.NET: bool vs enum as a method parameter
Posted
by Julien Lebosquain
on Stack Overflow
See other posts from Stack Overflow
or by Julien Lebosquain
Published on 2010-05-25T22:06:19Z
Indexed on
2010/05/25
22:11 UTC
Read the original article
Hit count: 184
Each time I'm writing a method that takes a boolean parameter representing an option, I find myself thinking: "should I replace this by an enum which would make reading the method calls much easier?".
Consider the following with an object that takes a parameter telling whether the implementation should use its thread-safe version or not (I'm not asking here if this way of doing this is good design or not, only the use of the boolean):
public void CreateSomeObject(bool makeThreadSafe);
CreateSomeObject(true);
When the call is next to the declaration the purpose of the parameter seems of course obvious. When it's in some third party library you barely know, it's harder to immediately see what the code does, compared to:
public enum CreationOptions { None, MakeThreadSafe }
public void CreateSomeObject(CreationOptions options);
CreateSomeObject(CreationOptions.MakeThreadSafe);
which describes the intent far better.
Things get worse when there's two boolean parameters representing options. See what happened to ObjectContext.SaveChanges(bool)
between Framework 3.5 and 4.0. It has been obsoleted because a second option has been introduced and the whole thing has been converted to an enum.
While it seems obvious to use an enumeration when there's three elements or more, what's your opinion and experiences about using an enum instead a boolean in these specific cases?
© Stack Overflow or respective owner