Should a method have only one return point/statement?

Hi,
sometimes I have Code that looks like
  public boolean equals(final Object o) {
    if (o == null) {
      return false;
    if (o == this) {
      return true;
    if (!getClass().equals(o.getClass())) {
      return false;
    if (this.getId() == 0) {
      return false;
    final Link cObject = (Link) o;
    if (this.id != cObject.id) {
      return false;
    if (!this.linkParameter.equals(cObject.linkParameter)) {
      return false;
    if (!this.uriType.equals(cObject.uriType)) {
      return false;
    return true;
  }Is it best practice to use return in this manner? Some code metric tools report this use of return as bad coding practice.
What are the pros and cons of the short return?
Thanks for your answers

tmnelson wrote:
So we should pervert exception handling by putting all our code into try/finally blocks? I don't think that's gonna fly...That doesn't make much sense to me and I don't know what it has to do with what I said. One of the good reasons for forcing a single return is that you can put all the required cleanup code at the end of the method. Finally blocks accomplish this same end. This is not a perversion. In fact, finally blocks are superior in this regard because they are guaranteed to execute, even if the method doesn't complete normally. Single return cannot make this guarantee.
Um, I still only see one return. Only now it's in the wrong place. Why not just add the appropriate else clause to the original code? That's what you're going to wind up doing in your "improved" code, anyway.You seem to have completely missed the point. Both code snippets are wrong. My improved version doesn't compile. It's impossible to miss. The other version was deployed into production. In my experience a compilation error is a much better problem to have than a production system crash.
I don't see any value in forcing the single return. Actually I think it generally makes code much harder to read. It turns the execution path from a tree into an onion.I think it's a good rule of thumb, up there with placing braces after your if statement and documenting when a case statement falls through. It was more important when people wrote 100+line functions, as it was mighty confusing to place a breakpoint at some line and then never hit it because the code executed a return twenty or so lines before your breakpoint. This is still a potential problem today, but people tend to write shorter routines, so it's less common.It's a rule of thumb that makes sense in languages without the high-level control structures that Java has. COBOL is an example of such a language where forcing single returns is really important but it doesn't have a true method structure. It doesn't make sense in Java. And for long methods, the proper advice is to shorten them, not to force a single return.
ISTR that compilers could perform certain register optimizations if routines only had one entry and exit point, but I can't find a definite reference, and that may have only been valid for block-structured programs anyway. Or loops.This is complete nonsense. The compiler or JVM can optimize your code much better than anything like this will accomplish. There's no reason that the JVM can't treat a method with multiple return statements as having a single return statement given that all paths are guaranteed to return a value of a specific type or an exception will be thrown.
If you just declare the variable and don't assign it, the compiler will complain if there is a path that doesn't guarantee that it is assigned before it is used.This doesn't work in many IDEs, as the editor won't perform much static analysis, it'll just flag the declaration as an error and refuse to compile the code until you "fix" it.I didn't mention IDEs. This is part of the Java Language Specification. No compliant compiler will allow such code to be compiled.

Similar Messages

  • I have a mixer which i was using with my pc and now i bought a new macbook and it have only one jack for headphones and to use mixers i need jack for microphone too so what should i do

    i have a mixer which i was using with my pc and now i bought a new macbook and it have only one jack for headphones and to use mixers i need jack for microphone too so what should i do

    You need to get headset splitter adapter.
    http://www.startech.com/Cables/Audio-Video/Audio-Cables/35mm-4-Position-to-2x-3- Position-35mm-Headset-Splitter-Adapter-Male-to-Female~MUYHSMFF

  • Best way to have only one  instance of an object in web application.

    Hello,
    I defined a class that provides services to my web application: subscribes user, check if user already subscrubed etc. The objects don't need to save any session information. So it is like a Stateless Session Bean (from what I've read about Session beans).
    The webapp is small and I don't want to use EJBs.
    What would be the best way to have one instance of the above class in my webapp ?
    Would making the class static be a good method ? Using a factory ?
    Is there a way to put in web.xml something that asks the container to instantiate an object that is not a servlet and place it in Application scope, so that I cann retrieve it whenever required in my app ?
    Other suggestions ?
    Thank you,
    Vlad.

    Hi
    The best way to have only one instance is use the singleton pattern. The idea is : the class has a private
    contructor, a public static method that returns an instance of this object and a static member that is false if not any instance and true if there si an instance.
    To obtain one instance you can do some like
    MyObject ob=MyObject.getIntance();
    this method inspect the static member and returns null if true. If false set to true and return the object
    via the private constructor.
    You can lear more at book of Gramma .... (gang of four)
    Hope this helps

  • To download from AppStore want tree security questions  but i have only one question

    When i want to download (free) from AppStore ask me TREE Security questions , but in security settings my APPLE ID have only ONE question and answer
    Help me please in this problem

    Hello HalisaEr,
    Thank you for the details of the issue you are experiencing with your security questions.  I found an article with some useful information if you unable to answer the security questions:
    What should I do if I don't remember the answers to my Apple ID security questions?
    Try answering them at least once to see if you can get them right, even if you are not sure you remember the answers to your security questions.
    If you are confident you can't remember them, try one of the following:
    If you have three security questions and a rescue email address
    sign in to My Apple ID and select the Password and Security tab to send an email to your rescue email address to reset your security questions and answers.
    If you have one security question and you know your Apple ID passwordsign in to My Apple ID and select the Password and Security tab to reset your security question.
    If you have one security question, but don't remember your Apple ID password
    contact Apple Support for assistance. Learn more about creating a temporary support PIN to help Apple confirm your identity when you contact Apple Support.
    Note: If you have forgotten your password and answer your security questions incorrectly too many times in a row, you will be unable to try to answer your security questions for a period of time. During that time you will not be able to reset your password and will not have access to your account.
    You can find the full article here:
    Apple ID: All about Apple ID security questions
    http://support.apple.com/kb/HT5665
    If you continue to have issues, please contact our Account Security Team as outlined in this article:
    Apple ID: Contacting Apple for help with Apple ID account security
    http://support.apple.com/kb/HT5699
    Thank you for using Apple Support Communities.
    Best,
    Sheila M.

  • I just synced my music to my iphone 5 and i have only one playlist but I need help

    Hi,
    i just synced my music to my iphone 5 and i have only one playlist but when i sync my music to my ipad i have other music on there that i don't want right now i just want my christmas playlist folder that i have playlists cause on my iphone 5 i just have one playlist which is christmas music playlist folder that has playlists in it which is what i only want on my ipad right now thanks

    Hey,
    Here is what I did:
    1. Connected my iPad to the computer.
    2. Opened iTunes.
    3. Pressed Music Tab.
    4. Pressed the Selected Playlists, Artists, Albums, and Genres
    5. Then in the Playlist box below I only have the Christmas music folder checked and all the playlists in that folder checked.
    6. Then I Synced my iPad
    Here is a Picture of my iTunes of what I'm talking about and then also here is a picture of my iPhone 5 music that has only one playlist folder with playists in it

  • TS3276 I can have only one recipient at a time on e-mails I am sending.

    I can have only one recipient at a time on e-mails I am sending.

    Any ideas on how to fix it?

  • How i can have only one Apple ID for everything my computer and tab and iphone?

    How I can have only one Apple ID for evrything, my computer Iphone

    Thats how the majority of people use iCloud. All you need to do is sign into the same account on all of your devices.

  • Why we can have only one public class in one source file

    why we can have only one public class in one source file

    When the java compiler is run it looks for classes referenced by the classes you are directly compiling. When looking for these referenced classes it looks for source as well as class files and compiles them automatically if the coresponding class files are missing, or older than the source.
    In order to do this it must be able to work out the source file name for any given class which might be referenced from another (the rule also applies to package level access).

  • Create a business model when we have only one source table

    Hi,
    How to create a business model when we have only one source table in Physical layer
    Regards
    Swathi

    This is very much possible and feasible. Its called as Single Table model. Good example is SA System Subject Area where we just have a single physical source. No need to create Alias in Physical. Simply use the same table twice in BMM with one Logical Table as Dummy Fact..Like say Count of Users (aggregated). Then apply normal Complex join in BMM and present in presentation layer.
    http://gerardnico.com/wiki/dat/obiee/single_table_model
    http://gerardnico.com/wiki/dat/obiee/sasystem

  • Why a table can have only one PK ?

    Just wanted to know the reason why Oracle allows only one PK per table ?
    I came across a situation where my existing large PK which is on a single (ID) column needs an alteration to add a new column (No).
    ID column on which PK is based is now subjected to have duplication and that is the reason why i want to add a new column. The new column composition is not going to ensure uniqueness.
    So, i need to create (alter) PK on two columns now.
    It seems, in order to do that, i need to drop the existing PK and create a new one. Since this is a OLTP production database, business cannot afford to drop the existing pk.
    When i tried to create a separate PK on two columns, Oracle gave me below err:
    ORA-02260: table can have only one primary keySo, i wanted to understand why Oracle allows only one PK / table ? and considering above err, is there any way to make required changes to my PK without altering existing PK?
    (Table is a large 30 GB partition table and PK is a non partitioned global index)
    I think PROBABLY i need to drop existing PK and re-create the new one. But core intention for opening this thread is to know rational behind one pk/table concept.

    OraDBA02 wrote:
    Just wanted to know the reason why Oracle allows only one PK per table ?
    It's not exactly Oracle's fault. The ISO SQL standard requires that a "PRIMARY KEY" constraint can only be used once per table. However, a UNIQUE constraint on non-nullable columns achieves effectively the same thing as a PRIMARY KEY. You can have multiple UNIQUE constraints.
    Arguably the PRIMARY KEY constraint is unnecessary and could safely be dropped from the SQL language. In principle in the relational model a "primary" key is nothing more or less than a candidate key. All keys are equal in the relational model and there is no fundamental reason to designate a primary key at all. There is certainly no reason not to have multiple keys. In the SQL world though it is a very widely observed convention to use a PRIMARY KEY constraint for each table and to use it for all foreign key references.

  • Had problem with DSL, now have only one tab with favicon matching that tab.

    After a storm I had a problem with my U-Verse DSL. I lost access and got a message that it may be due to a problem with the filters on my phones, fax or satellite box. I disconnected all the items that had filters. I was then able to click on a link that AT&T had sent on the message and I got a response, I previously could not get a response because I had no connection. I got pack to the pages on all my tabs by hitting the back arrow on each one. I now have only one tab with favicon matching this WEB site for that tab, the rest all have the AT&T globe. I tried refresh and also opening a new tab and then going to one of the sites.
    This problem is on a different PC that the one I am on now. It has version 21, and is Window 7 Home Premium. I have pasted the trouble shooting info from that PC.

    Hello,
    Many site issues can be caused by corrupt cookies or cache. In order to try to fix these problems, the first step is to clear both cookies and the cache.
    Note: ''This will temporarily log you out of all sites you're logged in to.''
    To clear cache and cookies do the following:
    #Go to Firefox > History > Clear recent history or (if no Firefox button is shown) go to Tools > Clear recent history.
    #Under "Time range to clear", select "Everything".
    #Now, click the arrow next to Details to toggle the Details list active.
    #From the details list, check ''Cache'' and ''Cookies'' and uncheck everything else.
    #Now click the ''Clear now'' button.
    Further information can be found in the [[Clear your cache, history and other personal information in Firefox]] article.
    Did this fix your problems? Please report back to us!
    Thank you.

  • When I try to edit preferences iTunes for Windows locks up.  I have only one user.  This is true even after a reboot.

    When I try to edit preferences iTunes for Windows locks up.  I have only one user.  This is true even after a reboot.

    Hello MF7642,
    Thank you for contacting Apple Support Communities.
    You can use this article to troubleshoot your issues with iTunes.
    iTunes: Missing folder or incorrect permissions may prevent authorization
    http://support.apple.com/kb/TS1277
    Regards,
    Jeff D.

  • VBScript does not retrieve Member details if a Distribution/Security Group have only one Member

    Hi,
    VBScript does not retrieve Member details if a Distribution/Security Group have only one Member. I have tried several Scripts even changed the coding in it, also tried few External Script by created by other Scriptor's. Any suggestion on why this is happening. 

    Perfect... Thank you. I reworked on the Script and it is showing up. One more info required. I know my script is having another bug. Can you help me getting the member list of a User Group. When i pull it retrieves all the Group info for a user
    but no "Domain Users" Group.
    Sorry for the lame humor but it was getting late.
    As for you new request.  I do not understand what you are asking. Can you post your script and any error messages you are getting.
    ¯\_(ツ)_/¯

  • After reverting to Firefox 3.6 I have lost the ability to close a webpage (down to an empty tab) when I have only one tab open. Where did the little "x" go on the single tab???

    I like to be able to close the webpage I am viewing when I am finished, when there is only one tab open, so that Firefox is empty when I next want to browse the web. After upgrading to 5.0 and finding I hated it, I downgraded back to 3.6 and now the little "x" on the single tab is gone. It still appears when I have multiple tabs open, but not when there is just one. What happened? How do I get it back?

    Thank you, but I already have "always show tabs bar" set.
    Also, I have two computers and the other is running the exact same version of Firefox, and the exact same theme, but it does not have this problem.
    To make sure I'm being clear: there is an "x" on each tab that allows me to close it when I have multiple tabs open. When I have only one tab open, there is no "x"; so in order to close the webpage I have to open another empty tab, and then close the first. My other computer has the "x" to close the tab visible even when there is only one tab so that I can close the page and have an empty (marked "(untitled)" tab). Please help!

  • Is Access Point name and cluster name same, if we have only 1 access point ?

    if we have only 1 Access Points, will the name of access point be same as the cluster name ? can i create more then 2 cluster on same role ?
    sid

    Hi sid,
    You can not create a role same with your cluster name, it will cause the DNS resource confilect.
    More information:
    DNS Registration with the Network Name Resource
    http://blogs.msdn.com/b/clustering/archive/2009/07/17/9836756.aspx
    I’m glad to be of help to you!
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

Maybe you are looking for

  • How can I call a web service using JAVAscript in LCD

    hi guys,      I know it can call a WSDL in LCD, but I have not any WSDL web service , and I have a REST web service ,how can I call this REST web service in LCD? I checked some documents and found nothing...if it's possible that it can call a REST we

  • Photoshop CS2 Issues After Latest Secuirty Update

    I am working on a Power Mac G5 with Mac OSX 10.4 and Adobe CS2. I do not know if it was the security update that caused these problems in Photoshop for me, but that was the only thing that had been installed around the time that the problems started

  • Using accents/special characters in keyboard WAY TOO SLOW!

    I'm often using french, and thus many words have many accents (just a short phrase exemple : l'été passé j'ai dû boire l'amère potion de la déception... A short sentence, 5 accents. Can be worse). I'm typing pretty fast, and already getting frustrate

  • IPhoto library in iPod view doesn't match my iPhoto library since Lion

    Help: Since installing Lion my iPhoto library no longer syncs to my iPod Touch. It's as if the iPhoto library stopped updating in the iPod window the moment I upgraded. All previous photos still show up. It's like iTunes thinks I have an alternate iP

  • Mozilla suddenly does not recognise my keyboard. IE does.

    I have to write this on a document and then copy and paste because Mozilla will not recognise the keyboard. A sdfg hj klçº\ ~zxc vb n m,.--+<1 234 5678 90'« qwe rtyui op+ásdf Ghjklçº \~zx cvb nm,.--+<1 234 890'«qwer That is what it looks like when I