So my main class was getting quite large so I decided to encapsulate the drawing of displays to its own class.
Then, on the OnPaint event handler I call displayDrawer.Draw();
The only problem is that in order to draw something the method needs quite a few arguments.
For example, there are four boolean arguments specifying flags that affect drawing. Example: whether or not to draw at all (don’t draw if the file isn’t loaded), tints, which layers to draw, et cetera. Then of course there is the offsets that need to be passed. Depending on the offset of the horizontal and vertical scrollbars or the width and height of the display, the drawer needs to react accordingly.
The reason these all need to be passed is because the class does not have access to the form’s controls. I rather not make the controls public or provide accessors and I don’t want to pass the form either.
The obvious answer is to create either a class or struct filled with the values like this:
class Offsets
{
public int horizontal, vertical, displayWidth, displayHeight;
public Offsets(int horizontal, int vertical, int displayWidth, int displayHeight)
{
this.horizontal = horizontal;
this.vertical = vertical;
this.displayWidth = displayWidth;
this.displayHeight = displayHeight;
}
}
class DrawingFlags
{
public bool drawCurrentLayer, drawOtherLayers, drawDisplay;
public DrawingFlags(bool drawCurrentLayer, bool drawOtherLayers, bool drawDisplay)
{
this.drawCurrentLayer = drawCurrentLayer;
this.drawOtherLayers = drawOtherLayers;
this.drawDisplay = drawDisplay;
}
}
But is it all really worth it? These containers will only ever be used once in the program during that method call and then after that it’s just more lines of code to have to sift through. Should I just bite the bullet and accept that this one method call has a lot of parameters?
Note that if you’re just creating a class with public properties, but you are populating that class with a constructor that takes a dozen parameters, then you are just pushing the same method parameter complexity from one place to another, and you are adding more complexity by incorporating the properties. Only do this if you get a net gain.
For example, your class
can be modified to look like this:
and can be populated like this
This is more readable, because you are giving a name to each parameter. It also intellisenses.
Note that if you’re using C# 4.0, you don’t have to do any of this, as you have the benefit of named and optional parameters: