Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid constructor code redundancy in Java?

Tags:

java

I have the following class:

class Pair
{
    String car;
    Integer cdr;

    public Pair () {}
    public Pair (String car) { this.car = car; }
    public Pair (Integer cdr) { this.cdr = cdr; }

    public Pair (String car, Integer cdr)
    {
        this(car);
        this(cdr);
    }
}

The class contains two optional values and I would like to provide all possible constructor permutations. The first version does not initialize anything, the second initializes only the first value and the third initializes only the second value.

The last constructor is the combination of the second and third one. But it is not possible to write this down, because the code fails with.

constructor.java:13: call to this must be first statement in constructor
        this(cdr);
            ^
1 error

Is it possible to write the last constructor without any code redundancy (also without calling the same setter methods)?

like image 768
ceving Avatar asked Jun 18 '13 14:06

ceving


People also ask

Which block can be used to avoid redundant code?

The use of feature branches can help to prevent redundant code getting checked into the main code branch.

Can I have 2 constructors in Java?

Constructor Overloading - Multiple Constructors for a Java Class. A class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need.

What is Java code redundancy?

Code redundancy occurs when a character or group of characters in a code word can be partially or completely deduced from the remaining characters of the code word.


1 Answers

As a rule, constructors with fewer arguments should call those with more.

public Pair() {}
public Pair(String car) { this(car, null); }
public Pair(Integer cdr) { this(null, cdr); }
public Pair(String car, Integer cdr) { this.car = car; this.cdr = cdr; }
like image 104
Sebastian Redl Avatar answered Nov 04 '22 15:11

Sebastian Redl