Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Calling constructor via constructor, what's the point?

Tags:

java

I see some people doing stuff like in the second constructor here:

public class Apples {

  String color;
  int quantity;

  public Apples(String color, int quantity) {
    this.color = color;
    this.quantity = quantity;
  }

  public Apples(String color) {
    this(color, 0);
  }

}

What are the reasons for doing so? To me it seems like you're invoking an additional method(the constructor) just in order to save a few lines. I recall a professor a few years back saying it's bad practice, but I don't remember his reasons for saying so.

like image 656
krystah Avatar asked Nov 27 '22 17:11

krystah


1 Answers

Computers today are so fast that invoking additional methods for the sake of readability and removing code redundancy is much more appreciative than having complex and duplicative code which no one can understand.

Programming is not just coding, but much more than that. You have to tell a story through your code to the people who will read your code. Clean code is the recommended way to go.

So if calling a constructor from another constructor is saving 10 lines of code, its much better. And compilers today are so smart that they will generate a very efficient byte/machine code for such scenarios.

like image 76
Aman Agnihotri Avatar answered Dec 21 '22 23:12

Aman Agnihotri