Setters AND ( not OR or VS ) builder patterns

后端 未结 6 1048
一整个雨季
一整个雨季 2021-02-05 23:07

I have a situation where I use a builder pattern for constructing an object. Best example to give is the pizza code

public class Pizza {
  private int size;
  pr         


        
6条回答
  •  北海茫月
    2021-02-05 23:31

    Now lets assume a usecase where I need to update the cheese. That needs a setter.

    Rather than thinking of setters or builders, try to think of responsibilities of a class and services provided to users of the class.

    What you're calling a setter here is simply a service that transform an object. A builder is a service that creates a complex object.

    If you're providing setters to access attributes (or the details of a complex object that should remain secret to the client), you're breaking encapsulation. That's an anti-pattern. Your cheese example is not sufficient to reveal why that might be bad. Does a user need to know a pizza has cheese and be able to modify it?

    As JB Nizet said, there's no reason both services can't exist, but I'd ask the question whether revealing details is good or not.

提交回复
热议问题