Last week my team member from Cambridge was reviewing my code; while he was going through a class he noticed a set-only property and told it is really bad idea to have one in the class. As we both kind of busy, he asked me to read the Property Design section from “Framework Design Guidelines” [ISBN: 978-81-317-2978-3] book.
Luckily I have copy of book, it is clearly mentioned in it that.
“DO NOT provide set-only property or properties with the setter having broader accessibility than the getter
If the getter cannot be provided, implement the functionality as a method instead.”
But it is nowhere in the book given the reasons not use it. So, here in this post I will try to list the reasons, why set-only properties are bad design practice.
It is quite obvious, if OO is meant to better represent the real world, a set-only suggest that our modelling is pretty off. Set-only properties are uncommon and properties are used to for dumb sets just to store a value without much processing.
If I can set a property on something but never get it, I will never know if something else changes/overwrites the value that I set. That could be a problem if I rely on the value that I set, and I am unable to persist it until the time that I would want to get it.
Using a method instead of a set-only property will be less confusing for a fellow developer. The name of the method usually indicates set or get, but property names don’t normally indicate that something can only be set and not be gotten. I suppose if the property were something like “ReadOnlyBackgroundColour” it would not be confusing to the other developers, but that would just look weird.
We can see lot of example of this in .Net framework; AppDomain has a method called SetCachePath instead of having a set-only property called CachePath. These small things may not feel important while writing code, but makes huge positive impact on readability and maintainability of code base.