[英]How do I handle a button tap according to Clean Code principles?
I have the following, seemingly simple piece of code handling button taps in an iOS application: 我在iOS应用程序中有以下看似简单的代码处理按钮点击片段:
- (IBAction)tapKeypadButton:(UIButton *)sender {
NSString *buttonLabel = sender.titleLabel.text;
if ([buttonLabel isEqualToString:@"<"]) {
[self _tapBackButton];
} else {
[self _tapDigitButton:buttonLabel];
}
}
To completely follow the Clean Code principles by Robert C. Martin, would I need a ButtonTapFactory or something in the same line? 为了完全遵循Robert C. Martin的“清洁代码”原则,我是否需要ButtonTapFactory或同一行中的东西?
You have two types of buttons, with different behaviors (back button and digit button). 您有两种类型的按钮,它们具有不同的行为(后退按钮和数字按钮)。 To make this code clean, you should have two actions for each type.
为使此代码清晰,每种类型应该有两个动作。 The type should not be determined by the contents of the text inside the button, but through a semantically meaningful way.
类型不应由按钮内文本的内容确定,而应通过语义上有意义的方式确定。 (ie subclass).
(即子类)。 Further, an action method should only contain a call to another method that does the actual logic.
此外,操作方法应只包含对执行实际逻辑的另一个方法的调用。 Everything else is not testable.
其他所有内容均不可测试。 In code:
在代码中:
- (IBAction) tapBackButton:(id) sender
{
[self _tapBackButton:sender];
}
- (IBAction) tapDigitButton:(id) sender
{
[self _tapDigitButton:sender];
}
This way you can have unit tests calling your methods without your UI code interfering. 这样,您可以让单元测试调用您的方法,而不会干扰UI代码。 Please also note that I removed the label from the call to
_tapDigitButton
. 另请注意,我从
_tapDigitButton
的调用中删除了标签。 The digit should not be parsed from the label, but be passed in a more semantically stable way, for example using the tag
property. 不应从标签中解析该数字,而应使用更加语义稳定的方式(例如,使用
tag
属性)进行传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.