YADIW: properties

YADIW (you are doing it wrong) is a series of posts about some common code smells, and how to avoid them.

Properties are cool


public class YADIW 
    public int Identifier { get; set ;}

That’s easy, that’s simple, so easy and simple, that it is easy to just write all your properties like that.



Mutability vs immutability is always a hot issue. Are you having one of those endless boring days? Just raise this issue with another developer. You are welcome.

But, the thing is mutability is bad. Not only because mutability is by definition thread-unsafe, but because of the fact that mutable classes have, by definition, more than one state. And that’s bad because, when you are going to use one of those mutable objects, it just can be in the wrong state. Either you make sure that the state is correct (red flag, that means the abstraction is leaking) or just hope for the best and prepare for the worst.

In this case, when you need to read Identifier, you need to make sure that it has been set previously. Or prepare for obtaining a null value.

The solution

Make your class immutable. Like this:

public class YADIR 
    private readonly int id;
    public YADIR(int id) 
	this.id = id;
    public int Identifier
	get { return this.id; }

Now, it is imposible to create instances of this class in any temporary state. And thread-safety.

Final words

Sometimes, a little bit of extra code, after some careful consideration of what the language provides, saves a lot of code and a lot of headaches in the long term.

One Reply to “YADIW: properties”

Leave a Reply

Your email address will not be published. Required fields are marked *