4

A method signature is part of the method declaration. It is the combination of the method name and the parameter list.

So instead of specifying a list of parameters, I just want to pass a request object which constitute all the parameters. It might not be true for all the methods, but want to try wherever it is possible.

Say for example

public void setMapReference(int xCoordinate, int yCoordinate)
{
  //method code
}

can also be written as

public void setMapReference(Point point)
{
  //method code
}

class Point {
  int xCoordinate;
  int yCoordinate;
  boolean isValidPoint();
}

But the caller may confuse as he is not aware of the parameters..!!

Is it a good practice???

Péter Török
  • 114,404
  • 31
  • 268
  • 329
Pradeep
  • 187
  • 1
  • 1
  • 7

3 Answers3

7

I wouldn't do it "wherever it is possible" - but it's often a good idea, yes. Basically, ask yourself whether the parameters themselves constitute a coherent single entity: does it make sense to lump them together and think of them as a single "thing"? If so, encapsulating them sounds like a good idea. It's even better if there's obvious behaviour which that "thing" could take responsibility for, to avoid that code living in a class which already has other responsibilities.

EDIT: Note that I wouldn't let the Point type have package-access fields as you've shown: I'd make them private fields with properties, as normal. I'd try to make it immutable if possible.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yeah, But the problem is...If I encapsulate all the parameters in the request object, then if I add any attribute to the request object(when needed), The callers of the method don't aware of the change, and not able to depict the problem as a compile time error. And the error will be promted at rum time. – Pradeep Sep 01 '10 at 11:26
  • 1
    @Pradeep: If you make all the mandatory values in the "request object" required as part of that object's constructor, then it will break the callers as you probably want. – Jon Skeet Sep 01 '10 at 18:14
0

If there's only 2 parameters, leave it alone. Object parameter may cause complex, maybe you even need defensive copy for object parameter.

On other hand, most programmer couldn't remember parameters more than 3, if there are same data types in parameters, it's worse and error prone for programmers. In this case, using object parameter is good idea.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
0

Some answers to the question Building big, immutable objects without using constructors having long parameter lists are probably relevant here also (it doesn't really matter if you're dealing with methods or constructors, a constructor is just a special method, after all).

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588