How to avoid code duplication in overloaded constructors?

Let's say that I have one constructor that accepts the input, and another that uses the default value. Both constructors then process this data in exactly the same way. (Example below.) What are my options for avoiding code duplication in this case?

(I read a post on how to reduce constructor overload code , where the top answer suggests using the keyword β€œthis.” In my case, I think I will need to use β€œthis” to call the first constructor from the second after the input has been saved. This results to compilation error: "calling this should be the first expression in the constructor.")

Code example:

public class A {
  public A(String a) {
    //process a
  }
  public A() {
    String a = "defaultString";
    //process a
  }
}

: (, , ). , :).

+3
6

init:

public class A {
  public A(String a) {
    init(a);
  }
  public A() {
    String a = "defaultString";
    init(a);
  }
  private void init(String a) {
    //process a
  }
}

PS: – , , .

+9

, , , - .

. . , ( ..) object ( string ).

, .

+4

:

public class A {
  public A(String a) {
    //process a
  }
  public A() {
    this("defaultString");
  }
}

, .

+3

, :

public class A {
  public A(String a) {
    //process a
  }
  public A() {
    this(JOptionPane.showInputDialog("a"));
  }
}
+1

, - - JOptionPane . , buildA , , .

public class A {
  public A(String a) {
    this.a = a;
  }
  public static A buildA(String input){
    if(input == null){
      input = JOptionPane.showInputDialog("a"); 
    }
    return new A(input);
  }
}
0

. .

Using this method, you can put the general code in the initializer block, and then leave different logic in the concrete constructor.

public class A {
  {
     //initializer block - common code here
  }
  public A(String a) {
    //constructor - specific code here
  }
  public A() {
    //constructor - specific code here
  }
}

This may not be ideal in all situations, but this is another way to approach a problem that I have not mentioned yet.

0
source

All Articles