Let's say I have a class Point
.
I want to give the user the tool to easily calculate the distance between 2 Point
s, 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?
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:
p1.distance(p2)
from the static utility method and put the calculation logic into the non-static method if you insist in keeping the static method (I would eliminate it). I would say there is good reason to ask "hey, I have got this point p1, give me its distance to p2". I fail to see how this gets any easier with a static method. You need to provide two Point
instances anyway, there is nothing you can do without instances, so why make it static in the first place?