1

In order to have tested more readable and easy to write I usually use the BuilderPattern in my value object. For example instead of writing this simple class in a standard way:

public class MyClass{

    private String myProperty;

    public void setMyProperty(String myProperty){
       this.myProperty = myProperty;
    }
}

I prefer to write it as follows:

public class MyClass{

    private String myProperty;

    public MyClass setMyProperty(String myProperty){
       this.myProperty = myProperty;
       return this;
    }
}

Could this approach has a bad effect on performance?

PatrickChen
  • 1,350
  • 1
  • 11
  • 19
Renato
  • 2,077
  • 1
  • 11
  • 22
  • Maybe this: https://stackoverflow.com/questions/1345001/is-it-bad-practice-to-make-a-setter-return-this helps – PatrickChen May 15 '20 at 04:15
  • @PatrickChen thank you, I tried to search something similar but without success. I will read it! – Renato May 15 '20 at 04:29

2 Answers2

0

Your code snippet is not about using the builder pattern (GoF/Bloch) it is only about using fluent mutators or chain setters. A common practice with no really performance impact.

Regarding builder you have the additional Builder-object. But directly elligible for garbage collection after the creation of the object.

So you may have some impact on memory-usage. But JVM is really optimized to handle this.

CodeScale
  • 3,046
  • 1
  • 12
  • 20
0

That is not a builder, a builder would be

public class MyClass { // My attrs are immutable now

    private final String myProperty;

    public MyClass(String myProperty) {
        this.myProperty = myProperty;
    }

    // don't add if you don't need
    public String getMyProperty() {
        return myProperty;
    }

    public static class Builder{
        private String myProperty;
        
        public MyClass build(){
            return new MyClass(myProperty);
        }

        public Builder setMyProperty(String myProperty) {
            this.myProperty = myProperty;
            return this;
        }
    }

    public static void main(String[] args) {
        new MyClass.Builder()
                .setMyProperty("MyValue")
                .build();
    }
}

It's not about performance, it's about to move the mutability on the Builders and make your models immutable: now you have setters only at builder level.

Andrea Ciccotta
  • 598
  • 6
  • 16