Android Studio错误地将条件标记为始终为真。

huangapple go评论61阅读模式
英文:

Android Studio falsely marks conditionals as always true

问题

I have a class that's intended to be subclassed. There's a variable and a method that looks at the variable:

protected int base = 10;

private void rebuildDisplay() {
    if (base == 10) {
        dealWithBase10YadaYada(X);
    } else {
        dealWithOtherBase(X, base);
    }
}

Android Studio flags the if (base == 10) statement with Condition 'base == 10' is always 'true'.

But here's the thing: even though base is always 10 in my class, my subclass will be changing base to other values. So base == 10 isn't always true.

Is there a way to tell AS to not make assumptions about protected or public variables? Should I disable this test entirely, and if so, how? Heck, should I be reporting a bug?

英文:

I have a class that's intended to be subclassed. There's a variable and a method that looks at the variable:

protected int base = 10;

private void rebuildDisplay() {
    if (base == 10) {
        dealWithBase10YadaYada(X);
    } else {
        dealWithOtherBase(X, base);
    }
}

Android Studio flags the if (base == 10) statement with Condition 'base == 10' is always 'true'.

But here's the thing: even though base is always 10 in my class, my subclass will be changing base to other values. So base == 10 isn't always true.

Is there a way to tell AS to not make assumptions about protected or public variables? Should I disable this test entirely, and if so, how? Heck, should I be reporting a bug?

答案1

得分: 1

这是一个问题(不是一个错误),因为它违反了封装原则,并将您的类实现与该变量绑定在一起。假设有一种更有效的方法来实现您想要的功能,而不使用 base;但由于用户依赖于 base,您无法更改您的代码,否则会破坏代码。

如果有需要,setBase() 方法的内部工作可以随时更改。

可能可以更改 lint 设置。

英文:

This is an issue (not a bug) because it goes against encapsulation and ties your class implementation to that variable. Say there was a more efficient way to do whatever you wanted without using base; You can't change your code because users rely on base, and it would break code.

A setBase() method could have it's inner workings changed if you ever needed needed them to.

There is probably a lint setting you can change.

huangapple
  • 本文由 发表于 2020年8月3日 08:41:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63222346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定