Search code examples
javamethodsparametersconventions

Dealing with Duplicate Method Headers


I'm new(ish) to coding, so let's get that out of the way. Also, I'm currently using Java. I want to instantiate a Line object in two different ways:

public Line(double x1, double y1, double x2, double y2){}//creates a line connecting two points and

public Line(double x, double y, double dir, double length){}//creates a line extending off of one point

However, they both have the same method header according to the compiler.

I considered adding a useless parameter to the second constructor, but that seems messy and unnecessary. Does anyone have any suggestions on how to deal with a problem like this one both now and in the future?

Note: This topic is only about fixing the header, not about how my code could be improved. Thanks!


Solution

  • You can create two different static factory method for both of those constructors calls. According to Wikipedia :

    The Factory Method design pattern is one of the "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

    The Factory Method design pattern is used instead of the regular class constructor for keeping within the SOLID principles of programming, decoupling the construction of objects from the objects themselves

    Factory methods are just essentially methods that can have different names (and not having to use the name of the class) and a different number of parameters or even the same number of parameters with a previous one. You can do something like this :

    public static Line createJoining(double x1, double y1, double x2, double y2){...}
    public static Line createExtending(double x1, double y1, double x2, double y2){...}
    

    Then you could have a single constructor like this

    public Line(double x1, double y1, double x2, double y2){}//creates a line connecting two points
    

    Inside createJoining() and createExtending(), you could call this constructor, and put your different program logic inside these two factory methods.

    createJoining() and createExtending(), would have to return a new instance of Line like this:

    public static Line createJoining(double x1, double y1, double x2, double y2){
      // program logic goes here, where you can do some calculations
    
       return new Line(x1, y1, x2, y2);
    }
    
    public static Line createExtending(double x1, double y1, double x2, double y2){
    // program logic goes here, where you can do some calculations
    
       return new Line(x1, y1, x2, y2);
    }
    

    Usage example,

    Line joinedLine = Line.createJoining(0.1, 3.5, 10.5, 1.0);
    Line extendedLine = Line.createExtended(0.6, 29.4, 20.0, 2.0);
    

    More info about Factory Methods here