2 Replies Latest reply on Dec 6, 2008 6:33 AM by joblini

    If a method returns Boolean it shouldn't return null:Good or bad practice?

      The following methods have a Boolean return type but in their code they explicitly return a null in some cases (that makes the return value not boolean because now 3 possible values are expected: true, false, and null:


      org.jboss.seam.mail.ui.MailComponent.getBoolean(String)


      org.jboss.seam.ui.graphicImage.Image.isRatio(double, double)


      Wouldn't it be better to return false in those methods instead of null ? And perhaps even change their return type from Boolean to boolean to prevent null from being returned at all?


      Should I submit a JIRA and a path?


        • 1. Re: If a method returns Boolean it shouldn't return null:Good or bad practice?

          The same problem exists in:


          org.jboss.seam.ui.util.JSF.getBooleanValue(FacesContext, ValueExpression)
          org.jboss.seam.web.IsUserInRole.isUserInRole(String)


          But I am not that sure that it is wrong to return null in this cases... Perhaps an Enum should be used for IsUserInRole.isUserInRole ?

          • 2. Re: If a method returns Boolean it shouldn't return null:Good or bad practice?
            joblini

            My 2 cents:



            org.jboss.seam.ui.util.JSF.getBooleanValue(FacesContext, ValueExpression)


            Null is OK, this is a general purpose method.  There are occasions when Boolean null can be very useful, for example, as a search criteria



            • true  - include values that are true

            • false - include values that are false

            • null  - include values that are true or false (in other words, don't use this as a criteria.





            org.jboss.seam.web.IsUserInRole.isUserInRole(String)

            Doesn't make sense here, the user either is or isn't in a role. 


            On the other hand, JSF doesn't like (small b) boolean values, so we don't have much choice here other than to use Boolean.


            In general, I think that Boolean is more appropriate, especially when mapping to a Database.  I hate things like mapping an integer in JDBC and having a null magically transformed to a 0.  Same thing goes for boolean - who is to say whether null corresponds to true or false.  If the database can accept a null, we also have to accept it in Java.


            Another classic is Oracle turning 0 length strings into nulls.


            Bottom line: deal with possible values as they are and don't try to force conversions, because in the end there may be cases you didn't anticipate.