Real-World Refactoring: Parameter List to Parameter Object
While most methods require 1-3 parameters, developers sometimes go overboard with parameter lists in the method signature. Today, we refactor a large parameter list into a Parameter Object pattern.
When we start developing at the start of our career, a majority of developers have no idea what standards are out there. Without consulting a mentor or professor, we, in turn, run rampant by writing wild, wild west code.
But as our career continues, we notice some practices are considered "code smells." One particular code smell is having a huge number of parameters in a method.
Without even knowing about this code smell, you think your code is really cool...until you have another developer look at your code.
Today, we'll go over some of the ways to remove a large parameter list in a method signature.
One of the best approaches to refactoring a large parameter list is to introduce a parameter object.
According to the development community, most have mentioned that 0 is the correct number of parameters while 3 is definitely stretching it.
So if we take the following code with multiple parameters,
public void SaveUser(string firstName, string lastName, string dob, string address, string city, string state, string zipcode, string country)
we can create our parameter object (in this case, a user) and pass that in instead.
public void SaveUser(User user)
Definitely a lot cleaner, right?
There really isn't anything else to mention regarding this refactoring. As you can tell from the parameter object link from above, this refactoring is so simple, even the refactoring definition is contained on one page.
It's probably one of the simplest refactors you can do when writing code.
Why such a short post? (translation: THAT'S IT?!)
I apologize, but this is probably one of my shortest posts I wrote since DanylkoWeb started, but I feel it's an important one.
If you do a search on "too many parameters C#" in Google (Here, let me Google that for you), you'll notice a lot of people are still discussing this topic which leads me to believe that everyone hasn't caught on to the Parameter Object refactoring yet.
Maybe it's in the "heat of coding?" Who knows?
Is there a better way of refactoring a long list of parameters? Post your comments below.