Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot understand this programming style

Can someone explain to me what this line of code means and whether it is good practice?

It seems to me that it is trying to assign one or another value to a boolean, but it is not clear.

   myBoolVar = isC || isP || isX;
like image 287
brillox Avatar asked Nov 05 '12 13:11

brillox


People also ask

Why is it hard for me to understand programming?

No, coding is not hard to learn. However, like anything new, it's not easy to start, and how difficult a time one has with learning to code will vary across a number of factors. The point is, learning to code isn't impossible; or, it's not as impossible as it might seem when it comes to getting your kids involved.

What do you mean by programming style?

A programming style is a set of guidelines used to format programming instructions. It is useful to follow a style as it makes it easier for programmers to understand the code, maintain it, and assists in reducing the likelihood of introducing errors.

Is it normal to struggle with programming?

Struggling to learn code is completely normal and expected. Most beginners go through at least one rough patch (and often several) while they're learning to code, but the good news is that a lot of these rough patches involve similar obstacles.


1 Answers

The || operator represents a conditional OR.

myBoolVar will be true if any of isC, isP, or isX is true.

It is similar to the | operator between boolean operands except that if the left-hand-side evaluates to true, the right-hand-side will not be evaluated.

As to whether it's good practise, consider a more verbose semantic equivalent:-

bool myBoolVar;

if (isC)
{
  myBoolVar = true;
}
else if (isP)
{
  myBoolVar = true;
}
else if (isX)
{
  myBoolVar = true;
}

In particular, consider which one you would prefer to maintain. For the most part, I would expect that folks consider the terser myBoolVar = isC || isP || isX; to be more readable.

I see from the comments below that you make an argument about programming being about simplicity and not about "showing off". I agree that programmers often try to compact or deliberately obfuscate code for their own satisfaction - often to the detriment of the project. This is probably not one of those cases. I might name the variables more clearly and I might encapsulate it behind an appropriately-named property, but I'd definitely use the a || b || c construction over something more verbose.

If you feel you have a clearer way to express it, share it with us and we can discuss it.

like image 88
Iain Galloway Avatar answered Oct 13 '22 13:10

Iain Galloway