I am having a开发者_JAVA百科 method in which there are more then 7 parameters ,type of all the parameters are different. Well my question is it fine or i should replace all parameters with the single class(which will contaion all parameters as a instance variable).
Well my question is it fine or i should replace all parameters with the single class
7 is way too much. Replace with a class. With my VS custom theme and fonts settings Intellisense wouldn't fit on the screen when there is a method with so many parameters :-) I find it more readable and easier to understand when working with classes.
Of course those are just my 2 cents and it's subjective. I've seen people writing methods with many many parameters.
Well, there are places where I'd consider that okay - but they're few and far between. I would generally consider using a "parameter class" instead.
Note that it doesn't have to be an "all or nothing" approach - would it make more sense to encapsulate, say, 4 of the parameters together? Would that allow the new class to be used in other methods?
Other thing to consider is whether the method might be doing too much - does the functionality of the method definitely feel right as a single cohesive unit?
Thare are Microsoft APIs with even more parameters; anyway I agree with @Darin, a class could be a good solution, clear and efficient that can avoid passing parameters in the right order... so for example if you change order for oen without using refactoring you're in a mess...
Consider also if that class can be used in other parts of the program...
I somewhat agree with all given answers. However it might be a good idea to break down the method into smaller parts as Jon is suggesting. Usually when you have a situation like this means that the method is doing too much. Typically methods should have 1 or 2 parameters at most. While you would achieve the same by replacing all your parameters with a class parameter you might just be hiding the bigger issue. Is there any chance you can post the method or describe what it's doing?
As a rule of thumb, if you can't fit the entire method, including declaration onto 1 screen, it's too big. Programmers will normally recommend to break down methods to make them reusable. But, it also makes perfect sense to break them down to increase readability.
精彩评论