开发者

Coding style, variable name

I have a method e.g. getSome(String param, boolean active). When I call this method I create a variable as shown below.

boolean active = true;

getFoo("some", active);     // To get active foo

g开发者_如何学PythonetFoo("some", !active);     // To get inactive foo

Is it worth create an extra variable or simply call getFoo("some", true);


If you have a boolean parameter, you should consider having two variants of the function instead. Having a boolean in the parameter doesn't help the user to read the code. To avoid duplication the actual implementation may contain a function with a boolean parameter but it can be hidden from the user of the API.

getSomeActive("foo")
getSomePassive("foo")

Another alternative is two use meaningful flags e.g. an enumeration instead of a boolean.

getSome("foo", FetchStyle.ACTIVE)
getSome("foo", FetchStyle.PASSIVE)

And to answer your question: having to declaring an extra variable for clarity just tells us that we have a problem in the interface. If you cannot alter the interface or wrap it then a variable is one way to document the intent. Unfortunately, someone else will probably just refactor the code and remove the variable at some later date.

Reference: Tip #12 in Clean Code by Uncle Bob


It depends, when someone else reads your code, are they going to think "Why did s/he put true there?". If the reason for putting true there is obvious then you should just put true there, otherwise, create a variable with a descriptive name so they can figure it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜