views:

565

answers:

14

Occasionally , we have to write methods that receive many many arguments , for example :

public void doSomething(Object objA , Object objectB ,Date date1 ,Date date2 ,String str1 ,String str2 )
{
}

When I encounter this kind of problem , I often encapsulate arguments into a map.

Map<Object,Object> params = new HashMap<Object,Object>();
params.put("objA",ObjA) ;

......

public void doSomething(Map<Object,Object> params)
{
 // extracting params 
 Object objA = (Object)params.get("objA");
 ......
 }

This is not a good practice , encapsulate params into a map is totally a waste of efficiency. The good thing is , the clean signature , easy to add other params with fewest modification . what's the best practice for this kind of problem ?

+2  A: 

Good practice would be to refactor. What about these objects means that they should be passed in to this method? Should they be encapsulated into a single object?

GaryF
yes they should . For example , a large search form , has many unrelated constraints and needs for pagination. you need pass currentPageNumber , searchCriteria , pageSize ...
ZZcat
+1  A: 

You could create a class to hold that data. Needs to be meaningful enough though, but much better than using a map (OMG).

Johannes Rudolph
I don't think it's that necessary to create a class to hold a method parameter.
ZZcat
I'd only create the class if there were multiple instances of passing the same parameters. This would signal that the parameters are related and probably belong together anyway. If you are creating a class for a single method the cure is probably worse than the disease.
tvanfosson
Yes - you could move related params into a DTO or Value Object. Are some of the multiple params optional i.e. the main method is overloaded with these additional params? In such cases - I feel it is acceptable.
JoseK
That's what I meant by saying must be meaningful enough.
Johannes Rudolph
+18  A: 

Using a map with magical String keys is a bad idea. You lose any compile time checking, and it's really unclear what the required parameters are. You'd need to write very complete documentation to make up for it. Will you remember in a few weeks what those Strings are without looking at the code? What if you made a typo? Use the wrong type? You won't find out until you run the code.

Instead use a model. Make a class which will be a container for all those parameters. That way you keep the type safety of Java. You can also pass that object around to other methods, put it in collections, etc.

Of course if the set of parameters isn't used elsewhere or passed around, a dedicated model may be overkill. There's a balance to be struck, so use common sense.

tom
A: 

Using a Map is a simple way to clean the call signature but then you have another problem. You need to look inside the method's body to see what the method expects in that Map, what are the key names or what types the values have.

A cleaner way would be to group all parameters in an object bean but that still does not fix the problem entirely.

What you have here is a design issue. With more than 7 parameters to a method you will start to have problems remembering what they represent and what order they have. From here you will get lots of bugs just by calling the method in wrong parameter order.

You need a better design of the app not a best practice to send lots of parameters.

dpb
+2  A: 

There is a pattern called as Parameter object.

Idea is to use one object in place of all the parameters. Now even if you need to add parameters later, you just need to add it to the object. The method interface remains same.

Padmarag
+6  A: 

First, I'd try to refactor the method. If it's using that many parameters it may be too long any way. Breaking it down would both improve the code and potentially reduce the number of parameters to each method. You might also be able to refactor the entire operation to its own class. Second, I'd look for other instances where I'm using the same (or superset) of the same parameter list. If you have multiple instances, then it likely signals that these properties belong together. In that case, create a class to hold the parameters and use it. Lastly, I'd evaluate whether the number of parameters makes it worth creating a map object to improve code readability. I think this is a personal call -- there is pain each way with this solution and where the trade-off point is may differ. For six parameters I probably wouldn't do it. For 10 I probably would (if none of the other methods worked first).

tvanfosson
+4  A: 

It's called "Introduce Parameter Object". If you find yourself passing same parameter list on several places, just create a class which holds them all.

XXXParameter param = new XXXParameter(objA, objB, date1, date2, str1, str2);
// ...
doSomething(param);

Even if you don't find yourself passing same parameter list so often, that easy refactoring will still improve your code readability, which is always good. If you look at your code 3 months later, it will be easier to comprehend when you need to fix a bug or add a feature.

It's a general philosophy of course, and since you haven't provided any details, I cannot give you more detailed advice either. :-)

dimitko
+13  A: 

alt text In Effective Java, Chapter 7 (Methods), Item 40 (Design method signatures carefully), Bloch writes:

There are three techniques for shortening overly long parameter lists:

  • break the method into multiple methods, each which require only a subset of the parameters
  • create helper classes to hold group of parameters (typically static member classes)
  • adapt the Builder pattern from object construction to method invocation.

For more details, I encourage you to buy the book, it's really worth it.

JRL
A: 

Create a bean class, and set the all parameters (setter method) and pass this bean object to the method.

Thomman
A: 

This is often an indication that your class holds more than one responsibility (i.e., your class does TOO much).

See The Single Responsibility Principle

for further details.

Helper Method
A: 

If you are passing too many parameters then try to refactor the method. Maybe it is doing a lot of things that it is not suppose to do. If that is not the case then try substituting the parameters with a single class. This way you can encapsulate everything in a single class instance and pass the instance around and not the parameters.

azamsharp
+1  A: 

If you have many optional parameters you can create fluent API: replace single method with the chain of methods

exportWithParams().datesBetween(date1,date2)
                  .format("xml")
                  .columns("id","name","phone")
                  .table("angry_robots")
                  .invoke();

Using static import you can create inner fluent APIs:

... .datesBetween(from(date1).to(date2)) ...
Ha
A: 
  • Look at your code, and see why all those parameters are passed in. Sometimes it is possible to refactor the method itself.

  • Using a map leaves your method vulnerable. What if somebody using your method misspells a parameter name, or posts a string where your method expects a UDT?

  • Define a Transfer Object . It'll provide you with type-checking at the very least; it may even be possible for you to perform some validation at the point of use instead of within your method.

Everyone
A: 

Code Complete* suggests a couple of things:

  • "Limit the number of a routine's parameters to about seven. Seven is a magic number for people's comprehension" (p 108).
  • "Put parameters in input-modify-output order ... If several routines use similar parameters, put the similar parameters in a consistent order" (p 105).
  • Put status or error variables last.
  • As tvanfosson mentioned, pass only the parts of a structured variables ( objects) that the routine needs. That said, if you're using most of the structured variable in the function, then just pass the whole structure, but be aware that this promotes coupling to some degree.

* First Edition, I know I should update. Also, it's likely that some of this advice may have changed since the second edition was written when OOP was beginning to become more popular.

Justin Johnson