by quelsolaar · 6y ago · 0 comments
There is a reason regular front-to-back books are more popular then choose-your-own-adventure books. You know where you are, and you dont spend all day flipping back and forth.
I also find that when you start splitting up your functions down to 5 lines, it becomes almost impossible to differentiate what the different functions do clearly, and that makes good naming almost impossible.
EDIT: Also, I dont understand why people complain about functions being longer then 5 lines making code hard to navigate, and then turn around and write header only files with 10000 lines of code....
If I'm reading a novel, it would be jarring to read "and then he took 45 steps of average length to reach the kitchen" instead of "he went to the kitchen".
Of course, for certain tasks long functions are still reasonable, but they tend to be the exception rather than the rule, and it takes quite some practice to realize.
Best practical advice: do more design and planning on paper.
Easier to test usually, too.
That's a bad example. A better example - and yes, I'm totally biased - is the main() method for the rebuild I'm working on - it's basically 'read config', 'set up logger', 'set up service x', 'set up service y', 'validate runtime dependencies like files and scripts', 'create & start http server', 'wait for shutdown signal', 'gracefully shut down http server on shutdown signal', etc. All in one place, no need to extract methods in my opinion. That said, it really is not the critical path of the application.
MajorFunction() {
// fast inverse square root
float x2 = number * 0.5F;
float y = number;
// several more lines of code
// find decimal point
char *c = input;
while (*c && *c != '.')
++c;
}
A goal of style A or B is for the names of the minor functions to make the shape more obvious, ideally self documenting: MajorFunction() {
y = Q_rsqrt(number);
char *c = strchr(input, '.');
}
This is the kind of advice you'll find in, say, Code Complete. Although I generally accept the premise, there is a readability cost to indirection. The bigger and more complex MinorFunction() is, the more likely I'm going to have to jump into it and remind myself what it does.There are two concepts that underlie DRY: coupling and cohesion. There are good expositions on this in old writings on structured programming and design (e.g., Yourdon and Constantine). If MinorFunction() is cohesive, and MajorFunction() is appropriately coupled to MinorFunction(), then style A/B is likely to be superior to style C. One of Carmack's points is that "very little of our real code" ends up that way.
But then some people will say that you're testing the internals of the caller and that you shouldn't do that. If we follow that logic to the absurd, there should only be one test for the entire application, one for main(), or whatever your entry point is.
I've never seen an answer to this problem coded as an intelligible, easy-to-follow guideline. Empirically and intuitively I think my "hotspot" approach kinda works in maximizing reliability.
But I don't think I'd like writing long functions as a system or philosophy; I think there is a threshold where a function becomes fat enough that it hurts readability.
Code is an art form.
As you said, organizing code is an art form. There are no hard and fast rules, only your own judgement and experience.
> Enclosing pages of code inside a conditional or loop statement does have readability and awareness drawbacks
I don't think that has anything to do with it. It's a roleplaying adventure where you need to keep track of things on a piece of paper and use dies for encounters. People that want to read don't want to participate, just consume. Active vs passive.
Regardsless, splitting 4-5 lines of code out into a function and giving that a proper name can enhance readability significantly. And modern IDE tools make it simple to read that without disrupting the flow. Visual Studio and IDEA for instance has a peak definition that makes it trivial.
If that function does not do what it say, that is a different problem.
If the function doesn't need to be called many times, it doesn't need to exist.
I prefer clear naming over comments, because comments doesn't "travel" everywhere the named function/type/variable does.
Especially if you don't need reuse (or if you only need it in a very limited fashion) nor unitary testing, you can handle things using different techniques than splitting into functions. Like simply having a succession of blocks in a bigger function, with inline notes about invariants between each blocks, etc.
If done in a disciplined way I don't see much avantage about that approach than about just using functions anyway, esp with a good IDE or code editor. Of course nothing is absolute but if it does not fit on a screen maybe at least consider splitting it (and improving the doc, etc.; or at least just improve the doc). Blindly requiring e.g. 5 lines max strictly everywhere is insane though, never do that. There can be excesses on both sides.
As a more personal rule of thumb, I avoid splitting things too much esp. if the result takes more lines than inline versions, except if not splitting results in a high number of duplications (small in that case, but still duplications). A moderate increase of LOC when splitting is OK but when trying to split like crazy you can fall to N fold increases and at some point this is sometimes counter productive. On the other hand some very moderate amount of code duplication is ok, at least if the duplicated parts are not too far away and can be found easily, and not in an unreasonable quantity, modulated by the size of duplications. For extremely tiny duplications even in huge quantity, replacing by a function call does not necessarily makes sens, if e.g. that's (i + base) % mod repeated 30 times in the same file maybe it would give no advantage to replace that with rotbufindex(i, base, mod), the call is not more easy to reuse than the inlined formula.
Don't break stuff up for the sake of it, but DRY.
In analysis using the structured program theorem, you only have three tools, really: Sequence, selection, iteration. If you copy-paste, you lean on the sequence more; if you add a loop or a cursor structure, you're iterating; and if you add more names for things, you're selecting on the name. All three create dependency risks, but not in equal measure.
What a really long function mostly indicates is that the inherent dependencies are mostly sequential. This maps with the domains where they appear most naturally: game loops are notoriously single-threaded, embedded code often needs to operate to hard real time constraints.
I think the appeal in splitting out more names has something to do with linguistic comfort zones: Rather than examine long sequences, assume the functions used by the one you are looking at are trustworthy. Then you are "improving" the code each time you factor it out because you can read more names, and because each function is small there is little concern about sequencing errors. It's intuitive, but shows its flaws as soon as you use another lens like the structured program analysis; adding the new function makes it harder to examine the sequence across the function boundaries, causing the "flea-jump" code you describe.
What I've found works is to let the large functions accumulate and mature, then derive a new dependency - a function, class, or other abstraction - that will simplify maintenance. Not every problem is solved with a new function, sometimes it really takes a compiler to get the desired improvement.
You end up with the same amount of code, but now you have to jump around. In most cases it also forces you to turn local variables into instance variables, globals, or pass state in parameters in order to carry state between the new functions, which further decreases readability.
You might as well add an "index" at the top of the large function and get the same readability benefits from doing it.
What should be done instead is trying to find code that can be abstracted without hurting readability. Most of the time in large functions there are mixed abstraction levels, such as business logic mixed with I/O, generic error handling that could be somewhere else, or object transformation that exists because of different libraries working differently.
When you automatically refactor into smaller functions you carry those problems into the small functions and you get code that is probably harder to follow, generates worse stack traces and only looks good in a shallow inspection.
If your function does an unexpected side effect, thats a problem with the code. Not with the idea of writing functions that do a specific thing.
I can't help but think people who complain about this, are just bad at creating functions at the correct level of abstraction.
It's also why i'm a functional fan, because it makes it more difficult for functions to do unexpected things.
I understand the argument to be that by breaking everything out into functions it makes it too easy to hide what is actually going on and you can miss a lot of fine detail. If your code looks like
x=doA();
y=doB(x);
z=doC(y);
then it becomes very hard to spot for example that both functions doA and doC recomputed the same intermediate value that you could just compute once and reuse or that doB validates its input, but in this case you know it's unnecessary to do so, since you know that doA can only return data that is valid for doB. If everything was inline then these things would jump out at you a lot quicker.Of course in many cases this doesn't matter and recomputing that intermediate value twice costs so little in the grand scheme of things that the extra readability is worth it.
They are complaining due to difficulty of reading other peoples' code, not their own.
> You can just skip over it
The point is that if I blindly break a larger functions by functionality, I still have to understand the deeper functionality. So, I can't just skip when I'm debugging or deeply reviewing/inspecting the code, or doing a rewrite or trying to understand it.
> I can't help but think people who complain about this, are just bad at creating functions at the correct level of abstraction.
My point was exactly that you should create functions at the correct level of abstraction, rather than just splitting large functions purely by functionality, like you would with a cooking recipe.
> If your function does an unexpected side effect, thats a problem with the code
But this is exactly what I'm trying to avoid. If you need side effects, keep them visible, by keeping them in the main function, instead of just blindly putting them into smaller functions.