GrandPa
GrandPa

Reputation: 504

Best way to initialise fields in a Class without boilerplate code

I have a PivotModel class which I will initialise using the new keyword.

PivotModel pivotModel = new PivotModel()

When pivotModel gets initialised, all the dependant fields(model1, model2,cell1,cell2) should get initialised with new object but not to null. I wanted to initialise all the fields and the fields of dependant classes without using new constructor. I don't want to have boilerplate code.

If you have any standard practice of way doing it, post it here. I am also using lombok in my project.

public class PivotModel {
    @Getter
    @Setter
    private Model1 model1;

    @Getter
    @Setter
    private Model2 model2;

    private Model3 model3 = new Model3() -----> Dont want to initialise this way for these fields 
}

public class Model1 {
    private Map<String,Cell> cell1;
    private Map<String,Cell> cell2;
    private Map<String,Cell> cell3;
    ------ will have some 10 fields here
}

Upvotes: 1

Views: 385

Answers (2)

Basil Battikhi
Basil Battikhi

Reputation: 2668

It seems that you are using Lombok project in your java project you can add @Getter @Setter above your class Scope, Lombok also provides Constructor Annotation, so Just type above your class Scope @AllArgsConstructor so you class Should be like this

@Getter
@Setter
@AllArgsConstructor
public class PivotModel {
    private Model1 model1;
    private Model2 model2;
}

@Getter
@Setter
@AllArgsConstructor
public class Model1 {
    private Map<String,Cell> cell1;
    private Map<String,Cell> cell2;
    private Map<String,Cell> cell3;
}

Upvotes: 3

suraj singh
suraj singh

Reputation: 31

For initialization, I would recommended Builder Pattern.

//keep your initialization logic in builder class and use build()/create() wherever required. Let's say:
Class Pivot{
 // Note: this have only getters for members

 //inner builder class
 PivotModelBuilder{

   //Note: all setter will be part of builder class

   /**
     * method which return instantiated required object.
    */
   public PivotModel build(){
        return new PivotModel(this);
    }
  }
}
//access initilization code as:
PivotModel pivot = new Pivot.PivotModelBuilder().build()

Adding referral link: https://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html (You can search more about builder pattern and it's implementation online)

Limitations:

  • However, it's good way to initialize/create bean, but, you might find duplication of member fields in both Parent and builder class.

Upvotes: 2

Related Questions