重构具有太多(6+)参数的方法的最佳方法是什么? [英] What's the best way to refactor a method that has too many (6+) parameters?

查看:45
本文介绍了重构具有太多(6+)参数的方法的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会遇到参数数量不合适的方法.通常情况下,它们似乎是构造函数.似乎应该有更好的方法,但我看不到它是什么.

Occasionally I come across methods with an uncomfortable number of parameters. More often than not, they seem to be constructors. It seems like there ought to be a better way, but I can't see what it is.

return new Shniz(foo, bar, baz, quux, fred, wilma, barney, dino, donkey)

我曾想过使用结构来表示参数列表,但这似乎只是将问题从一个地方转移到另一个地方,并在此过程中创建了另一种类型.

I've thought of using structs to represent the list of parameters, but that just seems to shift the problem from one place to another, and create another type in the process.

ShnizArgs args = new ShnizArgs(foo, bar, baz, quux, fred, wilma, barney, dino, donkey)
return new Shniz(args);

所以这似乎没有改进.那么最好的方法是什么?

So that doesn't seem like an improvement. So what is the best approach?

推荐答案

最好的方法是找到将参数组合在一起的方法.这假设并且实际上仅适用于您最终会得到多个分组"参数的情况.

The best way would be to find ways to group the arguments together. This assumes, and really only works if, you would end up with multiple "groupings" of arguments.

例如,如果您要传递一个矩形的规范,您可以传递 x、y、宽度和高度,或者您可以只传递一个包含 x、y、宽度和高度的矩形对象.

For instance, if you are passing the specification for a rectangle, you can pass x, y, width, and height or you could just pass a rectangle object that contains x, y, width, and height.

在重构时寻找类似的东西来清理它.如果确实无法合并参数,请开始查看您是否违反了单一职责原则.

Look for things like this when refactoring to clean it up somewhat. If the arguments really can't be combined, start looking at whether you have a violation of the Single Responsibility Principle.

这篇关于重构具有太多(6+)参数的方法的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆