简体   繁体   English

如何根据“清洁代码”原则处理按钮点击?

[英]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.

相关问题 如何检测在表视图委托方法中调用的UIActionSheet按钮的点击? - How do I detect the tap of a UIActionSheet button called inside a table view delegate method? 如何在视图中的任何位置检测到点击? - How do I detect a tap anywhere in the view? 如何更改此代码,以使其不违反MVC原理? - How can I change this code so that it doesn't infringe MVC principles? 如何在UICollectionView中处理后台点击 - How to handle background tap in UICollectionView 如何在UITextView中处理点击而不丢失默认的点击处理事件 - How to handle tap in UITextView without losing default tap handle event 我可以在UITabbarController中处理双击 - Can I handle the double tap in UITabbarController 如何让UIButton宣布双击语音提示? - How do I get UIButton to announce a double tap on voice over? UIPopoverController 在“点击关闭”时关闭 - 我如何检测此事件? - UIPopoverController dismiss on 'tap off' - how do I detect this event? 如果用户点击UIBarButtonItem,如何忽略点击? - How do I ignore the tap if the user tapped on a UIBarButtonItem? 如何在iPhone上检测到两根手指? - How do I detect two fingers tap on the iPhone?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM