C++ Help on Class Design Exception Handling -
i'm learning c++ , practicing knowledge implementing simple addressbook application. i started entry class , addressbook class implements stl map access entries lastly names of persons. arrived @ next code:
entry addressbook::get_by_last_name(string last_name){ if(this->addr_map.count(last_name) != 0){ //what can here? } else { homecoming addr_map[last_name]; } in scripting languages homecoming -1, error message(a list in python) indicate function failed. don't want throw exception, because it's part of application logic. calling class should able react request printing on console or opening message box. thought implementing scripting languae approach in c++ introducing kind of invalid state class entry. isn't bad practice in c++? whole class design not appropriate? appreciate help. please maintain in mind i'm still learning c++.
some quick notes code:
if(this->addr_map.count(last_name) != 0){ //what can here? you wanted other way:
if(this->addr_map.count(last_name) == 0){ //handle error but real problem lies here:
return addr_map[last_name]; two things note here:
the
operator[] map can 2 things: if element exists, returns it; if element doesn't exist, creaets new (key,value)
pair specified key , value's default
constructor. not wanted. however, if
if statement before have been right way, latter never happen because knowthe key exists before hand. in calling
count() before, tell
map seek , find element. calling
operator[], telling
map find again. so, you're doing twice work retrieve single value.
a improve (faster) way involves iterators, , find method:
yourmap::iterator = addr_map.find(last_name); //find element (once) if (it == addr_map.end()) //element not found { //handle error } homecoming *it.second; //return element now, back problem @ hand. if last_name not found? other answers noted:
simplest solution homecoming pointer (null if not found) use
boost::optional. simply homecoming
yourmap::iterator seems trying "hide"
map user of
addressbook that's bad idea.
throw exception. wait, you'll have first check calling method 'safe' (or handle
exception when appropriate). check requires boolean method
lastnameexists have called before calling
get_by_last_name. of course of study we'er square 1. we're performing 2 find operations retrieve single value. it's safe, if you're doing lot of calls
get_by_last_name potentially place optimize different solution (besides, arguably exception not constructive: what's wrong searching isn't there, huh?). create
dummy fellow member
entryindicating not real
entry poor design (unmanageable, counter intuitive, wasteful - name it).
as can see, first 2 solutions far preferable.
c++ class exception design exception-handling