Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Limit on # of Methods?  RSS feed

 
Nathan Leniz
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any kind of style guidance regarding the number of methods one should use before breaking them up into different variables?



Any guidance would be appreciated. I know what I want to do, but I'm working on a project with others and I don't want to be writing in hieroglyphs.
Edited to remove evidence of typing while drunk.
[ January 01, 2007: Message edited by: Nathan Leniz ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
google for "law of demeter"
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, i'd say one. I'm sure others will disagree.

When you chain calls together like this, what happens when one call fails, or returns a null? you get an error message like:

NPE on this line: methodA().methodB(methodC(methodD(something))).methodE()

you have no idea which of the 5 methods failed, and it can be a bear to fix. One of my mentors from years ago always said "one line should do one thing".

Yes, it sometimes makes for code that looks a little strange, but doing it that way has usually served me pretty well.
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For me, there is not a single answer. It depends on how complex and expensive the methods are and how readable the code is.

If a method in the chain is complex, somewhat likely to fail, or the result needs to be logged, I'd separate it out.

If the method is a simple method like a .toString() on an object that can't be null, I see no reason not to inline it.

If the method is expensive to execute, is called multiple times and you can save time by storing the result, then do so.

If the intent of the code is obscured by chaining the methods, then break the methods out into separate lines.

I think it's a judgment call that has to be made on a case-by-case basis.
[ January 01, 2007: Message edited by: Scott Johnson ]
 
Dan Fowler
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree that it is an issue that should be taken on a case-by-case basis, but I personally say one. One reason I say this is because it can make code a lot easier to debug if you just do one thing per statement.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!