143 points · by mr_tyzic · 10y ago · 152 comments
A year ago, I rewrote 424 lines of Java+Spring+Hibernate in 18 lines of bash. This is less glorious, but if you compare the size of the deliverable, it's 39Mb for the J2EE webapp against… 772 bytes for the shell script.
At my current job, I maintain an app with 500,000 lines of code that could easily fit in 20,000.
Code bloat is indeed a recurrent problem.
https://news.ycombinator.com/item?id=4549544
I've written small Java apps --- one class only, i.e. one source file --- which needn't be any more complex, yet coworkers have said there's something uncomfortable about my code; but for some reason can't explain exactly why. I'd get comments like "wouldn't it be better if you made this (only used once and very trivial) line of code a separate function?" "could you use more classes?" (for a <100LoC script-ish thing that had almost no duplicated code nor much in the way of loops.) It's almost as if they can't get their heads around how simple something can be, so it somehow feels very wrong to them.
Then there's the extremist "premature optimisation is evil" attitude, which I think is completely misguided because more code and complexity is bad not only in terms of computer time but also programmer time --- it takes more time for programmers to design, write, read, and debug more complex code.
I'd get comments like "wouldn't it be better if you made this (only used
once and very trivial) line of code a separate function?" "could you use
more classes?"
The trouble is that there is a cargo-cult belief in unit testing in the Java (and .Net) worlds. Everything must have a full suite of unit tests, even if it's a one-off script. Therefore, in order to enable the mock objects needed for unit testing, you can't have "just" a class. You have to have an interface, which that class then implements. If you have any non-trivial piece of functionality, it must be encapsulated into its own method, otherwise, how are you going to test it in isolation.My belief is that it all stems from the fact that Java doesn't have a REPL, so programmers use "test-driven development" to get the same level of interactivity from their code.
Many of the instances were things that we were only likely to make one example of either. I could see that argument being valid if there was a clear second implementation in mind, but an interface with only one implementing class is often just wasted time.
1. Lambdas: Lambdas are brief and to the point, the expressions reflect the terseness of `C/C++`. In many situations, you can totally do away with interface creation by just using a lambda instead. Consider all the lines of code saved in a legacy code by just using lambdas in code!
2. Default methods: Again, `Interface patching` is a curse that a lot of Java projects suffer from. Requirements change slightly and what your typical enterprise Java dev does is add patches upon patches and layers upon layers in an interface. With default methods, you can just add default methods to your existing interfaces without affecting the ABI of your app. Again, tons of redundant code saved here.
3. Type annotations: Again, your typical Java devs have to resort to ugly hacks to place any constraints on the object properties. With type annotations, all you have to do is:
@NonNull String str;
And lo and behold! The variable `str` cannot be assigned any `null` value. So, lots of validation code being saved here again.To the best of my knowledge, none of the above features exist in the `C#` language (yet), so I take it as a Java's edge over C#.
Once a program has been in production for a while and its use cases are more well defined it becomes easier for a single person to swoop in and rewrite it in a far more conscice way. In most of these cases I think the language is pretty irrelevant in terms of how much can be culled.
> The iterative bloat during development can happen for so many reasons. (Numerous changes in requirements late in the project,
... and people not cleaning their mess up afterwards;
> many developers working on numerous modules,
... without proper coordination, or, without the drive to keep things clean (i.e. proper manners);
> design for flexibility and expansion that are never used,
... and never cleaned up, i.e. left there to rot by the people who put them there;
> going too far down a path that turns out to be more work than an alternative)
... and not cleaning up.
> Once a program has been in production for a while and its use cases are more well defined it becomes easier for a single person to swoop in and rewrite it in a far more conscice way.
I think it's always easier for the guy/gal who wrote something to clean it up than for the next guy/gal, who doesn't know the code or its history as well.
Really, this is all just people not cleaning up (or being allowed to clean up) after themselves.
Now if we could all just be nice to each other and hold hands..
Indeed, I once had the pleasure of replacing a BizTalk server with 50 lines of C#. It wasn't that the BizTalk server wasn't a bad idea. The project was for a big harbour, which have documents, cargo manifests, import papers and a ton of other stuff flying back and forth. The idea of having a central hub for data exchange and data conversion wasn't actually that fare fetched. It's just that the only part that was ever implemented was a the upload of a small 5-10 line xml file to the maritime administration, regarding the departure of ships.
After three years of running a BizTalk server, for that one purpose, and with no-one fully understanding Biztalk, we just replaced it with a custom Windows service.
If anything the takeaway is that you projects should be revisited once in a while for clean up.
One is that people use abstractions that are more verbose than necessary. The fact this is bad is pretty uncontroversial. Though very few people go out of their way to write bad code, it's just that everyone's view on the right amount of abstraction is different. What's fine to you might look like gibberish to me. I've radically simplified code by converting complex regexes to multiple steps, for example.
The other cause of bloat in mature code is the inevitable bug fixes, feature requests, and edge cases that accumulate over time. Having the attitude that a system is unnecessary complex is dangerous because you don't know which of these edge cases could doom your rewrite.
Even if you do manage to ship a simplified version of the system it's incredibly difficult to maintain the pristine state of the system. Unless you devote all your time to playing code police then cruft will creep back in when others touch the code. This is where having more abstractions can actually help, because good abstractions limit the impact a bad piece of code can have.
In practice, even simple operations like "rm", or "mkdir", or even "cd" can fail in new and exciting ways. The blanket use of "errexit" and "pipefail" is really only the bare minimum of error handling; scripts that simply _stop_ as soon as a command exits non-zero are not generally an operable product that somebody unfamiliar with the innards of the system can be expected to work with.
It is also unfortunately easy to miss out on putting quotes around expansions, or to get caught out by the somewhat peculiar behaviour of variable scoping in functions. Some improved constructs are available in more recent versions of bash, but if the goal is to be _portable_ (without also shipping your target bash binary) you may not be able to use some or any of them.
The bash "language" (such as it is) is antiquated and clunky, because it seeks to be backwards compatible with the rich tapestry of history that is the Bourne shell. A truly robust, operable program written in this environment often does not come out a whole lot shorter (if it is shorter at all) than a program written in another language with better facilities.
Most recently, I just rewrote a decently written ~8 kloc C program in to a ~4 kloc Go program that does 5 times as much, 10 times faster. If I had more time, I could probably shrink the new Go program to about half its size. This new program includes the old, as well as a new simplified interface, both HTTP.
Moving clients to the new interface has had cascading C#/Scala code reduction of ~1 kloc each. This is the most important point! Simplicity breads more simplicity.
The big benefit is the drastic complexity reduction. Suddenly the junior developers look like superstars because they can understand it and their productivity soars.
I'm continually surprised at how otherwise smart engineers end up writing boated spaghetti that is 'correct' at the micro level but ridiculous at the macro level. A few poorly chosen abstractions can increase the cost of development by 10x easily.
I played with Forth. Sure you can do complex things without parenthesis, but if you squeeze something complicated into a single line equation, it will be harder for a human to follow than if you use parenthesis.
The original article also says "It's never clear how efficiently source will be translated into machine language," which is complete garbage: Most modern processors were designed precisely to optimize for the kinds of control and data structures that C creates, and C (though NOT C++) has close to a one-to-one mapping from code you write to assembly language output.
A key exception is those infix equations, which C can reorder in ways that are more optimal than a naive developer writing Forth would create, so this hardly seems like a recommendation for Forth.
This is all orthogonal to whether bloat exists or is a bad thing. I think that bloat exists and is a bad thing primarily because developers are some combination of lazy, unskilled, or pressured to complete features on constant deadline. And honestly, in most cases it's probably all three, though I would guess anyone reading HN is mostly afflicted with the last.
Not any harder than following Master Yoda speech.
OTOH, following something (say, an English text) (which is heavily parenthesised) may be (I'm sure there is a lot of references to back this notion) exceptionally hard (even if there is just one nested level (and more levels certainly add more confusion)). Choosing flat over structured often makes a lot sense.
6 8 7 5 4 + * - + .
-49 ok
Tell me that's easier to read than 8+6-(4+5)*7
Parenthesis can make things harder to understand if poorly used. RPN can make things harder to understand if poorly used.The reverse is also true for both. Forth does not prevent bad code.
Take my above asides ", convoluted," and ", typically,". Neither are necessary for understanding the sentence, but neither make the sentence exceptionally difficult to understand for a literate reader.
The method in which parentheses (and other structuring notations) are used is more akin to grouping from algebra and mathematics.
EDIT:
Original: OTOH, following something (say, an English text) (which is heavily parenthesised) may be (I'm sure there is a lot of references to back this notion) exceptionally hard (even if there is just one nested level (and more levels certainly add more confusion)). Choosing flat over structured often makes a lot sense.
But it doesn't make sense when we remove the parenthetical statements:
OTOH, following something may be exceptionally hard.
Choosing flat over structured often makes a lot [of]
sense.
(one edit for clarity). That first sentence has lost all meaning. Following what? Following a car on foot can, indeed, be exceptionally hard. But following a slug is often exceptionally easy.A more reasonable version of your sentence:
OTOH, following something--say, an English text--which
is heavily parenthesised may be, I'm sure there is a
lot of references to back this notion, exceptionally
hard (even if there is just one nested level (and more
levels certainly add more confusion)). Choosing flat
over structured often makes a lot sense.
Now the remaining asides (demarcated using the various English notations of em-dash, comma or parenthesis) can be removed without losing the general sense of your sentence.https://github.com/freebsd/freebsd/blob/master/etc/rc (standing on https://github.com/freebsd/freebsd/blob/master/etc/rc.subr)
made me feel the same.
(...)
> Code bloat is indeed a recurrent problem.
But in your example, you're still depending on thousands (millions?) of lines of BIOS, OS, library, runtime code.
It's so many orders of magnitude different than the point Moore is making -- and also, more subtly different: it's not like Forth system don't have library/OS code -- but eg. fitting a rich editor/IDE and OS on a floppy is quite different from eg: Ruby. It's a completely different mindset.
Even if something like Ruby does a lot of things out of the box, if you were to strip it down to a subset that only allowed to be used as a caluclator repl, it'd still be quite complex compared to a Forth system (just think about all the code need to handle keyboard input, and talking to the monitor over VGA/HDMI etc).
None of that invalidates your point, that code bloat is a problem, I just think it highlights that there are different kinds of bloat.
Somewhere between colorForth and developing in in a "traditional" language with a "traditional" IDE on a "traditional" OS, we find things like Project Oberon and Smalltalk-80. Or VPRI's recent effort to create a full drivers-through-gui-up-to-and-including-applications system in 50kcloc total, making aggressive use of DSLs to manage the complexity.
Ruby code requires the whole ruby runtime.
Bash and Perl might be the only exceptions to this due to their incredibly terse syntax for a certain subset of tasks.
Curious. Were you paid to write the Java? If yes, how much did your employer spend to license that software?
Is it possible that bloat supports livelihoods?
The Java code itself probably took less than a few days to write. Java/Spring/Hibernate have no licensing fees (in most cases) and is an industry-standard stack.
I'm guessing the original author didn't write it in Bash because either (1) they didn't know Bash, (2) they didn't know if/when requirements would expand beyond what Bash can easily do, (3) they wanted platform independence, or (4) their team wrote everything else on the Java/Spring/Hibernate stack.
You can argue the merits of all those reasons, but I don't see bloat being profitable as a factor.
The difference in lines and executable size is likely due to an apples-to-oranges situation. Bash scripts seem really light weight if you're not counting all of their system dependencies and if you're writing a program that Bash excels at (such as moving data around).
"J2EE" does not suggest Oracle in any way?
My understanding is that companies that license proprietary software are heavily involved in writing these open standards. Incorrect?
Please forgive my ignorance re: Java.
I think Moore was writing about drivers written in C.
Is the GP's story about programmers at a hardware company?
Does it matter that most of the comments are about high-level programming, not writing drivers?
Just wondering...
Would you write it in C++ differently if you did it again?
Typically bloated code comes from legacy and years of organic growth. I'd imagine almost any 30k LOC project in any language that has been developed more than just a few years could be rewritten in a small fraction of the original size, now that you actually know what the end result must do, a luxury you don't have on the first go.
Try to give him the benefit of the doubt. There's no indication that that's what he meant. Instead, he probably meant that one possible reason people write bloated code -- or at the very least, do not attempt to refactor it after writing it -- is that it provides them with job security. Which is a fair point.
I could be wrong, but I'd wager that a lot of projects that are 1,000,000 lines of C don't have well defined interfaces or documentation.
However, if the author wants to give it a shot, they could try replacing v8 with pure forth. That's a fairly well defined problem, they just have to maintain compatibility with the exposed v8 api.
1) please say that exists
https://en.wikipedia.org/wiki/Software_archaeology
And the wiki page suggests there are some consultants in the field.
Many programmers trying to understand open source projects will dabble a bit in this.
This system survived because no one in management could bear to pull the bandaid on doing significant rewrites and instead preferred to pay much larger amounts spread over longer time periods to continue accumulating technical debt. It basically made it take 6 months to a year before a new hire could be useful, but once someone was familiar with some corner of the system they mostly just stayed there. Keep in mind that most software engineers don't approach their job with passion. Most of the people I worked with didn't even want to touch a computer when they got home. They didn't spend their weekends contributing to open source projects, or keeping up with the latest techniques. They kept their head down and collected their paycheck. That is what the majority of companies actually want, and it's what they get.
That system has since (after a billion-dollar-plus contract to create a replacement system) moved to a 'devops' atmosphere. No automated testing or continuous integration, no, that would threaten the large test team. DevOps to them means what I suspect it means at many non-startup places. It means developers developing on the production environment. It means 10x as many problems cropping up, but management is thrilled because problems are fixed in hours instead of weeks. Development no longer consists of understanding anything, or designing anything, it's just an endless series of adrenaline fueled hasty patches while everyone keeps their fingers crossed that the data doesn't get so corrupted that everything grinds to a halt.
Forth's stack-oriented semantics make function calls very cheap- a function call and return is literally two instructions, whereas languages which use activation records will turn a function call into dozens of instructions- copying arguments around, backing up registers, etc. Since it's computationally inexpensive, you don't need to sweat over whether your optimizing compiler will manage to inline a function.
Short, simple and mostly pure functions are easy to test in isolation- there aren't deeply nested code paths to exercise.
Lots of short functions allow your codebase to reuse more of those functions- any redundancy can be collapsed together, both shrinking the codebase and improving test coverage. This effect is magnified in more complex programs.
You can do this sort of thing in other languages, but forth's syntax and semantics for function definition and invocation are both very lightweight, and this makes it much easier to apply.
[1] https://books.google.co.uk/books/about/Clean_Code.html?id=dw...
Take Perl, for example. I often write Perl scripts, and they're very few lines, but nobody can read them, which is really what matters. So, I'll expand it to be more C-like (calling functions with parentheses, using less implied arguments and scalar/vector contexts, etc.), thus making it very easily readable by people that don't even know Perl. I regard this revised version much better than the more Perl-like and obfuscated (although shorter!) version.
What is more readable, a TCP stack from the Linux kernel, or this [1] 200 lines of code?
[1] http://www.moserware.com/2008/04/towards-moores-law-software...
I recently experimented with writing a web application in q while limiting myself to a single screenful of code - the efficiency is amazing! I am still trying to figure out what factors contribute, but it reminds of solving math problems. Write down what you know and stare at it - no distractions.
Not if you're using a proper IDE (or the right emacs/vim plugins, which are effectively an IDE).
>Code is indented to indicate nesting. As code is edited and processed, this cue is often lost or incorrect.
Not if you're using a proper IDE configured for the project's chosen style. My engineering org also has linters in pre-commit hooks and automatically commenting on code reviews.
>Sometimes a line of code contains only a parenthesis, or semicolon. This reduces the density of the code, and the difficulty of reading it.
Depends on the style guide you choose. Also, some people find this more readable.
>There's no documentation. Except for the ubiquitous comments. These interrupt the code, further reducing density, but rarely conveying useful insight.
The only documentation I've ever found useful (aside from comments) was automatically generated from comments, explaining the signatures of methods and what they do.
Odd complaint, especially to be levied against C.
Some of these (such as double-words) have language-defined representations. (They're always stored with the low word at the lower address, regardless of your machine endianness or, as far as I can tell, whether your stack is growing up or down. Which means that on some platforms the low word is pushed first, and on others the high word first. This shouldn't matter, because you should be using the dword words to manipulate them, except that it's common practice to assemble and disassemble dwords manually.)
Some have implementation-defined implementation-defined representations. For example, the various bits of state that the control flow words push onto the return stack. You don't know how big any of these are, so accessing the return stack from inside loops is basically impossible.
And some are just weird. Floating-point numbers live on their own stack. Except not necessarily; the implementation is allowed to store them on the data stack. So you can't use NIP TUCK OVER PICK etc because you don't know the layout of your stack.
Basically, at every point, you have to know the type of the values on your stack so you can pick the right word (DROP vs 2DROP vs FDROP) to operate on the stack... and if you get it wrong, you get stack corruption and horrible, hard-to-debug crashes.
tl;dr: Forth is typed. Forth is very typed. Forth just doesn't check types.
Vanilla Forth values do not have runtime type information (such as class pointers or discriminator tags) nor does a traditional forth compiler have compile time type information (such as an abstracted understanding of the state of the stack at any given point of execution).
Meanwhile, Factor, a modern stack language has both: SmallTalk-style object-oriented class pointers on every value, and a compile-time stack-effect checker. Factor values have a Lisp-like dynamic typing discipline. That is to say "uni-typed" as "dynamic", or a discriminated union.
http://yosefk.com/blog/my-history-with-forth-stack-machines....
I remember Forth only from the time I was looking to replace `dc` with a more powerful calculator. I figured Forth could fit the bill because it was a stack language.
Whoops we didn't get along immediately. I realized that Forth was not meant to be my calculator, if anything I could have made it my calculator.
But the first time you write it, the first time you are solving the problem, it is much harder to focus on that part.
This is not to say that it's ok to have unmaintainable million lines of code application, but more that it is not something we willingly do to make ourselves look more important in a company.
We like syntax errors because they mold thoughts more precisely. Going against that is also going against a lot of "productivity enhancers" - we build them because we expect to have a lot of code, and we want to reduce the kinds of errors that it may contain. That doesn't mean that we should abuse them to write as much code as we can, but it does turn out that way in practice.
So in an odd way Moore and co are right - we would be more free if we also constrained ourselves more on this point.
But the broader thought is that you can apply such constraints at any time, in tandem with what you already like. And that is more likely to produce an innovation than "just Forth".
We have those productivity enhancers because the language makes it easy to make a mistake there. Ideally we would want to eliminate those mistakes without the syntactic headache.
Although obviously how to do that is a complex exercise, I do think that saying "code bloat is bad" even against "bugs are worse" can provide interesting insights into what we really want from languages.
I've worked with code bases where thousands of warnings (and even several errors) were left in place, which meant that you had to basically ignore all diagnostic messages every time you compiled. At that point, you might as well be 2>/dev/null. Someone even wrote a wrapper script that would diff the stderr against the "known good" stderr.
My general impression of that project was that it was dying a slow death unless someone went in and restored developer confidence in the build process, and the most likely person was me :-/
I have a feeling he's not the kind of person a C programmer could say things like "C is high-level (obvious one-to-one mapping) assembly" and "C is (blanket) efficient" around, and get away with it.
I admit, the first step were a bit brain-twisting, but after getting hands dirty, programming feels relieving. Like a rain shower on a steamy hot day. No worrying about syntax and punctation, elegantly shuffling the stack is fun. For me a perfect demonstration of KISS.
Elaborate Syntax: Your syntax is simple, C's is less simple. If you want elaborate, look at PERL or Haskell. Redundancy and Confusing Types: Fair enough, but the types have to be the ones they are because C's supposed to be close to the metal. Therefore, you need specific bit sized types. It could be better than it is, though.
Strong typing causes errors: Um. Take that up with the angry Haskellers lining up behind you. I'll just duck off this way... Honestly, C's type system is pretty awful, but that's not because it's strongly typed.
Infix:...Yeah, pretty much, but the mainstream won't except anything else.
Parens: Tell that to the lispers. Parens shine for syntax parsing, and the incredibly common editor support makes it even nicer than Python for editing. Unclear how source will be translated: Well, I guess, but more so than anything higher up the stack, like, just to pick a random example, most modern FORTH implementations. Subroutine calls are expensive: Compared to what? 1 mov or push instruction for for each arg, and than a call instruction, at least on x86. Most other processor architectures seem to have similar things going. Those are all pretty fast.
Elaborate Compiler, Object Libraries: Yes, compared to FORTH, the compiler is elaborate, but that isn't why object libraries are distributed, seeing as there's a C compiler for every system under the sun. And distributing object libraries isn't exactly hard.
Lots and lots of files: Yeah, this sucks. But every other system is going to have the same problem, and a proper module system that associates functions to files is really the only way to fix it, aside from oddly specific introspection utilities. Most other languages, say, for example, FORTH, don't have this, AFAIK.
Indentation as an indication of nesting: And you suggest counting braces as an alternative? or just not having nesting? Because most languages, say, for instance, FORTH, have nesting.
No Docs: In BAD C code, this is true. As in bad code in any language, like, for instance, FORTH, as any language designer knows that the language cannot make bad programmers good.
Names are Hyphenated: "I think hyphens suck" isn't a problem with the language, it's just a personal preference. Constants are named: With my passing familiarity with FORTH, I don't know what he's on about here. Could somebody explain, so I can see if I agree?
Preoccupation with Contingencies: Because everybody loves leaky abstractions that fail at critical moments for ill-defined reasons.
Conditional Compilation: This feature sucks. It really does. The problem is, I don't see what else they could have done. So my response here is, Do you have any better way to do cross platform compatibility? Because I would honestly love to see it. I'm serious.
Hooks: Ahhh, I see. You're from the beautiful-diamond camp of software design. I can recognize you guys by your catchy slogan, "Don't Design With The Future In Mind." Programmers best interest to exaggerate complexity: No language can fix this. It's impossible, because this is a social pressure.
Portability: Yeah, basically.
Maybe I haven't seen enough C. Maybe I haven't seen enough FORTH. Maybe I just can't get into Chuck's mindset here. But his claims just seem insane.
EDIT: I read some more off of Chuck's pages, he seems to be thinking more in terms of embedded architectures and single purpose code. Fair enough, in those situations, some of his reasoning makes sense. But the presentation of this page still makes him look like he's off his rocker.
I think this is the crux of it. As far as I can tell, Moore's attitude is basically that "software architecture" in the conventional sense is mostly a lot of churn solving problems of its own creation instead of solving user/customer problems. Looking at it from another angle, the main function of operating systems, virtualization monitors, container frameworks, etc. is to let multiple applications share a single computer. Moore's approach is to make lots of computers so that you can easily afford to have multiple computers per application. [1]
A simple answer would be conditional compilation for entire functions not individual lines of code.
https://github.com/ceylon/ceylon/blob/444f6a1c33e5689405d34a...