Elegant way of returning possibly non-existant values..

Started by
10 comments, last by sb01234 14 years, 10 months ago
Quote:Original post by c_olin
I've never really used exceptions in C++. Out of curiosity, is this what you guys have in mind when you suggest to use exceptions?

*** Source Snippet Removed ***


I prefer RAII:
class Foo {  Foo(const Configuration & c)     : name(c.get("name", "no_name")    , address(c.get("address") // throws    , age(c.get("age") // throws  {    if (age < 18) throw std::exception("Too young");    if (age > 100) age = 100;  }};int main() {  try {    Configuration c("some_config.txt");    Foo foo(c); // either foo is created and in valid state    foo.do_something();  } catch ( /* something */ ) {    // error occured, application can't continue    // exit  }}


The difference is - I let Foo decide what is valid or not, as well as how to handle unusual problems, all in constructor. If it succeeds, we're fine. If not, Foo is broken and can't be created.

This keeps rules in one place where they make sense. No point in creating a class, then letting user wonder what went wrong and how.
Advertisement
Like explained above, exceptions, or assertions (release time assert), is the right way of doing this in C++. All you want is ensure the user calls the isvalid method before trying to get the value, otherwise the user has made a programming error.

Also, consider changing the signature of your method that gets the status. Why encode things in -1, 0, 1 return values etc? Aside from encoding this in an enum which is a good way of making obscure codes more readable, why not go one step further by creating two separate methods that return true/false instead: one called "isValid" that returns true if and only if it's the right type and it exists, and another method called "exists" that merely checks if the data exists?

Bunching together two logical queries into one and returning the answer in a code just makes the code harder to understand, makes coding new features slower, maintenance more expensive, and in this particular case performance will also suffer (e.g. if all you want to check for is existence, it will still perform the type equality check, and you also need to add a big if-else if-else or switch construct to handle the return codes at the call site, and finally any code that uses codes just begs to be extended at some later stage by another programmer who wants to add a new code for a new case, which leads to problems unless the first programmer realized that this extension would happen and added a proper assert(false) in the else statement/default case).

[Edited by - sb01234 on June 6, 2009 8:37:44 AM]
http://www.better-than-real.net/sb/

This topic is closed to new replies.

Advertisement