Working with obscure arguments without C# 4


From yesterday’s post, I’m sure you’re itching to switch to the latest and greatest in tooling and languages for all future projects, and might even be considering upgrading some of the systems you currently have around.


But if you’re supporting previous languages and runtimes, do not despair: the ‘obscure argument’ problem has been around for a while, and a number of solutions exist.


I really like to think of this as two different sides: you’re either the writer of the library / API, or the user of the library / API.


If you’re the writer, you should consider what the code that uses your library will look like. Sometimes you an change your method name to make things clearer. So if you have an object that can work either connected or disconnected from the network, consider the following.


// Poor readability.
void SetWorkMode(bool connected) { }

// Leads to hard-to-read code:
instance.SetWorkMode(true);

// Better readability through different method naming:
// (part of the argument names moves to the method name)
void SetConnectedMode(bool connected) { }

// Somewhat better:
instance.SetConnectedMode(true);


Another frequently seen approach is to use an enum, even if it only has two values. This often provides a much improved experience, and sometimes even allows for future extensibility that you may not have foreseen.


enum WorkMode { Connected, Disconnected };

// Declare:
void SetWorkMode(WorkMode mode) { }

// Use:
instance.SetWorkMode(WorkMode.Disconnected);


Of course this should probably end up looking like a property – this is just for illustration purposes.


Tomorrow, ideas on what to do if you’re consuming some API that presents this problem.


Enjoy!

Comments (0)

Skip to main content