chris carter's web log

Home |  Contact |  Admin
 

Enum Versus Boolean

Posted on August 20, 2008

I've been in discussions in the past about this one.  Let's say you have a method signature, and one of the parameters to the method can either be true or false.  What Type do you use? Boolean? seems simple enough.  But it's becoming increasingly annoying to have to discover boolean values in method signatures.

Recently I created a method with a signature like this:

IEnumerable<T> OrderBy(string propertyName, bool sortAscending)
1

Using the above signature, my client code looked like this:

myRepository.OrderBy("FirstName", true)
1

Reading that code kinda makes sense, but that true as the second arg is a mystery.  What's true?? Intellisense tells me, but only after I put effort into this; effort I don't want to have to put in when I'm reading code.  So I went back and changed it to this:

IEnumerable<T> OrderBy(string propertyName, Sort sortDirection)
1

Where Sort is an enum that looks like this:

public enum Sort {
  Ascending,
  Descending
}
1
2
3
4

What's the difference? When I'm skimming code, this:

myRepository.OrderBy("FirstName", Sort.Ascending)
1

is more readable than this

myRepository.OrderBy("FirstName", true)
1

I guess it depends on what you're building, but I like the more readable look rather than the other, at least if I'm publishing the interface.

Comments

Tobin Harris

Totally agree, I use enums almost always these days. Don't like the loss of information you have with boolean parameters. Langauges that support named parameters give more scope to get around this problem without so many enums:

myRepository.OrderBy(Property=>"FirstName", SortAscending=>true); 

Even so, for sorting an Enum is nicer (Ascending, Descending, None);

Chris

Huh... That's gives me an idea...

Post a Comment

(required)
(required)
(no HTML!)