which way of return is better?

  • Thread starter Thread starter Phl
  • Start date Start date
P

Phl

hi,

just wondering which way of coding is considered better?

This style where the two returns aren't interconnected by an else
statement in the if seems to be very popular these day, where use ch:

public static bool IsProfileLoaded()
{
EditProfile ep = (EditProfile)BLL.TicketContext.Instance.GetUserControl("EditProfile");

if(ep == null)
{
return false;
}
//no else statement here
//does this generate less code as a result
//it's less obvious
return true;
}

This is what C programmers used to do:

public static bool IsProfileLoaded()
{
EditProfile ep = (EditProfile)BLL.TicketContext.Instance.GetUserControl("EditProfile");

if(ep == null)
{
return false;
}
else //this make it clearer it seems
{
return true;
}
}


Which is better?

cheers
 
I would suggest the first pattern, since an 'else' clause really is
superfluos (IMO).
In your particular case though, i would even do:
public static bool IsProfileLoaded()
{
return BLL.TicketContext.Instance.GetUserControl("EditProfile") as
EditProfile != null;
}
 
Phl said:
public static bool IsProfileLoaded()
{
EditProfile ep = (EditProfile)BLL.TicketContext.Instance.GetUserControl("EditProfile");

if(ep == null)
{
return false;
}
//no else statement here
//does this generate less code as a result
//it's less obvious
return true;
}
Personally, as long as you aren't doing anything else there except
returning, I would do something like:
public static bool IsProfileLoaded()
{
EditProfile ep =
(EditProfile)BLL.TicketContext.Instance.GetUserControl("EditProfile");
return ep != null;
}
 
Hi,

The presence of "else" is very unlikely to have any noticeable negative
effect on performance. On the other hand, it can improve code readability,
which should generally be favoured over "cheap" optimizations.
 
Phl,

For the simple example that you gave, I would actually assign the result
of the comparison to a variable, and then return that.

For more complex logic, where you have a number of conditions, the first
condition that triggered a return would return the value, whereas you have
the return value at the end where all conditions fail (which could generate
a true or false value, depending on the logic).

Hope this helps.
 
hi
I think a bottom line would be, "it really depend on the logic" .so in
such situation you would not need to use if at all
Mohamed Mahfouz
 
Phil.. What I do is

if (blah) {
return x;
} //else
return y;

Steve McConnell addresses multiple returns in his new edition of Code
Complete pp391-393 and argues to use multiple returns when

1) It enhances readability
2) Acts as a guard clause to simplify complex error processing

Regards,
Jeff
 
Back
Top