mob*_*Dev 17 intellij-idea android-studio
在IntelliJ中运行lint时,我收到警告"布尔方法总是反转".我的代码库中有几个类似的警告.哪种基本的编码风格,我错过了吗?
public static boolean isBlueToothEnabled(){
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter != null)
return bluetoothAdapter.isEnabled();
return false;
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*enz 22
false
如果bluetoothAdapter
为null则尝试返回,否则返回输出isEnabled()
public static boolean isBlueToothEnabled(){
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null){
return false;
}
return bluetoothAdapter.isEnabled();
}
Run Code Online (Sandbox Code Playgroud)
阅读更多:
在"清洁法典"中,罗伯特·马丁写道,"否定词比正面词更难理解.所以,在可能的情况下,条件应该表示为正数."(Martin,[G29]).IntelliJ IDEA有三次检查,以帮助您保持积极态度.
https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/ (条目#4避免负面条件)
https://www.jetbrains.com/help/idea/2016.1/invert-boolean.html
Amr*_*mar 10
节省时间:总是否定布尔方法调用.没什么好担心的.
为什么会这样
如果我们有方法 foo()
boolean foo()
{
if(condition == true)
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
并且只被称为!foo()
,
class A
{
if(!foo())
do something;
...
if(!foo())
do something else;
}
Run Code Online (Sandbox Code Playgroud)
因为我们只打电话!foo()
而没打电话foo()
.
警告要求我们以foo()
积极的方式使用.
删除警告
通过反转方法foo()的返回值,
boolean foo()
{
if(condition == true)
return **false**;
else
return **true**;
}
Run Code Online (Sandbox Code Playgroud)
现在调用方法
class A
{
if(foo())
do the same thing;
}
Run Code Online (Sandbox Code Playgroud)
我必须说,在某些情况下,我认为这个警告甚至无法以合理的方式修复。以如下所示的代码为例:
boolean getInfo(Info info) {
// Retrieve some info that can fail so the function returns true or false
}
void func() {
Info info;
if (!getInfo(info)) {
// Failed; handle error, early out
return;
}
// Do stuff
if (!getInfo(info)) {
// Failed; handle error, early out
return;
}
// Do stuff
if (!getInfo(info)) {
// Failed; handle error, early out
return;
}
// Do final calculations
}
Run Code Online (Sandbox Code Playgroud)
遇到这样的情况该怎么办?将函数重命名为notGetInfo()
? getDesinformation()
?失败时提前退出函数不会导致括号树不断增长吗?
归档时间: |
|
查看次数: |
14657 次 |
最近记录: |