I was watching a video regarding design patterns and the youtuber made an example of the builder pattern… I didn’t know about the pattern(there is a reason why I was watching the videos); But I had encounter the same type of problems so what I usually did was to return null to the fields I didn’t had their data.

Is it wrong what I was doing?

At the end the builder will make the object with a null data and realistically it takes the same amount of code…

@marsara9@lemmy.world
link
fedilink
English
71Y

So the builder pattern is supposed to solve the problem of: if you have a large number of optional fields that may or may not need to be set to construct your object. Then once the dev has called all of the setters that they require, they call build to fully realize that object.

Some rules that all builders should follow:

  • All setters SHOULD represent optional parameters. (Or ones that have a default value). If a parameter is required for all instances, include it in the constructor of the Builder itself.
  • All setters SHOULD return a copy of the Builder. This way you can chain calls off of each other.
  • Setters SHOULD do nothing more than store the provided value in a field local to the builder itself and then return itself (or a copy of itself).
  • You MUST expose a .build() method that will return the fully realized object. This method should essentially call the constructor for your target object using all of the parameters, regardless if a setter was called or not. Obviously any value where the setter wasn’t called will be null or some default value.
Create a post

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person’s post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you’re posting long videos try to add in some form of tldr for those who don’t want to watch videos

Wormhole

Follow the wormhole through a path of communities !webdev@programming.dev



  • 1 user online
  • 1 user / day
  • 1 user / week
  • 1 user / month
  • 1 user / 6 months
  • 1 subscriber
  • 1.21K Posts
  • 17.8K Comments
  • Modlog