What is the limit N of maximum methods you allow in your classes?

谁说胖子不能爱 提交于 2019-12-05 22:59:12

You don't have to limit N of maximum. But you have to follow 'High Cohesion' principe. And don't create all-can-do-whatever-it-is classes.

I suppose there is some N after which you should start worrying. But it is really depends on the class itself and its primary goal.

The idea that there's a magic number that we can base a Rule on is the usual squeamishness from those whose desire to impose order on the universe outweighs their sense.

That said, if you have more than 20 or so methods in a class, there's a good chance it's doing too much and violating the SRP.

I wouldn't put an arbitrary limit on things either, but I would say that once a class has more than somewhere in the 10-20 public methods range I'd take a serious look at what that class is doing. Back in my J2EE days, we called them Enterprise Java Melons.

Same rule applies for the length of individual methods. I've seen classes that had only one or two methods, but each of those methods was hundreds of lines of code.

Since I started breaking classes down to a single responsibility, I don't usually approach a place where it gets questionable.

Also, a well-designed class may have 30 methods, and a poorly designed one may have 3 (Umm, 30 is pushing it, but the point is--this isn't necessarily even a good metric, kind of like counting kloc)

Your framework / language can necessitate a lot of methods without business logic too.

Counting the number of non-trivial methods with business logic in them might be interesting--I'd say around 4 or 5 would be appropriate.

I was surprised how many methods the JDK classes actually have in them when I was looking at the source code, but they are so well broken, so small and so easily read that it wasn't a problem at all to have 20.

Like others have pointed out there generally isn't some arbitrary number of methods at which point I'll say "That's too many methods!" Sometimes the opposite can be just as bad, such as when an object has a monolithic do-everything method that spans hundreds of lines.

That being said, if I open up a source file I haven't looked at before and see more than 10-20 methods I will probably scan through it to see if it can't be re-factored in some way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!