Initialize class properties What principles do you have and how do you do it?

Asked 2 years ago, Updated 2 years ago, 58 views

Generator(){
    var1 = getVar1();
    var2 = getVar2();        
}

vs

Generator(){
    initVar1();
    initVar2();        
 }

iniVar1(){
    var1 = ...
}
iniVar2(){
    var2 = ...
}

You need to know var1 to get var2 What principles do you have, including these little things...

I'm getting worried when I write the constructor.

constructor

2022-09-22 13:49

1 Answers

If you have many fields to initialize, consider the builder pattern.

For simple cases

class Temp{
int x;
iny y;

public Temp(int x, int y){
    this.x = x;
    this.y = y;
}
public Temp(int x){
    Temp(x, null); // y is null or the default value
}

It's designed in the same way.


2022-09-22 13:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.