Skip navigation

Category Archives: api

When you are designing a .NET class, always, always use properties.

Don’t create them just as a public accessor.  Wrap 100% of your fields – 100% of which should be private – in properties, even if the property itself is also private.

You should never refer to the field except inside the encapsulating property (including the constructor!  Use the property there, too!).

Before I even begin to point out why you should, I’ll address the immediate knee-jerk reasons why you’ll tell me I’m wrong.

1.  It’s a waste of time.  If you think this is true, you haven’t used Visual Studio long enough.  Right click on your private field and select Refactor, then select Encapsulate Field.  Done.

2.  It bloats the code.  If you think this is true, you haven’t used Visual Studio enough.  Click on the little bordered minus sign in the margin of your code to collapse the property.  You’ve added exactly 1 line to your class definition.  Woe is you!

3.  It’s inefficient.  In practically every place you use them, the C# compiler inlines them.  You were saying?

 4.  It’s non-intuitive from an API consumer’s perspective.  If you don’t have access to the member’s fields, then all you see are properties, which are actually more intuitive because the rest of .NET is written that way.  If you can see the member’s fields and you are following the “everything is private” rule, then you have access to the source code.  If you have access to the source code, then who wrote it, and why are you confused?  Plus, if your team is operating under these guidelines there’s actually less confusion, not more – the confusion would stem from finding a field that doesn’t have a property.

5.  If I make a public property for a field, I don’t want the set to be public, so I don’t include a set on the property and therefore must refer to the field internally.  You need to brush up on your C# – split protection level properties have been around since .NET 2.0.  It’s perfectly legal (although not as common as it should be) to declare a property as:

public string MyString{    get { return _myString; }

    private set { _myString = value; }

}

6.  It’s pointless.  If you have a private field and a corresponding private property that isn’t any more sophisticated than the Studio-generated encapsulator, then why bother?  I’ll get to that in a minute.

Can you think of any more?  I can’t.

Now, let’s discuss why it’s seriously advantageous to always use properties:

1.  Code safety.  When you are in the habit of always using properties, you always have the opportunity to inject logic surrouding the set and get logic of all the fields, which means part of the natural thought process during design is, “what should I do about nulls?” (among other things).  Once you create the property and you see that you have a method rather than just a field definition, you can surround the field with protective code that will ensure, for example, that if null is passed as the value parameter of your mutator, you don’t replace a list that is by definition always non-null with a null value – instead of assignment, you call the list’s Clear method.  This leads to measurable decreases in exceptions, most of which are hard to trace.

2.  Extensibility.  One of the major advantages of using properties is the ability to allow the data members to also be extensible in derived classes.  If you have a property that returns an IDictionary and your subclass wants to provide a different implementation (Hashtable vs. Red/Black tree, for example), you can override the property.  This is still possible with fields if you defined your field to be IDictionary instead of Dictionary (a rarity amongst most programmers), but it is trivial to come up with examples of times when you would want to be able to redefine the return value of a boolean property, for example.  The base class might just return a bool field, but if they wrapped it in a protected property, the subclass could return the result of a comparison instead of the field (or and it with the field) and the rest of the base class code (which also refers to the property instead of the field) doesn’t change.

3.  It’s so much easier to maintain.  If you use properties exclusively, you only have one “Find All References” search to do to see where your data is being used or manipulated.  If you use a mixmash of the field itself and its encapsulating property, you have to search in two places.  You are never sure if someone is going to use the property or the field so you have to check both, which makes everything you do harder.

4.  It’s so much easier to debug.  I could be accused of not using Studio again here because it is possible to set a breakpoint on a field so that if its value ever changes, your execution breaks and you can see the callstack.  I don’t know about you, but navigating to the property and hitting F9 on get{} and set{} takes me about 1/10th the time of setting up a conditional breakpoint on the value of a field.  If you always use properties everywhere, both internally and externally, and you are wondering “hmm, where does this get changed?”  just pop a breakpoint on the property’s set and reproduce.  It’s just that simple.

I’ll say it again: always use properties.

Advertisements

One of the biggest problems of the concept of null in modern programming languages is the choice API designers have to make between returning null or a conceptually empty object, for example string.Empty or new List<Type>();

On one hand, null is the obvious choice because it prevents wasting resources.  Creating an empty list each time a call returns no results is wasteful.  This can be averted by creating a static empty singleton (like string.Empty), but unless the object is immutable (as string is, or returning a ReadOnlyCollection) you can run into trouble here since the caller can modify the result.  Even this is wasteful when what you’re really trying to say is: “hey, I have no results to return.”  That’s what null means, isn’t it?

On the other hand, for the consumer of an API, even when the API author and the consumer is the same person, it’s hard to guess whether a method will return null or an empty object.  Even the .NET API authors struggle with this fact as evidenced by the string.IsNullOrEmpty static method, which is great for argument and return checking.  Since it’s hard to guess, most good programmers are in the habit of always checking for null first even when they know that the method will never return null because they wrote it.

The reason good programmers check for null religiously is because things change.  You may not be returning null today (in favor of an empty list) but tomorrow you may change your mind.  The problem with an API designer changing his mind is that he can’t predict whether or not the consumers of his API are properly checking for null.  As I said, good programmers will.  But what about the bad ones?

In my opinion, you should generally always return null instead of an empty object except with strings.  The reason for this is that it forces even the average programmer to check for null immediately.  A simple negative unit test will result in a a NullReferenceException.  There is no harm in returning null in version 1.0 and then changing it to return an empty object in version 2.0 but the reverse is deadly, because it has the potential of breaking all your consumers.  Checking for null is benign.  Making the assumption that the result of a method will never be null is an exception waiting to be thrown.

The exception to this rule for strings is because of the string.IsNullOrEmpty method.  Good programmers should rarely check strings of being null or empty independently.  Good APIs do not distinguish between the two in the majority of cases.  In some cases, null is different than empty – for example, in a login form, an empty string means an empty password, but a null password may imply an error occurred somewhere (or may imply integrated security, for which a password is unnecessary).  But generally, this distinction should be obvious from the context.