Enforce Correct Usage By Wrapping Types: Have you ever written an API or a method and expected it to be used a cer… http://bit.ly/9AHp4a
In it, John tackles the problem of ensuring your code is used by other developers as you intended. He gives an example of a method that takes a date parameter that *should* be calculated using certain business logic. How do you prevent another developer from using this method and passing in a hard-coded date?
Normally, one might write up some documentation or add xml comments to the code describing how the method should be used, what parameters are needed, and so on. Of course, there’s no guarantee that those guidelines will be followed, if read at all. A second solution is to write a utility class that calculates the parameter using the correct logic (this is what I see most often). This is still no guarantee since it requires knowledge of the utility class’s existence and where to find it.
The better way, John writes, is to not accept primitive types at all! Instead, wrap the parameter in a data type that creates the needed type with the required business logic. This allows you to force the correct input instead of having to validate anything that might be thrown in.
For a simple code example and more ideas on where you might use this, check out his full post on elegantcode.