Introduction:
When calling a function, we often hope that the function can be "smart" and understand the caller's thoughts. Let's look at the example below.
Example 1 (implemented by default)
/// <Summary> /// obtain the log collection /// </summary> /// <param name = "where"> filter condition </param> /// <param name = "orderBy"> sorting condition </param> // <returns> </returns> public DataTable GetLogs (WhereClip where, orderByClip orderBy) {return this. getFromSection (). where (where ). orderBy (orderBy ). toTable () as DataTable ;}
Client:
Obtain the log set for filtering the latest object M (filtering and sorting -,-)
this.GetLogs(Log._.Module == 'M', Log._.Date.Desc);
Client B:
Obtain the latest log collection for filtering (only concerned with sorting, a little depressing -- |)
this.GetLogs(WhereClip.All, Log._.Date.Desc);
Client C:
Get the log set (neither filtering nor sorting, very depressing-|)
this.GetLogs(WhereClip.All, OrderByClip.Default);
In the above three cases, all the functions we define can be addressed, but it's just a bit silly. After a long time, the caller started to get frustrated. Who wrote the function, I am so tired of writing. At this time, it is time to come up with a powerful tool for restructuring. We can use overload functions to reconstruct our code. See the following example:
Example 2 (after Reconstruction)
/// Obtain the log collection /// </summary> /// <returns> </returns> public DataTable GetLogs () {return this. getLogs (WhereClip. all );} /// <summary> /// obtain the log collection /// </summary> /// <param name = "where"> filter condition </param> /// <returns> </returns> public DataTable GetLogs (WhereClip where) {return this. getLogs (where, OrderByClip. default );} /// <summary> /// obtain the log collection /// </summary> /// <param name = "where"> filter condition </param> /// <param name = "orderBy"> sorting condition </param> // <returns> </returns> private DataTable GetLogs (WhereClip where, orderByClip orderBy) {return this. getFromSection (). where (where ). orderBy (orderBy ). toTable () as DataTable ;}
Summary:
The restructured Code uses the function overload to encapsulate the "default parameters" of the function, so that the client pays more attention to the current business point when calling the function. When functions become "smart", they also encapsulate "Default implementations", but they are just two-pronged.