Saturday, January 8, 2011

Setters and Getters

Every Java or C# developer knows how getter/setter methodes make the code messy and noisy because you have to define them explicitly in those languages. I just like the idea of using annotations to reduce amount of the code that should be written. Objective C has defined an annotation to define getter/setter methods implicitly. See below example:


@interface SimpleCar : NSObject {
NSString* make;
NSString* model;
NSNumber* vin;
}

@property(readwrite, retain) NSString* make;
@property(readwrite, retain) NSString* model;
@property(readwrite, retain) NSNumber* vin;

@end


The implementation:

#import "SimpleCar.h"

@implementation SimpleCar
@synthesize make, model, vin;
@end

There is no sign of setter/getter methods however, they actually will be accessible during runtime. This is the most clear implementation that I've ever seen. Interface is more declarative.

No comments:

Post a Comment