I got into discussion with a friend on what is the best way to express boolean-like value in a C# initializer. Whole discussion was spurred by following piece of code (ok, not exactly this one, but similar enough):
var x = new FieldCollection(true);
This perfectly valid line has a magic boolean argument whose function is not immediately clear. Syntax-wise code is fine but readability does suffer. Neither one liked how this looked and we went into discussion about refactoring. First one was introducing an enumeration class:
var x = new FieldCollection(FieldDuplicate.Allow);
This is an usual approach to readability argument. Create an enumumeration that has (more or less) reasonable names and then use that as an argument. It allows for better readability at cost of a bit more coding.
But C# has something I find better. You can use named arguments to have greater visibility without any extra coding:
var x = new FieldCollection(allowDuplicates: true);
Maybe it is not as clean as a dedicated enumeration but I find it works for me. It doesn’t require any code changes inside of a class. It doesn’t require an extra enumeration declaration. And it works even when you don’t have access to code of a class. All that is needed is a bit of discipline upon calling code.
And programmers always have abundance of discipline… :)