Setters vs Overloaded Constructors in Java

I am not sure if a similar question was asked before, they searched for it, but did not receive useful answers.

How does the question arise, which is better, having an overloaded constructor or having several setter functions?

Scenario:

public class Something {

    private int a;
    private int b; 

    public Something(int a, int b) {
        this.a = a;
        this.b = b;
    }
    ... // Do Something
}

Now my main requirement was to have only two parameters. Now tomorrow the requirement will be changed, and I will be asked to add a new parameter c, and then the next day d and give the statement that we can have more fields.

I already have a dependency for this constructor in several projects. Now back to my question

  • Is it advisable to add new fields to an already overloaded constructor?
  • Create a new overloaded constructor every time I need to add a new field so that I don't break the dependent code?
  • ( , ).

, ?

+5
4

- - , , - , , , , "" -.

+9

, , , , , , . , , , .

, : . , . , , Java , , , , , , , , .

+4

- . , , , . , api.

+1

Do your other 2-arg constructor-dependent projects affect the new options? Do 2-arg constructors make sense with your new requirements?

Perhaps you need to create another class, for example. SomethingEx(Something), which will carry additional fields and have different constructors, but will use useful methods.

If the useful exchange methods are small and very short, it might be better to create a completely different class, just to have fewer dependencies.

0
source

All Articles