1

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

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

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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.