Nick W Nick W - 6 months ago 22
Java Question

Explicit Constructor Invocation using 'this' as poor coding practice?

I was told by a Professor that explicit constructor invocation using

this
was "poor coding practice" and penalized for it. However, I haven't been able to find anything in any java style guide that I've looked through that comments on it one way or another. On top of that, it seems to be done in quite a bit of coding examples that I have seen. I was hoping to get some input on whether this is poor coding practice and why.

An example of what I am referring to:

public class SomeClass {

private int a;
private int b;

public SomeClass() {
this(0);
}

public SomeClass(int a) {
this(a, 0);
}

public SomeClass(int a, int b) {
this.a = a;
this.b = b;
}
}


EDIT:
His comment exactly was "One constructor calling a constructor of the same class is not good practice. A constructor creates an object, so calling a constructor that calls another constructor what is happening in memory? Something to thing about."

And this was the specific code:

public class Employee {
private String name;
private int monthlySalary;

// Default constructor
public Employee() {
this("", 0);
}

// Constructor
public Employee(String name, int monthlySalary) {
this.name = name;
this.monthlySalary = monthlySalary;
}

// annualSalary() method returns the annual salary of the employee as an int
public int annualSalary() {
return monthlySalary * 12;
}

// toString() method returns the employee name and monthly salary as a
// String in the format: name, monthly salary
public String toString() {
return "Name: " + name + "\t\tMonthly Salary: " + monthlySalary;
}
}

Answer

In general, using this to chain constructors is not bad style. It could be bad style in particular examples, but I would only be prepared to make that judgment based on the specific code. Artificial examples (e.g. the semantic-free example in your question) cannot be judged.

It may be that your lecturer has actually "pinged" you on a different issue; e.g.

  • creating a bucket-load of unnecessary / confusing / semantically muddled constructor overloads, or
  • not writing decent javadocs for the constructor overloads.

Both of these would (IMO) be bad style to the degree that they make your code harder to read and maintain.


It is arguable that when you chain constructors that you need to look at more constructors to understand what is going on. But the counter argument is that making all of the constructors (artificially) independent violates the DRY principle.

Comments