Java和SQL:返回null或抛出异常? [英] Java and SQL : return null or throw exception?

查看:381
本文介绍了Java和SQL:返回null或抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是另一个辩论的主题,但这次我只是在寻找简单而有文字的答案。情况:

我们假设以下方法:



  public static Hashtable< Long ,狗> getSomeDogs(String colName,String colValue){
Hashtable< Long,Dog> result = new Hashtable< Long,Dog>();
StringBuffer sql = null;
狗狗= null;
ResultSet rs = null;
try {
sql = new StringBuffer();
sql.append(SELECT * FROM).append(dogs_table);
sql.append(WHERE).append(colName).append(=');
sql.append(colValue).append(');
rs = executeQuery(sql.toString());
while(rs.next()){
dog = new Dog();
//...初始化当前resultSet行中的狗
result.put(new Long(dog.getId()),dog);
}
}
catch(异常e){
createErrorMsg(e);
result = null; //我想知道...
}
finally {
closeResultSet(rs); //这个方法在关闭rs时测试null rs和其他东西。
}
返回结果;
}

问题:



1。你建议什么方法来改善这种返回一些狗的技术,有一些属性?



2。 rs.next()将为null ResultSet返回false,否则将生成异常,如下所示:



String str = null;

System.out.println(str.toString());



3。如果在从ResultSet的当前行初始化一个dog对象时会发生不好的情况,如:连接失败,不兼容的值已传递给dog属性setter等等?现在我可能在哈希表中有10个元素,或者没有(第一行)。下一个动作是什么:a)return null hashtable; b)返回结果散列表,现在是在这个阶段; c)抛出异常:这里会有什么异常类型?



4。我想你都会同意这一点:没有什么不好的发生,询问上没有行,一个空值将返回。不过,@ThorbjørnRavn Andersen表示:此处我应该返回一个NullObject而不是一个空值。我不知道是什么。



5。我注意到有人和一群人说应该将应用程序分成多层次或多层次。考虑到上面的例子,这里有什么层次,除了这些我可以想到的东西:

Layer1 ::数据库层,执行操作:此方法。


Layer2 :: ??? :构建新的Dog对象的某个层:我的Dog对象。


Layer3 ::? :我打算在狗集合中做某事的某个层:GUI层,大部分是用户界面的子层。



按照应用程序流程,如果第一层出现异常,最好的想法是什么?我的想法:捕获异常,记录异常,返回一些值。这是最好的做法吗?


感谢您的回答,我期待着看到其他人对这些问题的看法。

解决方案

您提出五个问题


1。你有什么建议改进这种退回一些狗的技术,有些属性?


/ p>


  • 您的方法是静态的 - 这不是可怕的,但是导致您使用另一个静态executeQuery,这对我来说是单一的。 ..

  • 类别狗违反了OO命名实践 - 除非该类的一个实例拥有一些东西,否则复数名词不会形成良好的类名,而且看起来狗实际上是狗。

  • HashTable 全部已被弃用。 HashMap或ConcurrentHashMap提供更好的性能。

  • 我看不出有理由使用多个追加来创建查询的第一部分 - 这并不错,但是它的可读性不太可观,所以sql.append(SELECT * FROM dogs_table WHERE);如果您只需要对所选列(*)和表名(dogs_table)进行硬编码,就会变得更明智的开始。




2。 rs.next()将为null ResultSet返回false,否则将生成异常


作为一个问题,但是,只要不再有任何行处理,rs.next()返回false。


3。如果在从ResultSet的当前行初始化一个dog对象的时候会发生不好的事情


如果发生,接下来你做什么取决于你和你的设计。有一个宽恕的方法(返回所有的行,你可以)和不原谅(抛出异常)。我倾向于倾向于不宽容的方法,因为使用宽恕方法,用户不会知道您没有返回所有存在的行 - 只是在错误之前所有的行。但是可能会有这种宽恕方法。


4。我想你们都会同意这一点:没有什么不好,询问上没有行,空值将返回。


这不是一个明显的正确的答案。首先,写的方法不是发生了什么。它将返回一个空的HashTable(这是一个空对象的意思)。第二,在没有找到结果的情况下,null并不总是答案。



我看到null,但是我也看到一个空的结果变量。我声称他们都是正确的方法,但我更喜欢空的结果变量。但是,总是最好保持一致,所以选择返回无结果并坚持下去的方法。


5 。我注意到有人和一群人说应该将应用程序分成多层次或某种级别。


这比其他人更难回答,没有看到您的其他应用程序。


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:

 public static Hashtable<Long, Dog> getSomeDogs(String colName, String colValue) {
  Hashtable<Long, Dog> result = new Hashtable<Long, Dog>();
  StringBuffer sql = null;
  Dog dog = null;
  ResultSet rs = null;
      try {
          sql = new StringBuffer();
          sql.append("SELECT * FROM ").append("dogs_table");
          sql.append(" WHERE ").append(colName).append("='");
          sql.append(colValue).append("'");
          rs = executeQuery(sql.toString());
              while (rs.next()) {
                  dog= new Dog();
                  //...initialize the dog from the current resultSet row
              result.put(new Long(dog.getId()), dog);
              }
          }
     catch (Exception e) {
         createErrorMsg(e);
         result = null; //i wonder....
         }
     finally {
         closeResultSet(rs); //this method tests for null rs and other stuff when closing the rs.
     }
   return result;
 }

Questions :

1. What ways do u suggest on improving this technique of returning some dogs, with some attribute?

2. rs.next() will return false for a null ResultSet, or will generate an exception, like this one :

String str = null; System.out.println(str.toString());

3. What if, while initializing a dog object from the current row of the ResultSet, something bad happens, like : connection failure, incompatible value has been passed to dog property setter, etc? I might have 10 elements in the hashtable by now, or none (first row). What will be the next action : a) return null hashtable; b) return the result hashtable, the way it is at this stage; c) throw an exception : what will be the exception type here?

4. I think u will all agree on this one : nothing bad happens, there are no rows on the interrogation, a null value will be return. However, @Thorbjørn Ravn Andersen said here that i should return a NullObject instead of a null value. I wonder what that is.

5. I've noticed people and groups of people saying that one should split the application into layers, or levels of some kind. Considering the example above, what layers are here, except these ones i can think of :

Layer1 :: Database layer, where actions are performed : this method.

Layer2 :: ??? : some layer where the new Dog object is constructed : my Dog object.

Layer3 :: ? : some layer where i intend to do something with the collection of dogs : GUI layer, mostly, or a sub-layer of user interface.

Following the application flow, if an exception occures in the 1st layer, what is the best think to do with it? My thoughts : catch the exception, log the exception, return some value. Is that the best practice?

Manny thanks for your answers, i look forward to see what other people think of these matters.

解决方案

You ask five questions

1. What ways do u suggest on improving this technique of returning some dogs, with some attribute?

Several, actually.

  • Your method is static - this isn't terrible, but leads to you using another static "executeQuery", which smells of Singleton to me...
  • The class "Dogs" violates an OO naming practice - plural nouns don't make good class names unless one instance of the class holds a collection of things - and it appears that Dogs is actually "Dog".
  • HashTable is all but deprecated. HashMap or ConcurrentHashMap give better performance.
  • I can't see a reason to create the first part of your query with multiple appends - it's not bad, but it's less readable than it might be, so sql.append ("SELECT * FROM dogs_table WHERE "); makes a more sensible beginning if you're just going to hardcode the selected columns (*) and table name (dogs_table) anyway.

2. rs.next() will return false for a null ResultSet, or will generate an exception

This doesn't seem to be a question, but yes, rs.next() returns false as soon as there's no longer any rows to process.

3. What if, while initializing a dog object from the current row of the ResultSet, something bad happens

If "something bad happens", what you do next is up to you and your design. There's the forgiving approach (return all the rows you can), and the unforgiving (throw an exception). I tend to lean towards the "unforgiving" approach, since with the "forgiving" approach, users won't know that you haven't returned all the rows that exist - just all the ones you'd gotten before the error. But there might be cases for the forgiving approach.

4. I think u will all agree on this one : nothing bad happens, there are no rows on the interrogation, a null value will be return.

This isn't something on which there's an obvious right answer. First, it's not what's happening in the method as written. It's going to return an empty HashTable (this is what was meant by a "null object"). Second, null isn't always the answer in the "no results found" case.

I've seen null, but I've also seen an empty result variable instead. I claim they're both correct approaches, but I prefer the empty result variable. However, it's always best to be consistent, so pick a method of returning "no results" and stick with it.

5. I've noticed people and groups of people saying that one should split the application into layers, or levels of some kind.

This is harder to answer than the others, without seeing the rest of your application.

这篇关于Java和SQL:返回null或抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆