Search code examples
javabuilder

Inline field initialization vs builder which is better


I have created a class with many fields, which I'd like to initialize most of them according to some default value while set few fields according to my needs in time. I come cross two solutions for this class.Inline field initialization and builder. Any comments? I know builder patter is popular, but why not just use default inline field initialization?

//Inline field initialization:

class foo{
    int a = 0;
    int b = 1;

    public foo setA(int a){this.a = a; return this;}
    public foo setB(int b){this.b = b; return this;}
}

//use foo
foo f = new foo().setA(1).setB(2);

//builder
class bar(){
    int a;
    int b;
    bar(int a, int b){this.a = a; this.b = b}
    public static class Builder(){
        int a = 0;
        int b = 0;
        public bar build(){
            return new bar(a, b);
        }

        public Builder a(int a){this.a = a; return this;}
        public Builder b(int b){this.b = b; return this;}
    }
}

// use
bar b = bar.Builder.build().a(1).b(2);

Solution

  • Builder pattern need to be considered when faced with many constructor parameters. Constructors do not scale well with large number of optional parameters.
    Refer: Item 2 in Effective Java http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2
    If the count of your fields will not increase to a large number then I will prefer to go with Inline field initialization as it means writing less code which is always good.