Jump to content
Mike Torrettinni

Am I using IF correctly?

Recommended Posts

Hi

this is very basic question, but it does bother me sometimes since it is how I commonly use this, but I see others don't:

 

I commonly use the assignment of local variables in methods with parameters like this - assuming all values are simple data types:

 

if ParamaterValue <> None then
	localVar := ParameterValue
else
	localVar := DefaultValue;

but I see often usage like this:

 

localVar := DefaultValue;
if ParamaterValue <> None then
	localVar := ParameterValue;
	

 

Is this just a personal preference or is there anything I can't see in 2nd example that is 'better' over my example?
 

Edited by Mike Torrettinni
Mising : fixed

Share this post


Link to post

Second alternative possibly does an unnecessary instruction but the first has a jump in both cases - so it depends.

If you are micro-optimizing code (which you usually don't) you might want to keep the common path jump free.

Edited by Stefan Glienke

Share this post


Link to post

The micro-optimization is not the goal, in this case. I use my version because it seems clearer, even at the expense of 1 extra line. Quick look at the code and I know how localVar is set.

Share this post


Link to post
Guest

Yes! 99,9% of cases (when not micro-optimising as mentioned above) readability is preferable IMHO.

However, readability is often subjective too. So.

 

Btw, please edit your code above in order not to throw off beginners (two : [colons] are missing).

Share this post


Link to post
Guest

Must admit i fret over this thing from time to time.

Share this post


Link to post

I see another advantage in the 1. option, which is debugging: You can step/break into both cases, instead or only one.

Share this post


Link to post

I would write it as 

localVar := ParameterValue;
if localVar = None then
  localVar := DefaultValue;

Presume that ParameterValue is assigned in most cases, then DefaultValue will not be accessed in most cases.

Edited by Kryvich

Share this post


Link to post

I think this comes (also) down to how expensive is getting Default Value. If just Constant or some simple value, then it is not an problem, But if it's anything more complicated, then it could be pretty slow if there is significant instances of other than default.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×