122 points · by vq · 11y ago · 143 comments
For example: make all constructors private and empty and use public static factory methods for manufacturing new instances. Now the factory can fail, and return an error to boot.
Similarly, ditch C++ exceptions and introduce the notion of a status object that methods return. You always have the option of C-style semantics without dumping the genuine advantages C++ brings.
In terms of some of what is brought up in part II, a C++ engineer can (and would) implement linked-lists C-style. See: http://www.boost.org/doc/libs/1_55_0/doc/html/intrusive/list...
* undecidable grammar: http://yosefk.com/c++fqa/defective.html#defect-2
* const inside containers: http://yosefk.com/c++fqa/const.html#fqa-18.1
* template error messages http://yosefk.com/c++fqa/templates.html#fqa-35.17
C is often nicer than C++ because it's simpler: it only has the C pitfalls not the combination of C & C++ pitfalls that plague C++.
If you really believe that, then you're probably writing dangerous code and not even realizing it.
Most C++ pitfalls come from subtle interactions between features that don't even exist in C, like exceptions, move semantics, templates, threading, constructors/destructors, references, operator overloading, etc. Those are the things people are talking about when they mention the pitfalls of C++.
The things you mention are the pitfalls of C, which technically still exist in C++, but they're not as interesting there because the C++ pitfalls are so subtle and dangerous.
The weird thing about C++—and the reason it didn't just absorb/replace C—is that it gives you the ability to encode strictly more nonsensical things than C does. In that sense, C looks more like the descendant of C++ than the other way around!
Just switching compilers makes the C code more robust.
And they certainly beat C's "equivalent", macros.
Let's take one specific example -- connecting to a remote host. The loop that goes through the DNS returned IP numbers uses local error codes to try each in turn until one is accepted. If none are accepted it throws an exception so that the higher level application code can decide what to do about the connect failure. The exception ensures that all resources are properly cleaned on the way through.
The exception is used to guarantee that resources are properly de-allocated on the way back up to where the error needs to handled as it cannot be handled locally, probably not in the function that kicked off the connect attempt either, but there's no local exceptions to handle the case where the error is handled locally.
The use of the exception is more like a ROLLBACK on a database transaction together with error reporting -- it helps ensure correctness by backing out properly changes in state that were kicked off by the connect attempt. When the exception is caught the program state is exactly as it was when the connect attempt was first tried so we know we have good clean state to make another attempt or to move on and do something else. Backing out all of these other state changes is really hard when an error code needs to be handled non-locally -- and it's this non-local handling of errors that's so hard and error prone without exceptions.
So if you're only ever using error codes you'll far too easily make mistakes when the error needs to be handled non-locally, and if you're only ever using exceptions then it's going to be real ugly when the error is handled locally.
You need to use both if you want clean code that is going to work reliably (or you need massive engineering resources to fix all of the bugs you'll end up with).
E.g you have function called connect() then it should return something like a state object with a connection instance or an error indicator such as {err:dns_fail, dns_servers:[..],hostname:".."}
Otoh, if you were writing a one-of script for scraping a web site then you don't care about fault tolerance and then connection failures are exceptional events so throwing on them becomes ok.
If you can handle the connect failure locally (i.e. probably no further away then caller of the connect function) then by all means do so. If you find another structure in your code makes other things simpler, but no longer allows you locality of error handling you should use an exception.
Well designed libraries allow you to choose. Check out Boost.ASIO for an example of this. Every API has both an exception and error handling version and you're free to use whichever is most appropriate for what you're trying to achieve.
This whole thing about 'expected' and 'unexpected' errors is a red herring that leads people down the wrong path.
The exception backs you out of the transaction that your code is performing -- this is the way to think about it. An error code allows you to try something else whilst keeping the transaction alive. Which you use depends not at all on whether you think the error is "normal" or not.
I once worked with a billing system that threw a BillingException when a charge didn't go through. It works ok, as long as your only response to such an error is to spew an error message to the user. But the more you need to handle it, the less an exception makes sense. The code that tried to handle the BillingException was a tangled mess of try and catch statemetns mixed with retry loops. For example, if there was a temporary error at the payment provider, you would just retry a few times, a permanent error, try with another account, if the customers remaining funds were to low show an error message or if they were just a few dollars of, charge them that and be happy we got something from them.
On the other hand, the billing system could also throw a DbException in case there was something wrong with the database connection. That's a different kind of problem and fatal for a database-backed website. Nothing to do, except log the error and crash.
The point of exceptions is not so much that you can catch and handle them, but that it separates exceptional situations from in-band normal error handling. Now what is in-band and what is exceptional depends on the circumstances which is why, as you say, Boost.ASIO provides both variants. If your system is supposed to handle the errors, use the one without exceptions. If not then use the one with exceptions.
In C (my preference over C++) I would use an arena memory allocation strategy in this case. This is something I learned from reading the python interpreter source code: when your parser barfs way down in the call stack, an arena is a simple way to clean up everything. (I'm not saying it will be easy in your particular case.)
As for exceptions, you can just use the return value to signal an exception, or if you want to be a bit more radical, use a longjmp.
You can't bypass all of this in all cases assuming that you only need to deallocate memory. Destructors tidying this up as the exception unwinds the stack is extremely easy to reason about and stops any number of idiotic mistakes.
The stated design goal is that the project "never fail and never exhibit undefined behaviour" yet exceptions are exactly for undefined behavior. If you can't allocate memory, if your function is called with arguments that it cannot possibly interpret, or that a fully expected network connection has failed and cannot recover. Those are exceptions. For all your defined behaviors, you can control just as described in the article without exceptions.
There is clearly too many exceptions (and handlers) in the first case and way too few in the second case.
http://yosefk.com/c++fqa/exceptions.html#fqa-17.1
http://yosefk.com/c++fqa/ctors.html#fqa-10.17
http://yosefk.com/c++fqa/exceptions.html#fqa-17.3
The FQA helped my crystallize a lot of the reasons I hated C++. Even if you like C++, it's a good idea to understand the FQA's arguments, for the same reason people play devil's advocate.
I don't detest the language the way he does, but the FQA really resonated with me. There's no one feature that kills the language, but it seems like everywhere you go you run into a feature that feels like it was designed to trip you up, and it gets tiring after a while.
For example, exceptions, as decribed in the article. Exceptions themselves make sense in some scope: they model some cases of error handling and controlled longjmping really well while are totally unsuited for other cases where a more fine-grained control of failure is necessary. Thus, exceptions themselves are applicable to an extent in a certain scope.
However, in C++, the scope where exceptions actually do work is even more narrow than the scope where exceptions would generally fit. Like explained in the article, the FQA, and this thread, there are numerous pitfalls where exceptions totally break and a number of assumptions you have to make but can't guarantee. This reduces down to a few "known almost safe ways" of using them with a lot of "ifs" bundled in, and you need to explicitly know those ways.
Unlike in C, in C++ you can't deduce what works and what doesn't out of merely reading or writing code: you have to have enough experience to know these pitfalls first hand so that you know how to avoid them and why. There's basically a line drawn in sand of what is known to work and what is not, like medical remedies in ancient cultures.
And further, all this effort is only really needed to deal with the language itself. It's not required to solve the programming challenge at hand. It's something that is not needed with C because you can reason with C on a "what I see is what I have" basis.
I guess you have not yet seen too much UB or compiler specific semantics then.
( If you dont’t understand why, dont’t worry it will be obvious to you in 3 years :-)
Not to mention Go having multiple return values IMHO also takes away the major pain point of returning errors in C; using up your only return value and having to take pointer arguments when you would rather not.
#ifdef _WIN32
# ifdef EXPORTING
# define DECL __declspec(dllexport)
# define STORAGE
# else
# define DECL __declspec(dllimport)
# define STORAGE extern
# endif
#else
# define DECL
# define STORAGE
#endif
// For every return tuple type actually used:
STORAGE template class DECL std::tuple<error_type, return_type1>;
STORAGE template class DECL std::tuple<error_type, return_type2>;
STORAGE template class DECL std::tuple<error_type, return_type3, return_type4>;
// etc.
Even without the above, exposing STL across shared objects leads to the games of "which side of the shared object did this get created" and "which STL did this shared object link against". Losing these games leads to sizeable butt pain.i.e.,
int foo_new(foo_t **res);
int foo_mutate_copy(foo_t *foo, bar_t *bar, foo_t **new_foo);
Instead of foo_t *foo_new(); // returns NULL on failure
foo_t *foo_mutate_copy(foo_t *foo, bar_t *bar); // returns NULL on failure
I also like the Go way, just thought this way of doing things in C should be mentioned in the thread.I specifically mention the C way of doing things- but use you demonstrate it above. I was suggesting the Go way is superior.
I don't like that I can't locally hide the boiler plate. There's obviously some measure of essential tension there; I could cope.
I still haven't gotten over the use of product types for return values rather than sum types, and I'm not sure if I will.
Also, with Go's approach you have to either explicitly ignore the error or deal with it.
If I'm doing something wrong here I'd love to know it.
- you can collect errors in a function and return them once or provide an extra method, like http://golang.org/pkg/bufio/#Scanner.Err
- you can type switch on the error; maybe there are errors that you can recover/retry locally, such as connection errors, or general io failures - so you do not need to pass back all errors to the caller
More on errors: https://blog.golang.org/errors-are-values
I feel like so many developers have been so damaged by Java's approach to exception handling that, of course, error codes seem simpler by comparison. I can't help by feel the recent push-back against exceptions is a step backwards in many situations. A whole generation of developers will have to re-learn the pain that lead to the development of exceptions in the first place.
But Exceptional C++ made me not want to deal with C++ exceptions, ever. If getting C++ code correct in the face of exceptions is that bloody hard, then the language is broken. I'm convinced that cobbling up an "int" equivalent type that is exception safe is a pyrrhic endeavor that will be a continual source of fragility in production code.
Alexandrescu's Modern C++ Design made me want to forget that templates ever existed. The entire second half of that book I kept saying to myself, "If I'm on a project with someone actually checking stuff like that in, one of us is going to have to leave." Fortunately I've yet to run into those kinds of template metaprogramming games in the wild. Good programmers seem to abhor them.
[Edit: Actually, I remember a bunch of stuff in Modern COM that used templates very heavily. Essentially impervious to debugging; that stuff sucked hard]
More recent C++ design decisions are better than the ones the committees made in the 90s and early 2000s. But the successful teams I've seen all practice restraint and keep things debuggable by limiting the amount of magic going on under the hood, regardless of what the committees have been pushing.
The Google C++ standards (and others that were independently created and haven't been seen much outside their own development cultures) may be "dated", but they remain an indictment of the design of C++.
Blame C, as they are that way to keep C++ exception behaviors compatible with C semantics.
First I can think of: don't create situations where error can happen. Compile with exceptions turned off. Out of memory? Terminate the process/thread.
Another: create your objects using some factory, make constructor empty and initialize class by said factory once instance is already created (perhaps recursively instantiating its members). This way all error generating code will be moved outside of constructor.
See how Google approach it: https://google-styleguide.googlecode.com/svn/trunk/cppguide....
EDIT: actually, there are two defects here. One are the implicit numeric conversions. The other one, which causes me most grievance in this context, is that size() on containers returns an unsigned type.
Except that
typedef int bool; /* or BOOL */
#define FALSE 0
#define TRUE (!(FALSE))
used to be quite common back then. So C++ only adopted an existing idiom in the C community.On a related note, I'd like to see the results of it being coded in a modern Ada or SPARK with one of the best compilers. I'd be interested in seeing it with full runtime checks on and off with conservative optimization. ZeroMQ with strong implementation assurance could lay the foundation for all kinds of secure networking and middleware schemes. Heck, I'd like to see a team formally verify a version of it with an executable for common architectures. I'd have fun with that. :)
I believe that Objective C is a pretty good (yes, it's getting old) combination of C compatibility with object oriented features as well. The 2 big downsides IMO are: (1) essentially restricted to Apple ecosystem and (2) the syntax keeps a lot of developers away.
The message-passing syntax is such a funny thing to me; it looks weird, but it takes about 1 minute to grok if you try, and then the rest is very simple. It's really dynamic and lets you do some very powerful things that you wouldn't expect to be able to do in a C-derived language (NSProxy, respondsToSelector:, etc.).
I find it very natural when doing ObjC development to write all my high-level code is very "objecty" style, and then call into pure C methods when I'm doing something tricky/low-level/fiddly.
On the downside, though, mostly due to it being old and not very well adopted, ObjC never got a proper generics system, which is really annoying if you're used to Java or C++.
Since C++ and ObjC are both (essentially) supersets of C, you can always mix however much (or little) of plain C that you want. Everything about OO in ObjC is very dynamic. It allows you to do some very cool/flexible/unsafe/unwise things.
In my opinion, that where the tradeoffs start showing up. Flexibility, runtime speed, nice abstractions, development speed, code complexity, etc. Really difficult, if not impossible, to have them all at once.
Despite the unusual looking OO syntax of ObjC, overall it's a pretty simple language given the power it provides. Once you get acclimated to looking at its syntax, I'll even dare say that it's much easier to read and understand than many other languages.
Rust [1], basically!
I appreciate you bringing it back to my attention. It's worth someone evaluating thoroughly against C and C++ for systems programming (incl OS) in terms of performance and maintenance. Not sure if I can squeeze time in but I'll suggest that to others at least.
It exists already, only needs more libraries and more users.
Yes, they are removing the GC dependency from the standard library.
Go or Rust? They might not quite match your dream outlined above, but I think in practice they are pretty much used with the purpose of achieving something similar. They both can be "unsafe" as needed and integrate well with C and ASM.
So, it's not a dream so much as me wanting to see an excellent middleware implemented in a language proven for decades to do what the two you referenced hope to do someday. Using proven methods, even if ugly or unpopular, is just what engineers do when solving new problems. I'd happily use the same thing built in Rust (not Go as it's less safe) if they can get it more compact and fast. Meanwhile, I have to use C++ and C implementations because that's what's available.
Can you expand on this? I have had no issue getting to C levels of performance by using "unsafe" or ASM a few small critical sections as needed (tight bodies of inner loops, etc or mmap based allocation).
For that niche it's quite nice, and helps avoid refcounting errors which can be very subtle in C, but Vala is still a fairly leaky abstraction over the C to which it compiles.
"Why I should have written nanomsg in Rust, not C".
From what I have read so far, implementing intrusive lists is not easy in Rust. (If you know of a working intrusive doubly linked list implementation in Rust 1.0 that does not invoke undefined behavior, please tell me; I'd like to know how it should be done.)
It can be used in a freestanding (nostd) environment such as a kernel. It uses unsafe code but provides a safe interface. The primary technique is to embed the type that is iterated over in a larger struct which contains the links. This way I can give out references to the inner type without fear of invalidating the iterator.
I see. I was too fixated in embedding a small struct with the links within the larger struct (in the style of the Linux kernel "struct list_head"), and didn't think of doing the opposite.
It probably makes being in several intrusive structs at the same time much more complicated, but I think it's possible to do without breaking anything.
Here's what I found after a Google search, by one of the core Rust devs (unsurprisingly).