marsara9@lemmy.worldtoProgramming@programming.dev•[help]Question regarding Builder design patter.English
7·
1 year agoSo 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.
Not saying a tool like this isn’t helpful for you but personally I don’t think I’d ever trust a service to analyze my code and provide accurate comments. There’s so many little quirks and ultimately nuance in what is written vs what and why it’s doing it that I’d never expect anyone but the original author of the code to get it right.