SLaks.Blog

Making the world a better place, one line of code at a time

Clarifying Boolean Parameters, part 1

Posted on Monday, September 12, 2011, at 9:31:00 PM UTC

Have you ever written code like this:

public void UpdateLayout(bool doFullLayout) {
//Code
if (doFullLayout) {
//Expensive code
}
//More code
}

This pattern is commonly used when some operation has a “cheap” mode and an “expensive” mode.  Other code will have calls like UpdateLayout(false) and UpdateLayout(true) scattered throughout.

The problem is that this isn’t very obvious for people who aren’t familiar with the codebase.  If you take a look at a file you’ve never seen before and see calls like UpdateLayout(false) and UpdateLayout(true) scattered, you’ll have no idea what the true / false means.

The simplest solution is to break it out into two methods: UpdateComplexLayout() and UpdateBasicLayout().  However,  if the two different layout modes have intertwined code paths (eg, the code before and after the if above), this either won’t be possible or will lead to ugly duplication of code.

One alternative is to use enums:

public enum LayoutUpdateType {
Basic,
Full
}

public void UpdateLayout(LayoutUpdateType type) {
//Code
if (type == LayoutUpdateType.Full) {
//Expensive code
}
//More code
}

This way, the callsites are much more descriptive: UpdateLayout(LayoutUpdateType.Full).  This also makes it easy to add more update modes in the future should the need arise.  However, it makes the callsites much more verbose.  When used frequently, this pattern can lead a vast proliferation of enum types that are each only used by one method, polluting the namespace and making more important enums harder to notice.

Next time: Cleverer alternatives

Categories: parameters, C# Tweet this post

comments powered by Disqus