Friday, June 15, 2012

Long Parameter List: A very long function declaration

Todays topic of discussion is long parameter list, to be sure that we are in same page I must first mention that “long parameter list” is a kind of “code smell”. Wikipedia has nothing to say about it, if anyone get a reference of a good resource please feel free to add in the comment section.

What is long parameter list?

Method or procedure that take too many argument tend to produce complex code and unreadable complex method, developer need to dive big time in a method to find out what it is doing!

But as big things has small beginning no method has this smell at the beginning I guess, as time progresses and developer start putting parameter one after another to accommodate long parameter list in a function and some thing end up with not only long parameter list but also long method.

Bellow a long parameter list method is given!

public SomeDetail GetSomeDetail(string payingId, string receivingId, string paymentStream, double holdingPercentage, int holdingPeriod,int param, int param2, int anotherparam, string moreparam, string andmore)
---------------------your code goes here

Where Long parameter list is allowed?

In some language there is possibilities of adding default value to a parameter, for instance C++, Python and C# (.NET 4.0 onwards) have this ability to have default value for a parameter on the other hand C and Java do not have such ability.

How to avoid long parameter list?

First of all the most easy way out is to use object class not clear ? for instance we have a long parameter method which is having a1,a2 …. a*n parameter, we can form a class named “ourclass” and then add members like “a1,a2…. a*n” and then pass single object to a method.

Secondly we can break the method in few smaller piece of method so that each method have few parameter and do only one thing, as long parameter list methods tend to do lot of work all by it self.

How lets look at a good example!

public IEnumerable<RepositoryItemInfo> GetAllDocumentInfo(string directory, string[] filteredExtensions)
return Service
.GetAllDocumentInfo(GetProxyCredential(), directory, filteredExtensions)
.Select(proxyDoc => ConvertProxyDoc(proxyDoc));

private static RepositoryItemInfo ConvertProxyDoc(RepositoryItemInfo info)
return new RepositoryItemInfo
Created = info.Created,
FullName = info.FullName,
Id = info.Id,
IsFolder = info.IsFolder,
LastModified = info.LastModified,
MetaData = info.MetaData,
ModifiedBy = info.ModifiedBy,
Name = info.Name,
FileSize = info.FileSize

In above code we can see that RepositoryItemInfo is a class which warps 9 parameter in a simple class and is been passed to a service method to get information.


No comments:

Post a Comment