The Artima Developer Community
Sponsored Link

.NET Buzz Forum
Multiple Return Statements

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Peter G Provost

Posts: 849
Nickname: pprovost
Registered: Aug, 2003

Peter G Provost is a Solution Architect for Interlink Group in Denver, CO.
Multiple Return Statements Posted: Sep 5, 2003 11:25 PM
Reply to this message Reply

This post originated from an RSS feed registered with .NET Buzz by Peter G Provost.
Original Post: Multiple Return Statements
Feed Title: Peter Provost's Geek Noise
Feed URL: /error.aspx?aspxerrorpath=/Rss.aspx
Feed Description: Technology news, development articles, Microsoft .NET, and other stuff...
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Peter G Provost
Latest Posts From Peter Provost's Geek Noise

Advertisement

I was involved in a code review the other day with a colleague and we got into a discussion about having multiple return statements in a method. He felt that it was almost always bad, and I felt that it depended on the code in question. My goal is to produce code that is easy to understand and has a minimal amount of duplication.

I think I know where this rule came from, and in some languages it makes sense. In C, C++, and COM, for example, you often have a method structure that looks something like this:

function DoSomething() {
// Allocate some stuff

//
Do something
// Release the stuff
// Return a value
}

In this case, you want to make sure that you always release the memory that is allocated at the top. So by having developers always drop through to the return statement at the end, you help them to not forget. This actually makes the code easier to understand. It also produces code with less duplication.

But in languages with garbage collection (like C# and Java), you don't often need to do this. Notice I didn't say never. Even in GC systems, we still sometimes have to clean up after ourselves (e.g. IDisposable and COM proxies) but for the most part you don't have to.

So remember, a rule like this was originally created for a reason. But that doesn't mean you should follow it like a religious fundamentalist. Use your brain and decide when it is appropriate and when it isn't.

PS. If you run across code that was written with massively nested if statements to enforce this rule, take a look at the Replace Nested Conditional With Guard Clauses refactoring.

Read: Multiple Return Statements

Topic: Busy Weekend Previous Topic   Next Topic Topic: A's Are Hot

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use