lundi 23 mars 2015

Method extraction


When I split big methods (or procedures, or functions — this question is not specific to OOP, but since I work in OOP languages 99% of the time, it's a terminology that I'm most comfortable with) into a lot of small ones, I often find myself displeased with results. It becomes harder to reason about these small methods than when they where just blocks of code in the big one, because when I extract them, I loose a lot of underlying assumptions that come from the context of the caller.


Later, when I look at this code and see individual methods, I don't immediately know where are they called from, and think about them as ordinary private methods, that can be called from anywhere in the file. For example, imagine initialisation method (constructors or else) split into a series of small ones: in the context of method itself, you clearly know that object's state is still invalid, but in an ordinary private method you probably go from assumption that object is already initialised and is in a valid state.


The only solution I've seen for this is where clause in Haskell, which allows you do define small functions that are used only in the "parent" function. (I'm a complete newbie in Haskell, please correct me if I make any mistakes here). Basically, it looks like this:



len x y = sqrt (sq x + sq y)
where
sq a = a * a


But other languages I use don't have anything like this — the closest thing is defining a lambda in a local scope, which is probably even more confusing.


So, my question is — do you encounter this, and do you even see this is a problem? If you do, how do you typically solve it, particularly in "mainstream" OOP languages, like Java/C#/C++?


Edit about duplicates: As others noticed, there are already questions discussing splitting methods and small questions that are one-liners. I read them, and they don't discuss the issue of underlying assumptions that can be derived from caller's context (in example above, object being initialised). That's the point of my question, and that's why my question is different.





Aucun commentaire:

Enregistrer un commentaire