Boolean parameter passing - A coding standard?


The Framework design guides talk about choosing between boolean values and enums when passing as parameters to a method and offers this advice (§5.7.1, p150):

In general, you should favor using enums where it improves the readability of the client code, especially in commonly used API's. If using enums would add unneeded complexity and actually hurt readability or if the API is very rarely used, Booleans should be preferred.

The reasoning for this is twofold: it's more readable, as the quote states and enums allow your API to expand without breaking the contract of the method. However, there are times where you cannot replace the parameter with an enum, or there will never be another value other than true or false.

Readability is the real issue for me here as I think the extensibility element is easy to architect and deal with, however YMMV, consider this code:

public Customer GetCustomer(int id, bool isDeep){ ... }

This is all well and good - readable, but what about at the call site?

Customer c = GetCustomer(11209, true);

The true value might make sense while you're writing the code and while it's all fresh in your mind; there may even be other developers in your team that might understand what you're up to right off the bat, because it could be a standard convention or something similar - but what about that contractor you've hired for a week, that code you've outsourced to your Indian partners or the poor newbie on your team?

On possible solution is the approach recommended by Steve McConnell in Code Complete is the following:

bool isDeep = true;
Customer c = GetCustomer(11209, isDeep);

This is a very valid approach, but (and it's a BIG but in my view) requires discipline, code review and forethought on the developer side to be consistent and effective. If you can achieve this in your team then great, you should do it, no questions asked - but how about this as an alternative:

Customer c = GetCustomer(11209, true /*isDeep*/);

The downside to this approach, over the McConnell approach, is that this only works when you have the actual source code - not an approximation like when you use Reflector. Otherwise this additional information is lost, where it would be preserved by creating variables (well, only if the PDB is available for the assembly; otherwise you're in the same place as with the comments approach).

Let me know what you think?

No comments: