简体   繁体   中英

Builder pattern VS my implementation

I had to build a logging dll assembly that will use a large amount of optional parameters, around 20 of them. It was written in c#.

What I end up doing was let my logging class to accept an object of type "log". This "log" class contains all the needed parameters and the corresponding properties to Get/Set them. All of the parameters were of course initiated with default values first.

Once passing the "log" object to my main logging class, it then extract the values from that "log" object and perform the printing to file.

My question is - should I change it now to the builder pattern? (I just now learn it in - "Effective Java 2nd edition" book).

I can see the advantages of this pattern against calling Ctr/Methods with a billion parameters but I also think that passing in a new object that contains all parameters is not bad.

Can you explain if I really should change my design and why?

Since this is a design question I did not provide any code input. If I need to post some code let me know.

There is no compulsary rules for using design pattern. But it makes life simpler if applied to correct usecase.

You can definitely use Builder pattern in your case. Here are some guidelines:

  1. First decide how many of the attributes of the Log object are mandatory (say x number), and how many of the attributes are optional (y).

2.Remove the y attributes from log object and put that in your Builder class through "add" methods.

  1. If x<6 , remove the x attributes from log class, put them in the constructor of your Builder class. Now you can get rid of the Log class itself.

  2. Else, if x>=6, keep them in the log class and pass the class in the constructor of your Builder class. This is also called "Transfer Object".

you can change the deciding number 6 as you wish. Usually a constructor containing 6 or more paramters becomes less readable.

Do you have a constructor with many arguments, where many of them are of the same type? Go Builder.

Do you have many constructors, where the difference between them is minimal? Go Builder.

Do you have a class initialized where one constructor calls another constructor, following a chain-like structure? Go Builder.

Otherwise, do your own thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM