[代码重构]利用“函数重载”实现“默认参数”

引言:

在函数调用的时候,我们往往希望函数能够“聪明”一点,能够明白调用者的心思,看下面的例子。

 

示例一(默认实现)

        /// <summary>
        /// 获取日志集合
        /// </summary>
        /// <param name="where">筛选条件</param>
        /// <param name="orderBy">排序条件</param>
        /// <returns></returns>
        public DataTable GetLogs(WhereClip where, OrderByClip orderBy)
        {
            return this.GetFromSection().Where(where).OrderBy(orderBy).ToTable() as DataTable;
        }

客户端A:

获取筛选最新的对象M的日志集合(关心筛选和排序-,-)

this.GetLogs(Log._.Module == 'M', Log._.Date.Desc);

客户端B:

获取筛选最新的日志集合(只关心排序,有点郁闷--||)

this.GetLogs(WhereClip.All, Log._.Date.Desc);

客户端C:

获取日志集合(不关心筛选,也不关心排序,非常郁闷—|||)

this.GetLogs(WhereClip.All, OrderByClip.Default);

上面三种情况,我们定义的函数都能够应对,不过就是傻了一点,时间久了,调用者,开始出现不满的情绪了,是谁写的函数,害我写的这么累。这时候,时候拿出重构的利器了,用重载函数,来重构我们的代码,见下面的示例:

示例二(重构后)

        /// 获取日志集合
        /// </summary>
        /// <returns></returns>
        public DataTable GetLogs()
        {
            return this.GetLogs(WhereClip.All);
        }

        /// <summary>
        /// 获取日志集合
        /// </summary>
        /// <param name="where">筛选条件</param>
        /// <returns></returns>
        public DataTable GetLogs(WhereClip where)
        {
            return this.GetLogs(where, OrderByClip.Default);
        }

        /// <summary>
        /// 获取日志集合
        /// </summary>
        /// <param name="where">筛选条件</param>
        /// <param name="orderBy">排序条件</param>
        /// <returns></returns>
        private DataTable GetLogs(WhereClip where, OrderByClip orderBy)
        {
            return this.GetFromSection().Where(where).OrderBy(orderBy).ToTable() as DataTable;
        }

总结:

重构后的代码,利用了函数的重载,封装了函数的“默认参数”,让客户端调用的时候更加关注当前的业务点。在函数变“聪明”的同时还封装了“默认实现”,只是一举两得,何乐而不为。

原文地址:https://www.cnblogs.com/JavCof/p/2022272.html