Design for object with optional and modifiable attributtes?

Posted by Ikuzen on Programmers See other posts from Programmers or by Ikuzen
Published on 2014-08-17T19:47:25Z Indexed on 2014/08/19 16:29 UTC
Read the original article Hit count: 285

I've been using the Builder pattern to create objects with a large number of attributes, where most of them are optional. But up until now, I've defined them as final, as recommended by Joshua Block and other authors, and haven't needed to change their values.

I am wondering what should I do though if I need a class with a substantial number of optional but non-final (mutable) attributes?

My Builder pattern code looks like this:

public class Example {
    //All possible parameters (optional or not)
    private final int param1;
    private final int param2;

    //Builder class
    public static class Builder {
        private final int param1; //Required parameters
        private int param2 = 0;   //Optional parameters - initialized to default

        //Builder constructor
        public Builder (int param1) {
            this.param1 = param1;
        }

        //Setter-like methods for optional parameters
        public Builder param2(int value)
        { param2 = value; return this; }

        //build() method
        public Example build() {
            return new Example(this);
        }
    }

    //Private constructor
    private Example(Builder builder) {
        param1 = builder.param1;
        param2 = builder.param2;
    }
}

Can I just remove the final keyword from the declaration to be able to access the attributes externally (through normal setters, for example)? Or is there a creational pattern that allows optional but non-final attributes that would be better suited in this case?

© Programmers or respective owner

Related posts about java

Related posts about design-patterns