473,406 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Removing else blocks

I have an 'if else' statement block like this:

if( inputArg != VALID_VALUE )
{
return error ;
}
else
{
// Do some major operation
return success ;
}

I am thinking of changing it to something like this:
if( inputArg != VALID_VALUE )
{
return error ;
}

// Do some major operation
return success ;
Which style do you recommend? Why?
Jul 22 '05 #1
6 1089

"qazmlp" <qa********@rediffmail.com> wrote in message
news:db*************************@posting.google.co m...
I have an 'if else' statement block like this:

if( inputArg != VALID_VALUE )
{
return error ;
}
else
{
// Do some major operation
return success ;
}

I am thinking of changing it to something like this:
if( inputArg != VALID_VALUE )
{
return error ;
}

// Do some major operation
return success ;
Which style do you recommend? Why?


The second.

Because exceptional processing (like error handling) should not be given
equal weight with normal processing. By having the error handling part of
you function in a separate if statement from the main part of the function
you are demonstrating that both pieces of code don't have equal importance.
Having both parts of the code in an if else statement implies some sort of
equivalence.

john
Jul 22 '05 #2
On 7 Mar 2004 01:40:13 -0800, qa********@rediffmail.com (qazmlp) wrote:
I have an 'if else' statement block like this:

if( inputArg != VALID_VALUE )
{
return error ;
}
else
{
// Do some major operation
return success ;
}

I am thinking of changing it to something like this:
if( inputArg != VALID_VALUE )
{
return error ;
}

// Do some major operation
return success ;
Which style do you recommend? Why?


I typically use the second style, because it avoids needless
indentation. I prefer to bail out immediately if there's a problem,
instead of having a whole mess with multiple if/elses.

There are those that think that a function should only have one exit,
and it's quite a religious issue. Personally, I think that rule just
causes longer, more unreadable, and more unmaintanable code. I keep my
functions short and simple, so the single exit rule is not as beneficial
as perhaps it would be in larger functions.

--
Be seeing you.
Jul 22 '05 #3
> There are those that think that a function should only have one exit,
and it's quite a religious issue.


This is structured programming, as exemplified by Pascal. Every function
should have one entrance point and one exit point. Everyone accepts the
first part, very few the second part, especially if they have done real
world programming where you do have to think about error handling.

C++ exceptions provide an even clearer way to bail out of a function upon
detecting an error. In code like this the use of else looks perverse to me.

if (some error)
{
throw some exception;
}
else
{
carry on as normal;
}

john
Jul 22 '05 #4
The first style might result in a 'function should return a value' warning
even though it always does. I would use the second style for that reason.

Fraesr.
Jul 22 '05 #5
qazmlp wrote:
I have an 'if else' statement block like this:

if( inputArg != VALID_VALUE )
{
return error ;
}
else
{
// Do some major operation
return success ;
}

I am thinking of changing it to something like this:
if( inputArg != VALID_VALUE )
{
return error ;
}

// Do some major operation
return success ;
Which style do you recommend? Why?


When I'm checking for something I expect to happen in the normal course
of the program, my preference is to maintain a single point of exit:

Status function( Input const& input ) {

Status status; // To be returned.

if( ! valid( input ) ) {
status = error;
}
else { // Input is valid.
status = success;
}

return status;
}

The biggest reason for this is that it guarantees a place in each
function where I can check the function's value (and any other program
state) immediately before the function returns. This isn't something I
did in school; it took a couple of years of "real world" debugging to
appreciate.

If a run-time check uncovers a truly exceptional condition, I prefer to
throw an exception. "Truly exceptional" means (to me) that it may not
be feasible to recover from the error. If one of my functions is called
incorrectly, I typically throw, since I no longer trust the immediately
higher layer of the program.

template< typename N >
N reciprocal( N const& n ) {

if( n == 0 ) {
throw Exceptions::Division_by_zero(
"attempt to find reciprocal of zero" );
}

N result = 1/n;

return result;
}

In most of these cases I actually use an ASSERT macro to do the "throw
if check fails." I know Bjarne recommends using a template for
Assertions, but I like my error messages to include the failed
expression, as well as the file name and line number.

As Thore said, this is a pretty religious issue. Bright people have
suprisingly different philosophies. The conversation seems to be along
these lines:

A: I like to keep a single point of exit.
B: That makes the code less readable.
A: But much more debuggable.
B: No, you're wrong.
A: No, YOU are wrong.
B: Taste my wrath!

[ Mild flames ensue. ]

Whatever you do, you're likely to upset a few folks. Pick whatever
makes sense to you and go with it. If you change your mind later, at
least you'll know *why* the way you've been doing it is wrong. Then you
can be religious about it, too. ;)
Jul 22 '05 #6

"Jeff Schwab" <je******@comcast.net> skrev i melding
news:VM********************@comcast.com...

When I'm checking for something I expect to happen in the normal course
of the program, my preference is to maintain a single point of exit:

[snip]

In certain situations, and maybe in the long run, might not this give you a
performance penalty, in contrast to exiting the function once an error is
discovered ?

- Magnus
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Geronimo W. Christ Esq | last post by:
Are there any scripts or tools out there that could look recursively through a group of C/C++ source files, and allow unreferenced function calls or values to be easily identified ? LXR is handy...
0
by: sameer mowade via .NET 247 | last post by:
Hello All, I have problem while dynamically removing row from the Datagrid which i have added dynamically as shown in the following code snippet. The problem is that while removing dynamically...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
7
by: Adam Honek | last post by:
Is there a direct way to remove one entry from a one dimensional array? I keep looking but either my eyes are funny or it isn't there. Must we really create a temp array and copy all but 1 of...
6
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or...
2
by: techi_C | last post by:
Hi I'm getting a problem while removing semaphore from system. Before removing semaphore I'm checking the usage count of a smaphore. // checking usage count usage_count =...
17
by: Eric_Dexter | last post by:
def simplecsdtoorc(filename): file = open(filename,"r") alllines = file.read_until("</CsInstruments>") pattern1 = re.compile("</") orcfilename = filename + "orc" for line in alllines: if not...
16
by: junky_fellow | last post by:
Is there any efficcient way of removing the newline character from the buffer read by fgets() ? Is there any library function that is similar to fgets() but also tells how many bytes it read...
7
by: =?Utf-8?B?Sm9lbCBNZXJr?= | last post by:
I have created a custom class with both value type members and reference type members. I then have another custom class which inherits from a generic list of my first class. This custom listneeds...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.