代码改变世界

返回空引用(null)还是返回零元素实例?

2006-05-05 03:34  晓风残月  阅读(1625)  评论(2编辑  收藏  举报

对于一个返回值是集合类型的方法,当处理结果是空值的时候,返回null还是零元素的实例?

1。返回零元素的实例《源码来源于Petshop4》

        public IList<ItemInfo> GetItemsByProduct(string productId) {

            IList
<ItemInfo> itemsByProduct = new List<ItemInfo>();  // “立即加载”

            SqlParameter parm 
= new SqlParameter(PARM_PRODUCT_ID, SqlDbType.VarChar, 10);
            parm.Value 
= productId;

            
//Execute the query against the database
            using(SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_ITEMS_BY_PRODUCT, parm)) {
                
// Scroll through the results
                while (rdr.Read()) {
                    ItemInfo item 
= new ItemInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5), rdr.GetString(6), rdr.GetString(7));
                    
//Add each item to the arraylist
                    itemsByProduct.Add(item);
                }

            }

            
return itemsByProduct;
        }


2。返回空值《记得以前有人称其为“延迟加载”》

        public IList<ItemInfo> GetItemsByProduct(string productId) {

            IList
<ItemInfo> itemsByProduct = null;  // “延迟加载”

            SqlParameter parm 
= new SqlParameter(PARM_PRODUCT_ID, SqlDbType.VarChar, 10);
            parm.Value 
= productId;

            
//Execute the query against the database
            using(SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_ITEMS_BY_PRODUCT, parm)) {
                
if (rdr.HasRow)
                
{
                    itemsByProduct 
= new IList<ItemInfo>(); // “延迟加载”
                }


                
// Scroll through the results
                while (rdr.Read()) {
                    ItemInfo item 
= new ItemInfo(rdr.GetString(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5), rdr.GetString(6), rdr.GetString(7));
                    
//Add each item to the arraylist
                    itemsByProduct.Add(item);
                }

            }

            
return itemsByProduct;
        }

直观上,返回零元素的集合实例,需要无味的开销,但是很多时候返回零元素比返回空值更方便,也更具健壮性,因为很多情况下当参数为null,会抛出“参数无效”异常。
比如,当你将集合绑定到DataGrid的时候,只有当集合是非空引用的时候,才会创建DataGridItem项,当DataGrid的DataSource是null的时候,是不会创建任何项的,连Header和Footer都不会创建,此时界面上就是空白信息,因此,我们就需要手动处理,告诉用户:无任何数据。

但是,偶目前能然没有非常好的测试实例,或者“best pratices”的建议,欢迎大家抛砖^_^。