287 points · by kiyanwang · 10y ago · 149 comments
Too bad that the article doesn't mention the original paper:
http://pixelscommander.com/wp-content/uploads/2014/12/P10.pd...
Some interesting HN discussions around applying these NASA coding standards to JavaScript:
It's already landed in unstable, testing shouldn't be too far away.
The original paper isn't that terrible to read.
Also the amount of third party cookie crap that site tries to deposit in my browser is crazy.
That's why HN prefers source material, not blogspam stuff like this which adds nothing new and often removes possibly useful information.
The recommendations look good to me and (with one caveat) correspond to rules that I apply when writing C code with a high reliability requirement.
My one caveat is in "Rule No. 8 – Limited Use of Preprocessor" which bans all complex uses of the preprocessor. The problem is that it is common in C to encounter situations where the only way to avoid lots of code duplication is to store a table of facts in a macro definition and use the preprocessor to expand those facts into the relevant bits of code in each place where they are used. So in these situations you face a trade-off between the risks due to complex preprocessor use, and the risks due to code duplication (namely, a maintainer might change a fact in one place where it is used but fail to change it in another). My experience is that the risks due to code duplication are very high, and so it's worth the risk of using complex preprocessor macros to avoid them. The risks can be mitigated by implementing the necessary macros in a structured way to keep the complexity under control: http://garethrees.org/2007/04/24/relational-macros/
Sometimes assertions are just crutches for lazy programming. Instead of handling of a very valid (corner) case, some people just assert that it doesn't happen. Lo and behold, years later, it does happen. And those years later, the context is completely lost. How easy is it to handle the corner case now? Hard. In this situation, instead of simply asserting that it doesn't happen, it might be warranted to just assume that it _can_ happen and handle the case. Then, followed up with coverage testing, one needs to (actually try hard) come up with an input that triggers it.
Assertions can also have bugs. The worst is trying to figure out which assertions are really valuable and which aren't.
Shotgun-spraying assertions in the code is not a good strategy in general.
If your point is just that the rule could be applied mechanically and without thinking and that would be bad, then that's true, but it applies to everything, not just to the rule about assertions. Someone could apply the "keep functions definitions below 60 lines" rule in a perverse way, by splitting every long function definition at an arbitrary point in the first 60 lines and tail-calling a continuation. It doesn't mean the rule isn't a good one.
Wouldn't it be better if we could create programs that were correct by construction (and thus needed no assertions)?
I dream of the day when not making use of contracts, static analysis and type based programming is seen as quality smell and not something that only a few are allowed to make use of.
Advanced typing/static analysis is not a pinnacle of software engineering, it's a set of training wheels. Useful? Yeah. But sometimes you may need to skip them.
You hit the nail on the head! However, I would like to mention that competition is only one very important factor.
I'd add that IT is a cost as it is a baker for a bakery, a cook for a restaurant, a mechanic for a repair shop. Do you want to be the n.1 restaurant? Then you must pay, so that your business is good food, not marketing - notice: the best restaurants don't even have good websites, as the food speaks for them. Yes, you must pay a lot to get the best cook, who will take all the time and require all the staff he wants/needs to prepare the best recipes, and so forth. We think we are in a better business just because IT is something relatively new, which not everyone fully understands, so we think that we are the best in everything we do, because we bring innovation. Sadly, we are not.
The current reality is that most companies are average or below-average with no great plans to further develop or to become the next IBM, NASA, Intel, or whatever. Most of them want to survive, some want to get a lot of money fast, and who knows, maybe in 5-10 years sell the company for 1,2,10 mln USD. As long as the mentality is driven by the idea of the acquisition, not by ambition, things won't change - the most efforts will be spent in hiding the pile of s* that employees do, trying to draw the right numbers on the right graphs. And even IBM, Nasa, Intel fail. They do. The difference lies in the ability to stand up and get on their feet again - learn from failures. They have also wasted huge amounts of money - it's documented everywhere, every time one of their projects gets shut down. However, they have a goal in their mind: to be the n.1 whatever they do.
How "paralysis by analysis" has anything to do with typing? And how is typing uber-complicated to begin with? This is ultra basic logic... And why exactly you you think dynamic langages are exempt of typing?
How does all of that has anything to do with a competitor shipping "buggy RoR-based systems a few months earlier"? You can do all kind of shit even in more statically checked langages if you really don't care about quality, and ship buggy products sooner too.
How is a system that prove that some aspects of your program is free of some class of defect should be considered "training wheels"? Do you also consider that compiler warnings are a bad thing for time to market, and so should be disabled? How can you gain any time from not using an automatic checker? Your brain is faster than a microprocessor to do repetitive tasks? This makes no sense. You do not abstain to put on your seat-belt just because you thing you know how to drive, nor do you disable all safety feature of whatever equipment just because you kind of think, without even the beginning of a reasoning to backup that, that you are going to do things "faster". And while the logic telling that what you are going to do is more dangerous is immediate and irrefutable. And while the studies about costs of discovery of bugs depending on the phase of dev clear.
Arguably there are some meta-programming aspects of Ruby which can let you program faster than with a language without equivalent features. But in no way we can deduce from this that "Advanced typing/static analysis" are "training wheels". This is one the the thing that is just so wrong in our industry that I sometimes just don't really know what to answer. I mean I could as well see a claim that the earth is flat and try to convince the crazy claimer that this is not the case, but I have the feeling that people making such claims are not sensible to logic to begin with.
Example: All projects that are to be released must demonstrate that they are maintaining one of these:
http://nodis3.gsfc.nasa.gov/displayDir.cfm?Internal_ID=N_PR_...
I rather use the Algol and ML family of languages, when given the option.
So the process of determining what does and does not require mission critical rigor has to be handled with mission critical rigor. Adding such a process is just one more point of failure. It requires the same attention as just writing the code "right" but is more subject to political maneuvering and other unproductive mental overhead and subjectivity.
Some of them seem to be universal such as statistic code analysis, heave use of sticking to a sub-set of the language that is well defined (Deterministic behavior). Sticking to a over-all coding convention and naming convention. Modulation of the code-base. Avoidance to thread's mutating the state of shared objects between threads (Share state between threads only in a single location eg.. IPC). Similar thing happened with java API with the designers attempting to make the language library thread safe. They soon discovered that was a real bad idea and backed off from that very fast.
At work I joke with my collegue's about the java framework they use they've now moved back to static enum's and static control id's for web pages instead of dynamically generating them on the fly. It's to a point where I feel like I'm programming win32 gui's all over again.
http://number-none.com/blow/john_carmack_on_inlined_code.htm...
>fighter) went a step further. It disallowed both subroutine calls and
>backward branches, except for the one at the bottom of the main loop.
>Control flow went forward only. Sometimes one piece of code had to leave
>a note for a later piece telling it what to do, but this worked out well
>for testing: all data was allocated statically, and monitoring those
>variables gave a clear picture of most everything the software was doing.
>The software did only the bare essentials, and of course, they were
>serious about thorough ground testing.
>No bug has ever been found in the "released for flight" versions of that code.
I was pretty excited to learn more about that style, and then I came across...
https://www.flightglobal.com/FlightPDFArchive/1989/1989%20-%...
...but I'd still like to know more about this style of programming, and languages that facilitate programming in that manner.
Which is to say, a serious problem, but if we take "bug" to mean a difference between designed function and realized function, not a "bug", and therefore not something which should tarnish the record of the coding style to which the bug-free nature of the Grippen software is attributed. The problem seems to have been at a different level than coding.
But I just don't buy that this was not a software fault. It clearly was a case of a faulty software specification.
> The problem seems to have been at a different level than coding.
This makes me queasy. Software engineers working on these sorts of systems -- -- or at least a few senior ones -- should understand enough of the domain to say "this spec is not adequate" or "bad things might happen under conditions xyz; what's the correct behavior in these cases?". And of course all software should notice and then degrade gracefully when assumptions are observably violated.
To absolve the software engineer of any responsibility for understanding the context surrounding his software is to wrongly assume there's not much to software engineering beyond programming to someone else's spec.
Really long functions that have very low complexity (very few nested control structures, ideally none) and do not contain any loops that aren't trivial are easy to reason with. They are essentially the one case I'm familiar with where longer is not worse after a point.
How close is it to the truth ? And how close are we to having that kind of capability for real-time programming(even assuming we're willing to forsake protability, community, and maximum efficiency to some extent ) ?
Another thing is, if you want to write high reliability code in a general-purpose language, you have to have the discipline not to use all language features because a general-purpose language is by default not safe enough. This article basically outlines a subset of the C language for writing high reliability software, and I imagine if Haskell is used for similar software, a large number of language features and functions in the base library would need to be banned.
I still don't see how that prevents user error. My question is then how do you mathematically prove intent?
Also, how far should "sufficiently advanced" be?
We already have a tool for that in the forms of unit tests and types does help if the subject is abstract enough.
The question hinges, on how much errors in your program express themselves as type errors too.
Often a lot closer than in other languages, but that's still not close at all. And it depends a lot on how careful your code is. If you want to rely on the type system more heavily, you have to do more work upfront. E.g., using a simple SQL library that just takes queries as strings vs building your queries in a type-safe EDSL. You can write sketchy Haskell just like any other language, but you're likely to be much more aware of it.
>And how close are we to having that kind of capability for real-time programming?
Last time I looked it seemed like real-time Haskell still had a fair way to go. Presumably because it has garbage collection, lazy evaluation by default and other things that make it hard to prove time bounds. It can also be really hard to optimize sometimes IMO. But I doubt the features that make Haskell reliable are dependent on the features that don't suit real-time programs. I don't know of any pure functional languages with similar type systems, though. https://en.wikipedia.org/wiki/List_of_programming_languages_... has a pretty small list.
"Haskell vs. Ada vs. C++ vs. Awk vs. ... An Experiment in Software Prototyping Productivity"
Hence the way it was written.
What they're saying is that Haskel (and Scala, and others) have such good type systems your data should never be wrong.
That has nothing to do with logic, and so if your code should be `if (foo)` and you write `if (bar)` or `if (!foo)` there is no way for a type system to catch that.
Additionally, there are a lot of constraints you can't capture with type systems. For example: given type Foo, type Bar extending Foo, and types * extending Foo, my type should extend Foo but not be or extend Bar.
Even just with raw data, imagine if your function required and was only valid if you passed in a prime number, or an even integer between 2 and 22, or a "sentence contained of 3 or more words none of which are Chinese" etc. It gets hard very quickly.
This is the reason why you see power of two limits in safety critical software. For example "radar is able to track up to 256 simultaneous objects".
for (i = 0; i < 256: i++) {
if (NULL != object[i]) {
// do stuff
}
}for(int i = 0; i < num_objs && i < MAX_NUM_OBJS; i++)
Combined with the no dynamic allocation rule, you can guarantee that the number of elements in the array must be less than some maximum since you have limited dedicated space for storing them.
Say you have a list of visible satellites, and the number of them can change as they go in/out of view. There's never more than 100, but sometimes there's 50 and sometimes 60.
I supposed you could have an object with an INVALID flag, which the loop can use in its logic?
eg...
const size_t taskSize = 256;
const Task *task = (Task*) malloc(taskSize);
zeroMemory(task,taskSize);
// Allocate array of int's
int *intPtr = (int*)(task);
int intSize = taskSize+4;
for (int i=0; i<intSize && i<(taskSize/sizeof(int)); i++)
{
// do stuff.
}They must use pre-allocated string buffers for some of the task's. Though I figured if you're doing a flight controller for a jet fighter or sate-light you don't need a lot of string parsing.
Everything should be static and deterministic at all times. This is the easiest/only way to ensure you have no resource issues.
You should always (statically) allocate for maximum/worst case.. because you have analysed your worst-case, haven't you?
Another analogy: I would rather have a program with a 100% chance of hitting a bug under a well understood circumstance rather than a program with a 0.00001% chance of hitting a bug under an unpredictable/unknown circumstance.
In an embedded environment, you have complete control over the system and all aspects of it (or at least you should).
You often need to understand the behavior of your system under all circumstances, and that becomes _much_ easier to do when you operate with fixed size data structures because you now know exactly when you will run out of memory.
Consider a hypothetical embedded system where you’re creating a sub-module which must handle external events by means of a message queue. If you know that you can only have three possible events, you can statically allocate your message queue to be 3 deep to ensure that you will never drop an event. If you were to use dynamic memory allocation, you can’t make that guarantee because you don’t know what the other components of the system are doing (and how much memory they’re allocating). Even if there are no other allocations taking place, you still can’t guarantee that yours will succeed due to the possibility of fragmentation.
Statically allocating your buffers ensures that if the program can be loaded in the first place, you can predict with 100% certainty your program will be able to handle those 3 events.
Embedded systems typically are not 'manned', they have to handle all issues themselves and continue providing service. Note that this does not mean "no resets".
Resets should be designed for because they will happen.
All effort should be made to make errors deterministic as (like you say) they will become a real time-suck.
IMO, servers should also be considered embedded systems and designed like this, but unfortunately the culture around server software is for very dynamic, very resource heavy and very inefficient, non-deterministic s/w.
i.e. "You shall handle x messages in y milliseconds."
from that, you derive your worst case buffer size given that you can service that buffer every 'z' milliseconds at most (Note, that involves a hard-real-time requirement as it is a bounded maximum time).
As for the stack usage requirements, it seems like this could be determined statically by some parametric process, but I’m no expert on this.
Does anyone see a reason why there couldn’t be some algorithm to statically analyze some code to derive the worst case stack usage?
For example, take every function and assume that every variable declaration will be required. Add them up. Then, follow every path down the call tree while adding up the required stack for each call.
I imagine unmanned space software is similar; there is little need for a text UI on the spacecraft itself.
(Seriously? downvoted because I gave a direct, true answer to a question?)
I remember using a quadruple pointer (char ) in one of my systems classes.
Also, after having dabbled in Haskell, I know the value of static analyzers. That is like good practices on steroids. And you start to avoid these errors, and start developing better practices.
Change the environment to change your habits.
So if you write safety critical code in Haskell, say, you won't have a large number of the holes that C gives you. But for safety critical systems, their rules say that you can't write code that has even the possibility of falling into those holes. That makes C much safer. That leaves you with a safer C, plus tooling, vs. Haskell (or whatever your choice is) without the tooling.
So, snark aside, what is your actual alternative that you recommend?
Yes. I used to work with the person who wrote it.
> One of the reasons for C is that the tooling around it gives you much more support.
That's because C is an unsafe language, so to write safe code you need that tooling. If you start with a safe language the need for that tooling simply evaporates because many of the mistakes that the tooling is designed to catch are simply not possible.
> For safety critical code, you need that, because programmers make mistakes, no matter what the language.
That's certainly true, but many of those mistakes are mistakes in the rendering of the desired semantics into code. Neither rules nor tooling can catch those kinds of mistakes.
> But for safety critical systems, their rules say that you can't write code that has even the possibility of falling into those holes. That makes C much safer.
No, it doesn't. All of the rules that are not specific to C can be equally well applied to any other language.
> So, snark aside, what is your actual alternative that you recommend?
Good heavens, just about anything is better than C if what you care about is safety. Ada. Java. Scheme. Haskell. OCaml. Python. Go. Swift. Common Lisp.
Python? Can't you get "method not supported" (or whatever the technical term is within Python)? That's not safety, by any stretch of the imagination. Or is there some way to prove that it can't happen, by some kind of (ahem) external tooling?
Ada I could accept. Go and Swift might be suitable. I don't know enough about Scheme or OCaml to comment.
I started having headache spikes after reading this sentence that refers to keeping functions "short", in the article about safety critical programs.
The fact that you could safisfy the business requirement with a single function of ~140LOC does not mean the other approach is more verbose, but that you are only thinking on the happy path, and a bunch of edge cases are left undefined.
Often the arguments boiled down to: It looks only clever if the skill level of your employees is too low, you should work on that.
When I look now at the rules that NASA enforces, it seems to me that their objective is to prevent bugs by not allowing code that is overly complex and I doubt it's because their engineers are not clever enough.
In fact I believe that it takes a lot of cleverness to create code that seems so simple that you don't even need to read the documentation.
Complexity is an emergent phenomenon. It occurs when there are too many interactions to track. To make something simple is to take all of that complexity and to understand and model it as the interaction of a few simple rules repeated over and over and over.
Ok.. I get it that they don't want their C programmers to do that, but do they also mean that this is to "complex" for normal developers to implement in a fault-free manner?
Ignoring the time required to establish a new stackframe (versus a mere jump for a loop), the creation of a stack frame uses more memory. The less memory you can use, while still producing maintainable code, the better. And an easy way to assist with this is to remove recursion.
You could make the case for tail recursion, which a sufficiently advanced compiler will/can/should turn into a mere jump, like a loop, because it is. But this isn't guaranteed in the C standard and so should not be relied upon.
And then there's Rule #2. Loops are bounded, the index variable is supposed to only be altered by the loop structure (so: `for(i = 0; i < MAX; i++)`, that increment is the only place `i` should be altered). By providing a compile-time max, and incrementing (deterministically) the index variable, you ensure that static analysis of the loop terminating (or not) is possible.
Although they define this flexibily as "It should be possible for a verification tool to prove statically that a preset upper-bound on the number of iteration of a loop can’t be exceeded."
So any loops where they can in fact write a verifier is simple enough.