布尔值作为方法参数是不可接受的吗? [英] Are booleans as method arguments unacceptable?

查看:25
本文介绍了布尔值作为方法参数是不可接受的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事表示,布尔值作为方法参数是不可接受的.它们应由枚举代替.起初我没有看到任何好处,但他给了我一个例子.

A colleague of mine states that booleans as method arguments are not acceptable. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.

什么更容易理解?

file.writeData( data, true );

或者

enum WriteMode {
  Append,
  Overwrite
};

file.writeData( data, Append );

现在我明白了!;-)
这绝对是一个将枚举作为第二个参数使代码更具可读性的示例.

Now I got it! ;-)
This is definitely an example where an enumeration as second parameter makes the code much more readable.

那么,你对这个话题有什么看法?

So, what's your opinion on this topic?

推荐答案

布尔值表示是/否"的选择.如果要表示是/否",则使用布尔值,它应该是不言自明的.

Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory.

但是,如果要在两个选项之间进行选择,而这两个选项都不是明确的是或否,那么枚举有时会更具可读性.

But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable.

这篇关于布尔值作为方法参数是不可接受的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆