Question

If a class have too many parameters in the constructor we can either use a structure or a builder pattern.

Which is better? Is there any good practice?

Was it helpful?

Solution

Use a class with structure that meets your need. Martin Fowler has one similar technique called DataTransferObject (DTO), in which you pass an object model instead of retrieving the data using multiple calls (persumably database calls), reducing the cost.

The benefit over builder pattern:

  1. The class structure has no additional logic, means it is easier to read (less logic)
  2. Do not create constructor doing real works code smell, again makes the code easier to read
  3. The operation is cheap, since you just passing the references and not creating a brand new object. Especially when the data structure is big.

The downside: The object is in mutable state.

OTHER TIPS

It would depend on what the parameters were and their relation to each other and how many are required vs optional.

If several parameters are related, it is usually better to create a separate class (or structure) to store those parameters.

For example instead of

TransferMoney(long srcAccountNumber, int srcAmount, Currency srcCurrency, long destAccountNumber)

We can see that src ammount and srcCurrency are related and we can create a new class to handle money of various amounts (and possibly add methods for converting to other currencies etc) and reduce the number of parameters:

TransferMoney(long srcAccountNumber, Money amount, long destAccountNumber)

This question is language agnostic, but if you had a language that doesn't support default values (like Java) then you might need to have several overloaded methods with different number and types of parameters to fit all possible combinations. If there are lots of combinations, then a Builder is a cleaner way to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top