In the book "Pragmatic Programmer," the authors suggest that all input to the method should be verified. This allows problems with the method to be caught at an early stage, and their sources are easily traceable.
In my Mac application, I achieved this by creating an Assert class. This class has several class methods. These methods determine if any precondition is met, and if not, an exception is thrown. A typical statement might look something like this:
-(void) setWidth: (int) theWidth { [Assert integer: width isGreaterThanInteger: 0]; width = theWidth; }
This works very well and significantly reduces the time I spent searching for errors. However, recently I noticed that some of the assertion methods are very useful as predicates. For example, my methods integer:isGreaterThanInteger:andLessThanInteger: and my stringIsNotEmpty: equally useful. To this end, I created a second Predicate class, which I populated with several of my more useful predicate methods. So I took the logic from the assert methods and moved it to Predicate , and then rewrote my Assert methods as follows:
if ![Predicate predicateMethod] throw exception
It turned into a nightmare for maintenance. If I change the name of the method name in Predicate , I must also change it in Assert to stay consistent. If I update the documentation for the Assert method, then I have to do the same with the Predicate method.
Ideally, I would like to restore the Assert class so that when a method is called on it, it intercepts the selector. Then the Predicate class can be checked to see if it will respond to the selector, and if so, the method is called on Predicate with the same arguments that were passed to the Assert method. If the Predicate method returns false, an exception is thrown.
Is there a way to do this in Objective-C?
Thanks.