Java and SQL : return null or throw exception?

前端 未结 6 991
面向向阳花
面向向阳花 2021-01-21 10:09

This is another debated subject, but this time i am searching only for the simple and documented answers. The scenario :

Let\'s assume the following method:



        
6条回答
  •  生来不讨喜
    2021-01-21 10:40

    I'd avoid the following

       sql.append("SELECT * FROM ").append("dogs_table");
       sql.append(" WHERE ").append(colName).append("='");
                            sql.append(colValue).append("'");
    

    and instead use a PreparedStatement with its associated parameter setter methods (setString()) etc. This will prevent problems with values for colValue having quotes, and SQL injection attacks (or more generally, colValue forming some SQL syntax).

    I would never return a null if the collection was merely empty. That seems very counter-intuitive, and completely unexpected from the client's point of view.

    I wouldn't recommend returning a null in error conditions, since your client has to explicitly check for this (and will probably forget). I would return an empty collection if need be (this may be analogous to your comment re. a null object), or more likely throw an exception (depending on the circumstances and the severity). The exception is useful in that it will carry some information relating to the error encountered. Null tells you nothing.

    What should you do if encountering a problem whilst building a Dog object ? I think that depends on how robust and resilient you want your application to be. Is it a problem to return a subset of Dogs, or would it be completely catastrophic and you need to report this ? That's an application requirement (I've had to cater for either scenario in the past - best-effort or all-or-nothing).

    A couple of observations. I'd use HashMap rather than the old Hashtable (synchronised for all access and , more importantly, not a proper Collection - if you have a Collection you can pass it to any other method expecting any Collection), and StringBuilder over StringBuffer for similar reasons. Not a major problem, but worth knowing.

提交回复
热议问题