I’m creating a calculator class and I want to be able to extend it in the future. I can’t decide if I should have future classes subclass it, or if I should just have each extension be a new category. Which is the better option?
I can’t decide what the best way for someone to extend this calculator class, if I wanted to add on to it in the future. Should I have each user subclass it, or add a category of methods that they want to add.
What I wanted to do is if the user wants to define a new operation say “+*”, they could define it in a new category and give me a selector, so I could store all operations in a Dictionary and pick which method to compute the result.
For example,
SEL method = NSSelectorFromString (
@"plusTimesWithArgA:andArgB:";
);
[self performSelector:@selector(method) withObject:operandA withObject:operandB];
I would suggest using the Visitor pattern. Subclassing is the tightest form of coupling. Extending the class carries risk of overriding existing methods and creates a high amount of coupling.
With Visitor the pattern you can have a method that takes the id of an object that should have the an “operate” method. It can operate in any way as long as it takes the input and returns a result. This means you can implement unlimited operations with no knowledge of the rest of the calculator class.