I will agree that if you are coding in the kind of environment Carmack is talking about, where you are writing code which interacts with massive shared global state, that purely procedural structured code is easiest to understand, because you can be sure that you can see all interactions with global data structures in one place.
But if you don't have massive shared global state, I'd argue that calling subfunctions is a hugely valuable aid to understanding, since it allows you to reason much more about the way data dependencies flow through code when you can be sure that a call to a function means that that function can only act on the data structures passed in to it and is guaranteed not to affect anything else. I would much rather in that case see:
a = subOperationA(arg)
b = subOperationB(a)
c = subOperationC(a, b)
d = subOperationD(b, c)
return d
than see those three suboperations inlined and have to figure out for myself how the data dependencies flow through the code. a = subOperationA(a, b, c, d, e, f, g, h, i)
b = subOperationB(a, d, e, f, g, h, i, j, k)
c = subOperationC(d, e, f, g, h, i, j, k, l)
return c
And then some poor fool breaks each of those up into about 8 functions each. So, you click into subOperationA to find it is subOperationAa chaining to subOperationAb,....My gripe is when we argue against having the full solution in your mind as you work the pieces. Logically, it makes sense to reduce everything down to named things. Cognitively, that is expensive.
And yes, I'm responding with an equally opposing strawman. I am beginning to reject that there is a "one true answer."
For example, adding two n-length vectors is a good abstraction ("vector_add"). Adding two n-length vectors then multiplying the magnitude of the result by 3 is a bad abstraction.
There are basically no guidelines that always apply. Novices should stick to them, and people with more experience can recognize when they don't apply.
I like Jens Gustedt's proposal for annonymous functions in C (at the end of Modern C[1]) by extending the syntax for compound literals. That would in a way give parameterized blocks, except that what you pass would be at the end (although if you name the parameters the same as what you pass it should work).
I think the main point is that it is helpful to be able to easily follow all the code that executes from point A to point B (at least up to the point of whatever portability layer you use). If you can reasonably structure it so that you just need to hit page down to read that code (without duplicated code) then that will often be easier to read IMO. I don't find one or two levels of function calls to be hard to follow, but after that it quickly gets more difficult. I suspect preferences here may to some extent be influenced by how good your short term memory is (and how good your IDE is). But I suspect there are also significant differences in how often different programmers try to step through code.
[1] http://icube-icps.unistra.fr/img_auth.php/d/db/ModernC.pdf
int a,b,c;
// ...
[a, &b]() {
// do stuff
}();* abstract class Connection would have maybe 3 or 4 methods;
* DataConnection would extend Connection and add a couple more methods that were specific to some proprietary protocol.
* POSDataConnection would extend DataConnection and wrap this proprietary protocol for POS machines
* ControllerDataConnection would extend POSDataConnection because a Point of Sale controller is technically a POS machine with a bit more functionality (Really just a couple flags turned on).
* There was plenty more in between; it's been so long now that I've forgotten it all.
It's just like we all learned in college! Object Oriented programming is supposed to model real-life! Except no, it's not. That's stupid and complicated.
Now the part of the OS that was C/C++ was absolutely beautiful. It took the UNIX style of programming / applications seriously; every little piece was its own program, and it worked flawlessly. Anyone could jump in and get to work immediately because it was so well written. You could follow any program top to bottom and it just... made sense!
My god.
A lot of these fancy language features sound good on paper but can be so abused that even just coming to understand the code takes up too much space in your head.
Also gofmt having the last word on what code is acceptable and what isn't helps kill a lot of arguments that aren't worth having.
https://www.youtube.com/watch?v=rFejpH_tAHM is a good overview.
It is - in execution (message passing), not in taxonomies. You can't model the taxonomies because all set-in-stone languages are inadequate for that (see SICP, for example). Also, it sounds like someone had an inheritance mania on your project. That's an instant loss right there. (But maybe the language used didn't allow for anything better? C++ is notoriously bad in this respect, for example.)
That is definitely the way I was taught OOP in college. I came out thinking it as a steaming, overcomplicated pile of shit. I have since learned better. Of course, there is a whole world of enterprise programmers for whom what was described is "proper" OOP.
It is what I had to deal with, though.
These languages, as well as things like WSDL/SOAP, are the late 90's/early 00's snake oil designed to woo clueless manager-types into funneling money to consultants and 'architects'.
I worked a lot with those types and saw the futility of suggesting 'simple' solutions to simple problems - everything had to be over-complicated to justify their salaries.
It left me pretty bitter towards that whole business model. Then again, there's lots of money to be made there....
interface -> abstract -> base -> TheOnlyImplementationInstantiated
Repeat for a couple more chains, and one line bug fixes require visiting a dozen files to figure out.In code as in life, all in moderation.
> In code as in life, all in moderation.
Beautifully said. Both methods (procedural vs. object oriented) give you different ways to shoot yourself in the foot. Instead of picking one or the other, it's more important to manage the scope at which your project grows. You have to avoid falling into the traps of each style.
If you modify your example to 400 nested 10-line function calls, how does that change your comparison?
But sometimes it is just a "Such is life" situation.
If a functional language, I'd prefer each being its own function, with the case matching in a single, standalone file that returns the appropriate function based on whatever. That way you still get just apply_tax_rate(type, amount) in your main calculation function.
My "problem" is an online store. It is about 75,000 lines of code. It needs all 75,000 to solve the problem. What you are saying is that it would be "somewhat" hard to deal with whether it is all in one big function or many functions.
But in reality, one big function would be incomprehensible. It is vastly easier to deal with broken out into many functions.
However you end up solving it, it is way to big for a single function. On the other hand, a moderate bunch of functions can do it nicely -- and at that scale you don't need big complicated object-oriented abstractions other than the external interface itself.
Related:
[1]: https://dubroy.com/blog/method-length-are-short-methods-actu...
You can only do it one at a time, and it's for quick scanning of what the function does, though.
Oh, I want to frame this and put it on the wall.
I can't stand code where even the simplest thing is implemented as a giant tree of sub-5-line functions nested 15 deep (and probably, for bonus points, scattered across half a dozen files).
config_filename = get_config_filename()
config = read_config(config_filename)
endpoint_url = config["endpoint_url"]
auth_data = get_auth_data(endpoint_url)
to just dumping all of that inline.
I've used the same technique - instead of creating a function that might be awkward due to all the inputs and outputs, I'll create an inner scope {} with nothing around it. Only the variables that it modifies/initializes are left on the outside. This is a simple way to enforce more of a data flow style within a function and ends up being a useful organizational tool. It is also similar to 'let' in some languages.
If your methods are functional, then
int fancyNumber = calculateFancyNumber();
Can be inclined cleanly/equivalently as: int fancyNumber;
{
// [Mathy stuff redacted]
fancyNumber = someIntermediateVariable / anotherIntermediateVariable;
}[&fancyNumber] { // [Mathy stuff redacted] fancyNumber = someIntermediateVariable / anotherIntermediateVariable; }();
If it turns out said little dance needs to be done twice, instead, assign the function expression to a name (in an appropriate scope) and call it twice.
Nested funcs/procs in Pascal were useful for this kind of local partitioning, as well (before C; C++; Java came and peed in the development mindshare pool), even if you couldn't make closures out of them.
Yep, namely when someone fixes a bug in one of the paths but forgets to update the second.
It really depends on how long the function is. Ignoring stuff like variable declarations and verifying constraints at the beginning of a function, I personally find anything longer than a screen or two is usually better off (in terms of readability) being in its own function.
I have come to interpret this as: We are language designers. This isn't about functions. This is about building a language for the business case that is comprised of primitive expressions, means of combination, and means of abstraction. If the language is clear to the reader, expressing the problem well, it should be easier to detect problems or extend the existing language and its uses.
We are language designers already: If you build a traditional class with a bunch of methods, that is a language with how to deal with the concept embodied by the class. It must be held to the same standards of any language, DSL, or API design.
I like to remind people that we don't tend to dig into the code behind printf(); we trust what it does. We have years of experience using that primitive. It's a great example of a function that has been through many revisions due to security issues, untrustworthy in its inception. What is key here is trust that a primitive does as advertised so that one does not have to dig into its source code repeatedly. Nested functions are not an issue in the presence of trust.
My "secondarily" clause has a fatal flaw: Many languages are not suited for building languages while simultaneously not trading off speed and resource usage. The ones with pre-runtime macros/templates assist us developers in the building of expressions beyond the limitations of the base language with minimal fuss.
Heh. Anyone up for a Sussman&Abelson drinking game? :D
Abstracting with functions is very beneficial to the writer because, well, they come up with the abstractions and know what they mean.
I feel they are less helpful to the reader, except perhaps at a very cursory level. If the reader is trying to actually understand the code to be able to modify it, many abstractions are actually a hindrance.
For example, in lisp, it's a fairly common practice to essentially write a DSL for the problem you are solving. It's a great tool to be able to do this easily and quickly. You can build massive and complex programs without overloading your brain.
However, for a reader new to your code base, there is a huge cognitive load to try to decipher the DSL. It's intuitive for the writer, because they invented it, but for the reader, it is a hurdle to overcome.
Once you learn someone's DSL, it's a very powerful tool now for you too. But when every project has it's own, it's really too much to bear.
The article includes comments from Carmack from 2014 saying he now favours breaking the code up into pure functions.
Nested functions can actually allow you to even out your abstraction levels... Just group lower-level operations in more deeply nested functions. It's sort of the functional equivalent of extracting a group of similarly-leveled concepts into a new object in the OO approach.
Not sure if you were talking about C++, where my point probably doesn't apply... (Lack of nested function support, AFAIK)
If another developer joins the team, then he might not have noticed that there is a taskY and may end up writing his own, completely different, implementation in yet another place.
For C, I tend to go the big function route but I usually try to put extra braces with comments to isolate subtasks from each other within the big function. Then I can pull out the tasks into functions if I see that I need them in more places. I don't know how my old code is doing so I don't know if anyone has followed my lead in those projects.
It's a big motivator in terms of deciding up best practices. And whenever I fix a bug, I try to identify the root cause. If it was a coding pattern to blame (as opposed to bad process or design) I look for ways to eliminate that pattern.
I hand wrote a LA(1) style parser (and lexer) for JSON, because I wanted to experiment with a source code generation notion I had (vs reflection, or bytecode generation). I was surprised that in micro benchmarks, Jackson + Afterburner is still twice as fast as my stuff. I had to understand why.
Turns out it does the lex/parse equivalent of unrolling and inlining (cut and paste) absolutely everything. The code is utterly baffling.
My implementation's jar is ~30Kb, fast enough (faster than all but Jackson + Afterburner, Boon), stupid simple, and works the way I want, so I'll keep using it for my projects.
Templates are usually more of a pain to debug.
Nothing is more annoying than a pointlessly huge call tree where the function is called from a single place.
There are other tradeoffs of code reuse and speed and worst-case-speed and probability of introducing bugs. If you haven't read the article, do, its worth it.
I love that Carmack tries to measure which styles introduce more bugs! Who else does that? Seriously, I would love to see more of that.