Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No arg constructor or arg constructor

In my program I read a fixed length file, stored each string in a local variable, and then stored every value into a class type array list. For creating the object of an array list, I used argument constructor with all the variables. The below code demonstrates this.

String a = "text1";
String b = "text2";
SampleModel sm = new SampleModel(a,b);
ArrayList<SampleModel> sampleList = new ArrayList<>();
sampleList.add(sm);

I find this absolutely right but my colleague asked me to change it to a no arg constructor and call getters and setters instead. That would be like below.

SampleModel sm = new SampleModel();
ArrayList<SampleModel> sampleList = new ArrayList<>();
String a = "text1";
String b = "text2";
sm.setA(a);
sm.setB(b);
sampleList.add(sm);

Is there any reason to prefer a no arg constructor over argument constructor? (My program has around 15 variables)

like image 299
Nikitha Avatar asked Dec 25 '22 09:12

Nikitha


1 Answers

It depends on how the class will be used.

For example, an immutable class will need a constructor that takes arguments, and no setters.

But a Java Bean will need a no-argument constructor, and setters.

Some things to consider:

  • Encapsulation can be valuable. Other than special cases like JavaBeans, usually the interface of the class can be designed based on the desired interactions, not on the current set of data members.
  • Methods have names. Java does not support named arguments. Method names communicate how an actual parameter is being used, in the calling code. If your class has more than a handful of parameters, passing them via methods can result in more readable calling code.
  • Immutable classes have value. If you're adding named setters directly in your class, it won't be immutable. The builder pattern allows you to accept construction parameters even for immutable classes.
like image 110
Andy Thomas Avatar answered Jan 10 '23 11:01

Andy Thomas