Is Java cast boolean to int a good idea?

290    Asked by alexGONZALEZ in Java , Asked on Oct 6, 2022

Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/interpreters.

So I came across this question:

How do I convert a boolean to int in Python? Can I just do it(mybool)?

My response was to write:

1 if mybool else 0

My reasoning was that blindly "casting" to int would rely on the internal implementation of the compiler/interpreter. And who knows, if running through a different interpreter int(mybool) might return something else. Explicitly stating the value for a "truthy" value and for a "falsey" value will always yield the expected behaviour.

This is surely something which one can consider for most languages.

Am I too picky about this? I know that I have written int(mybool) myself in the past. And that question made me think: Was that okay? Given that this is a very common case, are the compilers/interpreters smart enough to do "the right thing" for bool -> int conversions?

Now, for the special case for duck-typing languages like Python, int(mybool) might certainly be a really bad idea, but other languages are a bit clearer on their typing.

Answered by Amanda Hawes

With other languages the situation is not so clear, but python happens to be specified in such a way that you can depend on it always casting to 1 and 0. Python's designers are some of the best with regard to the principle of least astonishment.

The issue is that python is relatively rare as a first language, and programmers transfer practices from other languages that become superstitions in the new language. If their first language was C++, they are going to be very nervous about Java cast boolean to int instead of using a branch, especially if python is more of a hobby language for them than something they use in depth.

Code is for humans to read more than computers. It's often less hassle to use a construct that works reliably across programming languages than to depend on in-depth knowledge of the specification of one language or creating a comment to that effect. It's the same reason we use parentheses in cases where operator precedence might differ between languages. It's less effort to read for multilingual programmers.

That doesn't mean we shouldn't try to write idiomatic code, just keep in mind your maintainers when either method will do.

Your Answer


Parent Categories