How to deal with 2 almost identical constructors

If I have 2 constructors in my custom class, and one of them takes an additional argument and does everything that the first does, but has only one additional line of code (and this extra line uses an additional argument), what is the best way to handle this without need to duplicate all the code in the first constructor?

Code example

public myConstuctor(int number, int number2){ int result = (number + number2); int result2 = (number2 - number1) //Etc //Etc //Etc //Etc } public myConstructor(int number1, int number2, int number 3){ int result = (number + number2); int result2 = (number2 - number1) //Etc //Etc //Etc //Etc int result3 = (result + result2 + number3) } 
+6
source share
4 answers

You can make the second constructor first:

 public MyClass(int number1, int number2, int number3) { this(number1, number2); 
+14
source

You can call another constructor and put all your logic in.

 public myConstructor(int number, int number2){ this(number, number2, 0); } public myConstructor(int number1, int number2, int number3){ int result = (number + number2); int result2 = (number2 - number1) //Etc //Etc //Etc //Etc int result3 = (result + result2 + number3) } 
+13
source

You can also use the builder pattern if the arguments get too much to control:

 MyClass obj = Myclass.set1(number1).setN2(number2).setN3(number3).build(); 

build() can call bulky constructors.

+6
source

Just use the first constructor method in the second constructor method, and then ... just add the new line needed in the second constructor method.

 public ClassName(arg1, arg2){ //etc } public ClassName(arg1,arg2,arg3){ this(arg1,arg2); //new line of code to deal with arg3; } 

And here it is :) a lot of time has been saved.

0
source

Source: https://habr.com/ru/post/951571/


All Articles