Get方法的大小 [英] The size of a Get method

查看:139
本文介绍了Get方法的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码行方面,对于获取"的大小是否存在任何准则或普遍共识?我在一个成员上有一个Get方法,该成员在这里很容易增长到30行代码.我不确定应该在什么时候将其提取到方法中.但是然后,我只能像GetMyString这样调用它,然后将值分配给另一个成员,然后无论如何都要在构造函数中调用它.

Are there any guidelines or general consensus towards the size of a 'Get' in terms of lines of code? I have a Get method on a member that has quite easily grown to 30 lines of code here. I'm not sure at what point this should be pulled out into a method. But then I'd only be calling it something like GetMyString and assigning the value to another member and calling it in the constructor anyway.

这样做值得吗?

这对SO来说是否过于主观?

Is this too subjective for SO?

推荐答案

dcastro的答案很好,但可以使用一些扩展:

dcastro's answer is good but could use some expansion:

  • 很快就可以回来

这是无法量化的;让我们量化一下.一个属性所花的时间不应比获取字段所花费的时间长十倍.

That's not quantified; let's quantify that. A property should not take more than, say, ten times longer than it would take to fetch a field.

  • 它未连接到外部资源(数据库,服务等)

这些都是缓慢的,因此通常属于第一条规则,但这有第二个方面:失败应该很少发生或不可能发生.属性获取器不应引发异常.

Those are slow and so typically fall under the first rule, but there is a second aspect to this: failure should be rare or impossible. Property getters should not throw exceptions.

  • 它没有任何副作用

我要澄清这是为了可观察的副作用.属性获取器通常会产生副作用,即它们只计算一次属性并将其缓存以备后用,但这并不是可观察到的副作用.

I would clarify that to observable side effects. Property getters often have the side effect that they compute the property once and cache it for later, but that's not an observable side effect.

从哲学上来说,使属性具有可观察到的副作用是很不好的,它还会使您的调试体验变得混乱.请记住,默认情况下,当您在调试器中查看对象时,调试器会自动调用其属性getter并显示结果.如果这样做很慢,则会减慢调试速度.如果这样做可能会失败,那么您的调试经验将充满失败消息.而且,如果这样做有副作用,则调试程序会更改程序的工作方式,这可能会使查找错误非常困难.您当然可以关闭自动属性评估,但是最好首先设计好的属性.

Not only is it bad philosophically for getting a property to have an observable side effect, it can also mess up your debugging experience. Remember, when you look at an object in the debugger by default the debugger calls its property getters automatically and displays the results. If doing so is slow then that slows down debugging. If doing so can fail then your debugging experience gets full of failure messages. And if doing so has a side effect then debugging your program changes how the program works, which might make it very hard to find the bug. You can of course turn automatic property evaluation off, but it is better to design good properties in the first place.

这篇关于Get方法的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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