开发者

tips on reducing the number of parameters passed into a function

HI,

I'm working on a AS3 project, ori开发者_StackOverflow中文版ginally written by someone else. I'm re-writing one of the functions in a class. This function creates a simple value object, but the function takes in 16 parameters which is a mess.

What is a good way to re-write this so it looks neater and is more read about?

Thanks

Stephen


Or perhaps, if there's an obvious relationship between the parameters, create a class. Instantiate the class, fill in the values, then pass the object.

Instead of

myfunc(p1, p2, p3, p4, p5, ..., p16);

you get

c1 = new c1();
c1.p1 = val
c1.p2 = val
...
c1.p16 = val

then you call

myfunc(c1);


I'd go for the following:

  1. Check if some parameters can be spared (not used, duplicates, can be retrieved other way), with 16 parameters I wouldn't be surprised if some of them are redundant.
  2. Check if some of the parameters are logically connected to each other. It may worth to create an object containing them all. In case the same set of parameters travels to other functions as well, then you have a winner.
  3. Check the design of the class, it could be that some of them should be class members.


I'd go either for Chaining http://en.wikipedia.org/wiki/Method_chaining, passing anonymous object with variables set, like:

someFunction({id:1, pizzas:"1", types:["triple cheese"], location:"sun"});

Or, like someone mentioned, Value Objects http://en.wikipedia.org/wiki/Value_object, depending on how you like your code :).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜