Primitive obsession is a developer’s reluctance to write small objects instead of using primitive data types. One such example could look like this:
// when I blog, I have no fantasy for function names
public long ShoesInStockByShoenumber( int shoeNumber )
{
var matches = from shoe in _datacontext.Shoes
where shoe.size == shoeNumber
return shoe;
…etc…
The parameter named “shoeNumber” is an integer, and, defies oop in that the function should really be named ShoesInStockByShoenumberAsInteger( … ) (yup, eww!)
What you really want is to objectify shoenumber:
public class ShoeNumber
{
// This is all we need for now
public int Size{ get; set; }
}
… you can quickly expand the functionality of the ShoeNumber class if and when you need to. One typical first could be to throw an exception whenver a value is given that could not possibly represent a valid shoenumber.
So:
Why should I bother with packaging small parameters like this into objects?
Answer:
Because it is semantically correct, because it is oop in practice and because it makes refactoring your code that much better. But, to me, most importantly:
Packaging your parameters into objects means you can save your functions from having to check them. Objects should be smart enough to validate themselves.
Dont be like me; avoid the obsessing with primitives, no variable is too small to be turned into an object. Overcome this, and a world of options will open up for your code.