SLLegendre
SLLegendre

Reputation: 750

How can I avoid writing many very similar setter methods?

I am working on a piece of code where the following applies:

  1. I need to instanciate a lot of similar objects within an instance of Class A
  2. Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A i.e. In class A:

        B b = new B();
    
        final SomethingA somethingA1 = new SomethingA("input1");
        b.setSomethingA();
    
        ...
        final SomethingB somethingB15 = new SomethingB("input15");
        b.setSomethingB15();
        ...
    
        final SomethingA somethingA23 = new SomethingA("input23");
        b.setSomethingA23();
    

Where all "somethings" inherit from the same class.

  1. The setter does nothing but:

    public void setSomethingX(somethingX){
    this.somethingX = somethingX; 
    }
    

I really do not want to write 23 setters that all do almost the same. Is there something like a multi-purpose setter?

The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. Apparently, this way of doing saves lot of work somewhere else (that I have no influence on). Also, as you can probably tell I am a novice developer.

Upvotes: 0

Views: 100

Answers (2)

Eugene
Eugene

Reputation: 120858

I'd use Lombok setter/getter for this.

A single annotation that would trigger the creation of those methods. The source code in your IDE will not be polluted with those setters and a lot easier to read.

There is a proposal for data classes, but not yet implemented FYI.

Upvotes: 2

alexey28
alexey28

Reputation: 5220

There are couple technics to reduce setters:

1) Create constructor with B as parameter

class A {

    private B b;

    public A(B b) {
        this.b = b;
    }    
}  

A a = new A(new B());

2) Use builder pattern (with lombok will be easy to implement):

@Builder // lombok annotation
class A {
    private B b;
}

A a = A.builder().withB(b).build();

3) Use factory method:

class A {

    private B b;

    public static A newInstance(B b) {
        A a = new A();
        a.b = b;
        return a;
    }

}

A a = A.newInstance(new B());

Upvotes: 2

Related Questions