(Writers note: I apologize for this C#-related post. I’ll return to posting trivial and useless information, reviews, and links soon)
A post on one of our internal groups came up asking whether a class’s implementation should use properties on that class, or whether it should restricted to fields. There was a bit of discussion, with some replying “sure”, and others saying that you should always use properties.
Here’s my take on it. The discussion is about a class that implements lazy loading of a bitmap property named “Bmp”.
If you use properties for everything, you’re complicating the life of the code maintainer considerably. Instead of being able to trust that “bmp” has behavior that I understand (ie it’s a field), I have to go look at the definition of Bmp to see what’s going on.
In my book, that’s an example of premature generalization – you’re using a property *in case* you want to change things later. Premature generalization, like premature optimization, is something to be avoided. Or, as the agile guys would say, “You ain’t gonna need it” – you’re wasting time and bloating your class.
An exception to this is if you think you are going to version the class and client separately (ie you’re building a reusable library), and you wouldn’t be able to add in a property later.
If you use properties from inside your class when convenient – such as a lazy load of an bitmap – you’re still making things tougher on the maintainer – the difference between bitmap and Bitmap is pretty subtle, especially if you don’t have a naming convention for fields.
If you’re in that situation, I think it’s a far better solution to pull the lazy-loading code out of property and create a function named “GetBitmap()”, and use that function from inside the property and in other cases where you need the bitmap in your class. It’s more readable.