Are booleans as method arguments unacceptable? [cl

2019-01-16 02:48发布

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.

What's easier to understand?

file.writeData( data, true );

Or

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?

26条回答
你好瞎i
2楼-- · 2019-01-16 03:46

Where I do agree that Enums are good way to go, in methods where you have 2 options (and just two options you can have readability without enum.)

e.g.

public void writeData(Stream data, boolean is_overwrite)

Love the Enums, but boolean is useful too.

查看更多
仙女界的扛把子
3楼-- · 2019-01-16 03:48

I think you almost answered this yourself, I think the end aim is to make the code more readable, and in this case the enum did that, IMO its always best to look at the end aim rather than blanket rules, maybe think of it more as a guideline i.e. enums are often more readable in code than generic bools, ints etc but there will always be exceptions to the rule.

查看更多
登录 后发表回答