开发者

Better design choice: Method returning Object or passing 'Class<T> type' as argument?

开发者 https://www.devze.com 2023-02-17 10:17 出处:网络
I encountered this during object-relational mapping while creating a row mapper (to map a row into >= 1 objects). I was playing with DBUtils, and you need to implement the RowProcessor interface to ha

I encountered this during object-relational mapping while creating a row mapper (to map a row into >= 1 objects). I was playing with DBUtils, and you need to implement the RowProcessor interface to have your "own" row mapper. This is the method signature (开发者_如何学JAVA1 of 4 such methods, returning a single object, list, map and array)

public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException 
{
    //conversion logic
}

In Spring this is the method signature for row mapping (only 1 method):

Object mapRow(ResultSet rs, int rowNumber)
{
//conversion logic
}

Going from DBUtil's method to object involves reflection based instantiation and too much type casting to even get the objects out.

Spring's seems rather straightforward (easier by comparison).

The question is then from the flexibility of design which style is better and when would you choose a reflection based approach over the latter (as above)? I was just curious so I thought I'd put it out to get some ideas on it. Basically why do you think DBUtils took a reflection based approach? Any advantages?


Using reflection (or huge switch statements, or whatever) in this case has the advantage of encapsulating the type unsafety in one place. Callers specify what they're after and that's what they get back. They can then continue to work with it without any casts, etc. You only need to manually check the type safety in this one place, the compiler will check it everywhere else. Returning Object implies that callers are going to be doing a lot of casts, each of which might come with a ClassCastException and needs to be manually checked.

0

精彩评论

暂无评论...
验证码 换一张
取 消