【问题标题】:Best Practice for Checking Dependent Variables Before or inside Method在方法之前或内部检查因变量的最佳实践
【发布时间】:2015-04-22 06:04:46
【问题描述】:

我想知道当您有一个变量需要在某个辅助方法运行之前进行检查时,最佳实践是什么。检查应该在调用者还是被调用者中完成?我看到两者都有好处。在调用者方法中(在调用帮助者方法之前)执行此操作的成本要低一些,但这会将检查放在开发人员的肩上,并且如果代码转手(它会这样做),某些东西可能会丢失。因此,这就是在被调用者中拥有它的好处。下面是我的意思的一个非常粗略的例子

public class TestClass implements TestInterface {

    private String dependentVariable = null;

    public TestClass(arg1) {
    }

    @Override
    public void init(String flag) {
        this.dependentVariable = flag;
        caller();
    }

    public void caller() {
        //do it here?
        if(this.dependentVariable != null)
            callee();
    }

    public void callee() {
        //or do the check here?
        // do stuff involving the dependentVariable...
    }

}

【问题讨论】:

    标签: java methods coding-style call


    【解决方案1】:

    您应该在init() 本身中处理这个问题。如果你的类行为依赖于这个变量,你不应该让你的类被初始化为null

    @Override
    public void init(String flag) {
        if (flag == null)
            throw IllegalArgumentException("Flag cannot be null");
        this.dependentVariable = flag;
        caller();
    }
    

    如果没有flag 是可以的,并且应该抢占callee() 的执行,它应该在callee() 本身内处理。

    public void callee() {
        if (flag == null) return;
        // do stuff involving the dependentVariable...
    }
    

    这是因为,随着代码库的增长,在调用 callee() 之前,您将无法检查 flag 是否在任何地方都被 null 检查。这也符合 DRY 原则。

    【讨论】:

      【解决方案2】:

      在您的示例中,将被调用者设为私有或至少受到保护是一个好主意,以尽量减少可能的滥用。在使用敏感变量之前进行这样的检查通常是个好主意,但在某些情况下,由于各种原因这不切实际或不可行。

      我会说我更喜欢在您的情况下检查callee

      【讨论】:

        【解决方案3】:

        最好检查被调用方法的内部。对象应保证一致的状态。下面的例子可以很容易地说明:假设你实现了一个 Money 类:

        public class Money {
            private final BigDecimal value;
        
            private Money(BigDecimal value) {
                this.value = value;
            }
        
            public static Money valueOf(BigDecimal value) {
                return new Money(value);
            }
        
            public BigDecimal getValue() {
                return value;
            }
        }
        

        合同规定货币价值必须为正。因此,如果您将责任转交给客户来检查用于构建 Money 的值是否为正,那么您就是在允许某人构建具有非正值的 Money,那么您的 Money 对象不再可靠并且代码更难维护.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-16
          • 2011-12-16
          • 1970-01-01
          • 1970-01-01
          • 2021-04-28
          • 1970-01-01
          • 2012-02-10
          相关资源
          最近更新 更多