Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing the number of arguments to a constructor

I am reading "Clean Code" and having trouble figuring out how to keep some of my functions (usually constructors) to their MAXIMUM of 3 parameters.

Often my objects need an awful lot of information to work - am I supposed to make a small constructor and then use mutator functions to give them all of the information? This doesn't seem any better than just using a big constructor.

As an example, I have a "MovablePatch" class. It lets the user drag a square around in a window. It needs a several parameters, including Radius, Color, Renderer, InitialPosition, and Visibility. Currently I collect all of these from my GUI and then call:

MovablePatch(int radius, Renderer* renderer, Color color,  Position initial, bool visibility) 

These are only some of the things that I need in this class. Can anyone suggest how else I might package this information to pass to the constructor? I don't see any obvious "break it into smaller classes" appearing here.

like image 913
David Doria Avatar asked Dec 29 '11 18:12

David Doria


People also ask

How do you reduce the number of parameters in a constructor?

One good option is to use a Builder pattern, where each "setter" method returns the own instance, and you can chain the methods as you need. In your case, you will get a new MovablePatchBuilder class. The approach is very useful and you can find it in many different frameworks and languages.

How do you fix constructors with too many parameters?

Using a builder can solve the issue of having to many parameters in a constructor when all the fields are not mandatory. It also takes away the problems with having multiple constructors for different purposes. Note that a builder still should have a constructor with the mandatory fields that always needs to be set.

How many arguments should a constructor have?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.


1 Answers

You could have

MovablePatch(Renderer* renderer, CircleAppearance circleAppearance) 

where CircleAppearance gathers the other info.

However, clean code and other books that generalize about what good code should look like, are aiming for 80 percent of the code out there. Your code seems to be "closer to the metal" than the typical LoB (Line of Business) variety. As such, you may run into places where certain coding ideals are not applicable.

The most important part is that you're thinking about it and trying to keep things nice and tidy! :)

like image 63
Adam Dymitruk Avatar answered Sep 22 '22 08:09

Adam Dymitruk