1

It is correct to write the same method PublicMethod of this example as static and non-static i? Is there some effect on performance invoking the non-static method or the compiler will optimize the code?

public class MyClass
{
  private double y;
  private double PrivateFunc(double x) { return some_operation(x,y);}

  public static double PublicFunc(MyClass A, double x)
  {
      return A.PrivateFunc(x);
  }

  public double PublicFunc(double x)
  {
      return MyClass.PublicFunc(this,x);
  }

  /* instead of repeating code of the static method
  public double PublicFunc(double x)
  {
      return PrivateFunc(this,x);
  }
  */
}
Ozzy
  • 304
  • 3
  • 15
  • 1
    Calling a method is so fast you will never see a difference. It is more about readablity. Think about why you need the static or non-static method. Is it really necessary to have both? – FCin Mar 31 '18 at 10:48
  • The code you have written is nothing but recursively calling itself. This code is of no use. When you call MyClass.PublicFunc it is going to be in infinite loop and throw StackOverflowException... Did you try this code? – Chetan Mar 31 '18 at 10:49
  • You first need to learn about static method and class method. And why they should be used. If static method were the solution, OOP wouldn't have been in place. – Chetan Mar 31 '18 at 10:50
  • @ChetanRanpariya Although I disagree with how it's implemented, but it's not recursively calling itself. It's calling the other static method, and it wouldn't throw a `StackOverflowException`. – 41686d6564 stands w. Palestine Mar 31 '18 at 11:06
  • @AhmedAbdelhameed agree with you. I missed the `PrivateFunc` and `some_operation` methods. – Chetan Mar 31 '18 at 11:14
  • @FCin if you have to implement a mathematical model with recursive or iterative invocation of a function, then the difference is important. – Ozzy Apr 13 '18 at 06:45
  • @Ozzy No, it is not. – FCin Apr 13 '18 at 06:49

1 Answers1

1

Yes, sometimes it's convenient to have a static and a non-static version of a method. string.Equals() is an example although the static and the non-static versions of this method don't share the exact same implementation.

However, why do you think you need a private version of the method in this case?

You can simply implement it without the private method, something like this:

public class MyClass
{
    private double y;

    public static double PublicFunc(MyClass A, double x)
    {
      return A.PublicFunc(x);
    }

    public double PublicFunc(double x)
    {
      // The actual implementation.
      return some_operation(x, y);
    }
}