Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Good Practice in Method Design – TIP (Beginner/Intermediate)

5.00/5 (1 vote)
20 Oct 2011LGPL31 min read 14.3K  
Good practice in method design

In this post, I shall show you a small good practice that I follow and even many books suggest it while designing our generic methods which we daily write.

So today, I was refactoring a code at my work place. Due to privacy rules, I will not post the exact code but similar kind below:

C#
public IList<T> GetList<T>()
{
IList<T>  IMyList = new List<T>();

return IMyList;
}

public void DoSomeWorkOnMyCollection<T>(List<T>myList)
{
//Some collection operations done.
}

For sure, there is no flaw in this method, but there is a slight problem with their design with respect to extensibility. Upon further refactoring process, I happen to see similar method DoSomeWorkOnMyCollection() implemented again somewhere else, but this time it was for handling HashSet<T> type.

Regarding the first method, i.e., GetList<T>(), the return type is more generic or more base type, which at the caller side I might have some problem.

So upon reading some books and blog, I came to the conclusion that it is better to have a return type of method to most derived type as shown below:

C#
public List<T> GetList()
{
return new List<T>();
}

In such a way, I do get flexibility in getting the return value to List<T> or IList<T> (more stronger) at the caller side. So it's all a matter of being flexible or choosy here.

Similarly, with respect to the second method accepting more derived parameter type, this method is tightly coupled to the List<T> typed arguments. I won't be able to pass arrays or other types at all to this method, such way forcing me to write other methods or overloaded methods. So to have more of a generic code, I can go for:

C#
public void DoSomeWorkOnMyCollection<T>(IList<T> myList)
{
//Some collection operations done.
}

Now I can pass Arrays, other types which implement IList<T> interface, thus again making the code more flexible.

Thanks for reading!

P.S.: If you know of any better practice, please do let me know. Your valuable suggestions/comments/votes are appreciated.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)