Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement my own static Empty or Zero field properly

I have a class, this class can be empty. This class has only public properties of type String. When this class is in an empty state, that means that all properties have the value of String.Empty.

1) With a public static field, the properties of Class.Empty can be modified.

2) I don't see that a public static property getter should return a new empty object (set all fields to Empty manually) every time. I consider that bad practice.

3) An alternate solution is to implement your own Class.IsNullOrEmpty(Class obj).

4) A non-static public boolean property obj.IsEmpty.

In the other class where this class is being used, the property will never be null. The other class is returned from a method (of yet another class,) which properly initializes it.

The only case the property might be null, is if it's newed outside that method, which then causes it to be in an invalid state anyway.

like image 239
CS. Avatar asked Jul 31 '09 15:07

CS.


1 Answers

1 and 2 conflict, basically.

Either your type is immutable, in which case you can return a reference to the same instance every time... or it's mutable, in which case you have to return a reference to a new object each time.

The reason string.Empty is fine is precisely because string is immutable.

Does your type have to be mutable?

EDIT: Based on your comment, it sounds like the properties shouldn't have setters at all. Instead, the values should be passed into the constructor, and stored in readonly fields.

At that point your type is immutable, so you can expose either a public field or property which always returns the same value, i.e.

private static readonly MyType empty = new MyType("", ""); // Or whatever
public static MyType Empty { get { return empty; } }

or

public static readonly MyType Empty = new MyType("", "");

You don't need to worry about anyone setting any properties, because you haven't got any setters...

like image 63
Jon Skeet Avatar answered Nov 15 '22 01:11

Jon Skeet