I’m working on an assignment which involves making an RPN calculator. I am currently using class methods to check whether a string is an operation as below:
+ (NSSet *) noOpOperations {
return [NSSet setWithObjects:@"π", nil];
}
+ (NSSet *) unaryOperations {
return [NSSet setWithObjects:@"sin",@"cos",@"log",@"+/-", nil];
}
+ (NSSet *) binaryOperations {
return [NSSet setWithObjects:@"+",@"-",@"*",@"/", nil];
}
+ (NSSet *) operations {
/* surely there is a better way - is it possible to save this call and reuse it? Or what about having the objects register themselves so you can add operations more easily? */
return [[self noOpOperations] setByAddingObjectsFromSet:
[[self unaryOperations] setByAddingObjectsFromSet:
[self binaryOperations]]];
}
+ (BOOL) isOperation:operand {
return [[self operations] containsObject:operand];
}
I believe it would be better to implement a kind of function registry system to allow dynamic adding of operations from another location in the project, but I think it would require a class variable. Is there a better way to do this than how I am doing it now?
My Personal solution for situations like this:
I find it to be very straightforward and easy to extend.