Search code examples
oopdesign-patternslanguage-agnostic

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.


Solution

  • 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! :)