473,657 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code Style - Handling Returns

While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}

Dec 13 '05 #1
41 1923
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?


I tend to prefer case 1 with RAII classes to handle cleanup which makes
it both exception safe and much less prone to error from code
maintenance adding a new if/return block.

Dec 13 '05 #2
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.
Regardless of your personal preference, writing

if (flag == false)

is silly. 'flag' already has type 'bool', so just write

if (!flag)

Same goes for

if (flag == true)

.. Just write

if (flag)

and drop the "== true" clutter.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}


Neither is better than the other.

I prefer

if (!myFunc1() || !myFunc2())
return;
// continue code

V
Dec 13 '05 #3
[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).

Regards,

Marcelo Pinto

Dec 13 '05 #4
Victor,

I just wrote that for clarity for the group. Thanks.

Dec 13 '05 #5
After putting some thought in this, it sounds like Gianni made a good
point that validating for failure after each call would be the better
approach since memory can be safely deallocated, messages logged, etc.
It also reads better on screen rather than having a deep nests.

And yes, I'm a strong believe in the '!'. Like I said earlier, I was
just trying to clarify for readability on the group board.

Dec 13 '05 #6
Jordan wrote:
Victor,

I just wrote that for clarity for the group. Thanks.


Wrote what?
Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Dec 13 '05 #7
On Tue, 13 Dec 2005 11:48:09 -0800, Marcelo Pinto wrote:
[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).


What is "not" in this example?

- Jay
Dec 13 '05 #8
Jay Nabonne wrote:
On Tue, 13 Dec 2005 11:48:09 -0800, Marcelo Pinto wrote:

[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).

What is "not" in this example?


Uh... It's a keyword, the alternative spelling for '!'. What else could
it be?
Dec 13 '05 #9
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}


Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exce ption&) {
}

Or some variant thereof.

Regards,
Peter Jansson
Dec 13 '05 #10

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

Similar topics

25
3726
by: delerious | last post by:
I see some code examples like this: <DIV onmouseover="this.style.background='blue'"> and other code examples like this: <DIV onmouseover="javascript:this.style.background='blue'"> Which way is more proper? Or are both ways perfectly fine? Are there any specifications that discuss when "javascript:" should be put in front of code?
13
4470
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently runs into problems on the system where it will actually be used, and since I used so little error-trapping it dies very ungracefully. I will of course try to fix whatever is causing the error and add error-trapping to the functions where the...
17
2694
by: tshad | last post by:
Many (if not most) have said that code-behind is best if working in teams - which does seem logical. How do you deal with the flow of the work? I have someone who is good at designing, but know nothing about ASP. He can build the design of the pages in HTML with tables, labels, textboxes etc. But then I would need to change them to ASP.net objects and write the code to make the page work (normally I do this as I go - can't do this...
7
9600
by: Coder | last post by:
Hi I have the following code in java script, it is not giving proper output in FIREFOX but running fine in IE... can anybody help me out to make this run in FIREFOX . <script language="JavaScript"> var cntlName; var eleTarget = document.getElementById('hiding'); function showOrHide(){
16
2614
by: lawrence k | last post by:
I've made it habit to check all returns in my code, and usually, on most projects, I'll have an error function that reports error messages to some central location. I recently worked on a project where someone suggested to me I was spending too much time writing error messages, and that I was therefore missing the benefit of using a scripting language. The idea, apparently, is that the PHP interpreter writes all the error messages that are...
232
13242
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
28
1671
by: Platonic Solid | last post by:
Hi- I am learning C from some old lecture notes, but they don't have solutions so I'd like some feedback on my code if anyone has the time. This is an exercise: "Write a program to trim any leading whitespace from a string and return a newly allocated buffer containing the trimmed string. Don't forget to handle errors." main(argc, argv)
0
8324
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8516
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6176
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.