Parameterized Method

One of the dependency-breaking techniques described by Michael C. Features in his book “Working Effectively With Legacy Code” is Parameterized Method. I use this quite often to make code testable. My typical usage looks something like the following. Let’s say, I have the following method:

   1: public void ComplicatedMethod(View view)
   2: {
   3:     // some code here
   4:     if (view.Available) 
   5:         Console.WriteLine("more complicate code");
   6:     // even more complicated code
   7: }

What makes it hard to test this method is the instance of view. The view might not be easy to create. The view may have its own dependencies and so forth. However, notice how the view is being used. The view is only being used to check for a condition. So, let’s apply Parameterized Method refactoring to it.

   1: public void ComplicatedMethod(View view)
   2: {
   3:     ComplicatedMethod(view.Available);
   4: }
   5:  
   6: public void ComplicatedMethod(bool available)
   7: {
   8:     // some code here
   9:     if (available)
  10:         Console.WriteLine("more complicate code");
  11:     // even more complicated code
  12: }

Now, the over-loaded method that takes a bool instead of the view is easy to test!

The above example is in C#, but equally applicable to Java or anything else for that matter. There are many other alternatives to Parameterized Method as well.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name (required)

 Email (will not be published) (required)

 Website

Your comment is 0 characters limited to 3000 characters.