Which one is more effective in building builders?

NOTE. All assemblers are for unit testing only.

So, I created the builders, and as I created them, I began to notice that some of the other developers, already in place, were following a slightly different pattern.

I think I'm asking which one is more effective.

My way to do this is:

public class Builder { public Builders() { SetDefaults(); } private void SetDefaults() { // Setting my defaults } } 

Another way that is in place:

 public class Builder { public Builder WithDefaults() { // Setting my defaults } } 

In my opinion, the first one is more effective because you just create your own builder and it automatically sets the default settings.

Otherwise, you need to explicitly call the WithDefaults method to set all the defaults before continuing.

The second seems more error prone since some objects that need to be built can throw a null exception if they do not have all of their fields.

Perhaps I missed something subtle here, so I decided to ask you a question about which one is more efficient to move forward.

Thanks.

+6
source share
1 answer

I would like to suggest a third option. Since the builder must reduce the amount of test code by eliminating the initialization of the object (s) in a clear and meaningful way - why do you announce that you are using the default values? It says nothing of its own about what the actual defaults are, and you run the risk of the script writer forgetting to call "WithDefaults."

Check out this post, for example, on how to do it.

Instead, use the constructor to set the default values ​​(fields that store them), and only change them if they are explicitly asked. This way you get an initialized object with minimal and meaningful builder calls.

0
source

Source: https://habr.com/ru/post/985612/


All Articles