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:
- 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.
- 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.
- 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 :).
精彩评论