英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论