If a method has too many parameters, the suggestion is to convert them into a parameter object. Where to place such parameter objects? in domain/entity classes package? or if I have a separate package for DTO's, should I place there?

  • I usually have'em in separated packages. DTOs may or may not be directly related to the domain model. It's closer to mid/upper layers than core. – Laiv May 28 '16 at 9:12

In layman's terms:

I'd suggest you put it in the same package as the class whose method, having initially such a long signature, originated the need for such a paramter object.

Parameter classes are classes nonetheless are they belong to the package where the rest of related classes are located. It doesn't matter whether or not they have behavior whichm by the way, they could end up having down the road.

| improve this answer | |

First thing I try to do is to somehow conceptualize the parameters into one or more cohesive classes. Let's say we have method like this:

public void sendEmail(String firstName, String lastName, String email, String subject, Map<String, String> headers, String body)

I can see two cohesive groups of parameters. It makes sense to create kind of "concepts" from these - User and EmailMessage. These concepts (classes) seem quite reusable (they might even already exist!) so I put these into dto package.

Of course, this example is trivial, reality is more complex, but it is often possible to create meaningful and cohesive concepts after some thinking.

If you can't find reasonable concepts in the parameters, it might be sign of code smell. Method is trying to do too much etc.

But let's say the design is good but you still have a lot of parameters. These cases happen. You create parameter class, it's used only in one of your methods signatures. In that case I often put this class as inner static class near its usage in the method's signature (in class or interface) - e.g. directly above it.

Alternatively you can also put this into a dto package. In my opinion, these cases should be rather rare and it's kind of OK either way. You won't find single definite solution unfortunately.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.