2 ms·
Lets start with the problem: he doesn't want to use exceptions (fine, I can agree with that), but also wants a "constructor" to return an error value if necessa
by dragontamer 13y ago
Lets start with the problem: he doesn't want to use exceptions (fine, I can agree with that), but also wants a "constructor" to return an error value if necessary. So whats wrong with the obvious solution?
Create a private constructor with a friend function: a "static" factory method. Bam, no more "semi-initialized" crap that you have to deal with.
- rumcajz 13y agoHow would you return the error from the private constructor to the static factory method?
- dragontamer 13y agoThrough any means necessary. Exceptions, partially initialized objects, whatever. But since it is entirely contained within the class now, external code doesn't have to deal with the ugly crap that is inside of the class. IE: A perfect separation of concerns. Adding new exceptions to the constructor isn't a problem, because it is a private constructor... only "friends" can access it. There are a _very limited_ number of functions that can use the constructor.
- lcampbell 13y agoTo extend that, I don't understand his issue with discarding destructor errors -- most errors I can think of during resource release are mundane (e.g., close(2) returning ECONNRESET) and can safely be ignored. Why not just have `int term();`, which returns the mundane errors, be optional and automatically called from the destructor? Are there any non-mundane error states that would occur during a stack unwind that you can't safely ignore?
- dragontamer 13y agoYes actually: proper destruction and cleanup of a mutex must happen, or else a deadlock will likely occur soon. But proper cleanup of non-mundane issues is a well known problem in all programming languages, C included. If you don't handle the mutex correctly 100% of the time, issues come abound. At least in C++, there is a methodology / philosophy (RAII) that handles most situations.
- deathanatos 13y agoDepends on your object. Hopefully, no. To build on your example with files, you can get I/O errors (disk full, disk has a hole in it, etc.) while flushing data, if your file is buffered. (Which is the common case.)
- pdmccormick 13y agoThat's awesome, thanks for the tip!
- dragontamer 13y agoIf you find this tip useful, you probably need to read the Gang of Four's Design Pattern book. Not every design pattern has been useful (omfg, decorators, visitor, and double-dispatch are messy as all hell. Singleton IMO is an anti-pattern, no better than a global variable... etc. etc.). But a lot of the simpler patterns, like static factory methods, are very useful in day-to-day programming.
- munificent 13y agoI use the visitor pattern in interpreters, parsers, and compilers all the time. Outside of the language domain, though, I've almost never reached for it. Decorator is a cool idea, but I haven't found much use for it in practice.