Last Updated: February 25, 2016
·
560
· michaelmorrison

Create properties with a sane default state

When creating properties, always name them in such a way that false/FALSE/NO is the default value. This is important in case a property isn't explicitly set - you want its default value to still make sense. For example:

@property (nonatomic, getter=isNotLoaded) BOOL notLoaded;

So if you have some kind of data class with this property and you don't set it, it will default to 0 (false/FALSE/NO). Logically, that means not-notLoaded...or loaded! Nobody likes a double-negative, especially when it wrongly indicates that unloaded data is loaded.

A better approach is to name the property so that the zeroed state is still accurate, like this:

@property (nonatomic, getter=isLoaded) BOOL loaded;

Now you have a default state that means not-loaded, which makes a lot more sense in the zeroed state. I know what you're thinking...duh, this is so obvious. And you're right, but I've seen very experienced developers screw it up on occasion, myself included.

Here's one more example that's maybe not quite as intuitively obvious:

@property (nonatomic, getter=isVisible) BOOL visible;

A property called visible seems reasonable until you think about its default state of false/FALSE/NO, which means not-visible, also known as hidden. Unless you truly want hidden as the default state, it's better to call the property hidden (as Apple did in UIView):

@property (nonatomic, getter=isHidden) BOOL hidden;

Now the default (zeroed) state means not-hidden, or visible, which is likely the default visibility state you'd want for objects with this property.

One more thing, it's not always safe to assume that unset variables will be zeroed out. Instance variables (including properties), global variables, and static variables are automatically zero-initialized but local variables are not. So be careful what you assume.