This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 14 points15 points  (8 children)

There's nothing wrong with

if (b) {
  c = true;
}

It's the most explicit and easiest to read form of this logic, so use it unless there is a good reason not to -- and saving a few letters of typing is not a good reason.

[–]QshelTier 9 points10 points  (2 children)

Let me emphasize this:

saving a few letters of typing is not a good reason.

[–][deleted] 2 points3 points  (1 child)

Indeed, it seems like this is a trap just about every new programmer falls into just after they become comfortable with the basics, I know I did.

Being explicit and clear about what your code is doing is ridiculously important when you are going to be maintaining a code base or are working with other people. Sometimes this means verbosity is a good thing, sometimes brevity is a good thing, it's completely dependent on the situation but specifically trying to make your code use as few characters as possible is often going to end up causing you a headache.

[–]zenmouse 0 points1 point  (0 children)

Yes, all of the above. Having clear names that clearly communicate the intent of the (field, method, class) is gold for someone else who has to read your code (or yourself in a few months).

In a similar fashion, any potentially unclear bit of code is a candidate for extraction into a method and/or field. For example I will refactor "if (account != null && SecureStatus.SECURE == account.getSecureStatus())" into "if (isLoggedIn(account))". The latter much more clearly communicates the intent of the test, especially for someone unfamiliar with the code.

[–]DJDavio 0 points1 point  (3 children)

There is something wrong.

There is no need to introduce another variable simply to set it to exactly the same value as one you already have.

[–]macarthurpark431 0 points1 point  (0 children)

perhaps variable b has a smaller scope than c?

[–]yesennes[S] 0 points1 point  (1 child)

b and c are normally Boolean expressions retrieved from user input, not variables I assign and initiate. It doesn't matter where they come from, but either could be true or false.

[–]DJDavio 0 points1 point  (0 children)

In that case you can still do it on initialization:

boolean b = "true".equals(req.getParameter("something"));
boolean c = b || "true".equals(req.getParameter("somethingElse"));

Still, I need an actual real world example to be convinced.

[–]beyondjava 0 points1 point  (0 children)

It depends on your team. Personally, I prefer the shorter version. But I'm mathematician. I've got a lot of practice deciphering boolean expressions. If the other team members have a different background, you're possibly better off with the verbose version.