javastatic-methodsclass-designinstance-methods

Use static method inside instance method of the same class


Let's say I have a class Point. I want to give the user the tool to easily calculate the distance between 2 Points, so I write the method:

static float distance (Point p1, Point p2)

Now, I also want to give the user the tool to directly calculate the distance between one Point he already instanciated and another Point:

float distance (Point p)

Is it a good idea to use the static method distance(Point, Point) inside the instance method distance(Point)? Something like:

float distance (Point p){
    return Point.distance(this, p);
}

This way I would reuse the code.

If it is a bad thing to do, why should I avoid this?


Solution

  • Many people have debated about the general pros and cons of static methods with regard to testability, much of it I agree with. So I am not going to elaborate on that but just answer your question: