I am creating a custom gesture recognizer, and my goal is to log movement above a certain threshold for the duration of the gesture, then report that data set at the end of the gesture. I’m a little fuzzy about the role that the gesture recognizer object plays.
As I am still a bit new to OOP, I am wondering about the best practice for MVC with this gesture recognizer. Specifically, should the gesture recognizer be “dumb” and only report movement to a view controller, and let the logic and logging happen in the VC, or is it just as fine to do light logic and logging in the gesture recognizer, then let it report back when the gesture is finished, and have the VC ask the gesture recognizer for the data.
Here is some sample code for what I’m currently prototyping (with the approach of having the logic and logging in the gesture recognizer):
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
if (self.state == UIGestureRecognizerStateFailed) return;
CGPoint nowPoint = [[touches anyObject] locationInView:self.view];
int xMovement = nowPoint.x - self.previousPoint.x;
int yMovement = nowPoint.y - self.previousPoint.y;
if (xMovement >= 0) {
// positive/no x movement, log points if x or y has movement above threshold
if (xMovement > MovementThreshold || yMovement > MovementThreshold) {
NSLog(@"Movement above the threshold!\nx: %f\ty: %f", nowPoint.x, nowPoint.y);
self.previousPoint = nowPoint;
}
} else {
// negative x movement
self.state = UIGestureRecognizerStateFailed;
}
}
I’d go the logging in the gesture recognizer object. I look at it this way.
If I ever want to use this gesture recognizer with logging anywhere else, what will I have to do? If your logging is in the view controller then you have to cut and paste that code. If the logging is in the gesture recognizer you just create a new instance of the gesture recognizer.
If I ever want to remove the gesture recognizer from this view controller, what do I need to do? Again, if your logging code is in the view controller it will be a lot more work.
Encapsulation tells me I want to keep my code in the gesture recognizer.
That said, your gesture recognizer doesn’t have to be a single object. It could be small set. One for the gesture recognizer itself, one for the act of logging and one for the storage of the data. It really depends on how complicated each task is. If each new data point is just adding a single number to an array, then it seems premature to break it apart, but if it’s data you are going to want to pass around independent of the gesture recognizer itself, then it might be better to break it out.
If you decide you made the wrong choice, that’s what re-factoring is for. 🙂