开发者

Having one request object as a Method Signature parameter, which constitute all the required parameters

A method signature is part of the method declaration. It is the combination of the method name and the para开发者_运维问答meter 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???


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜