There is a refactoring tool in IntelliJ-IDEA which allows me to extract a parameter object from a method.
This will do something like the following:
public interface ThirdPartyPoint {
float getX();
float getY();
}
Before:
class Main {
public static float distanceBetween(float x1, y1, x2, y2) {
return distanceBetween(x1, y1), x2, y2);
}
public static float distanceBetween(ThirdPartyPoint point1, ThirdPartyPoint point2) {
return distanceBetween(point1.getX(), point1.getY(), point2.getX(), point2.getY());
}
}
After:
class Main {
public static float distanceBetween(Point point1, Point point2) {
return Math.sqrt(Math.pow(point2.getX() - point1.getX(), 2) + Math.pow(point2.getY() - point1.getY(), 2));
}
public static float distanceBetween(ThirdPartyPoint point1, ThirdPartyPoint point2) {
return distanceBetween(new Point(point1.getX(), point2.getY()), new Point(point2.getX(), point2.getY()));
}
private static class Point {
private final float x;
private final float y;
private Point(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
}
Why is this any better than before?
Now, if I have to use this method, I need to create a new point object each time I invoke it. Whereas before, I could just use the primitive types.
My feeling is that method signatures should generally go in the opposite direction. For example, if you have some function that finds out how popular a name is like this:
public int nameRanking(String name) {
// do something with name
}
And you extract a parameter object like this:
public int nameRanking(Person person) {
// do something with person.getName()
}
Doesn't that make things worse? For example, what if, after creating the Person
class from the refactoring menu, I decide to remove the getName()
method because I don't want the name to be publicly available for all persons, but other classes used the nameRanking
function? Now I need to change my nameRanking function. If I used the built-in String class, I know that nothing injected into this function would ever change.