Jump to content

check if i have 2 logs in my inventory


blueshirt

Recommended Posts

Ya I guess so, but why waste a boolean on it?

Just put it straight in the condition? smile.png

We can look at:

if(hasTwoLogs)

without needing extra cognition to work out the 

getInventory().getAmount(...) == 2

in our heads. If we really care about how we determine we have two logs (which there is no reason to, unless there's a bug), we can look at the assignment, but now we aren't forced to; we are instead given an actual name to read.

 

It's a lot more useful when the condition has multiple expressions (|| or &&), but I still prefer it over placing the expression in the if statement. Slightly lowers the amount of thinking needed, as we can ignore the assignment (of the expression) without any confusion about the code.

 

Compilers will inline the value if they see it's effectively final (not modified after initialization), so there's no performance impact; it's just to make things easier to understand when it comes to reading the actual processing part. On top of that, worrying about such small changes should be avoided (micro-optimizations) as they can consume quite a bit of time over the course of a project, while giving no noticable performance boost. You should never pre-optimize anyways: always monitor your program AFTER writing it, to see where optimization is really needed :)

 

Keep in mind, that expression is a boolean, we are just storing it somewhere and giving it a name. Either way you do it, a single boolean is being allocated to the stack.

Edited by fixthissite
  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...