Recommended Posts

If I have a templated class that contains a member of type map and implements a Get function which uses the find() method of a map to get that object, what should be done if the object is not found? What should I return?
Here's my function:

The only thing I've come across is returning a null object.
But then any class that potentially uses this class must implement
a null object type. Is that really practical? I'm not sure if I'm
comfortable with creating this kind of dependency.

0

Share this post

Link to post

Share on other sites

You could return a pointer and use a null pointer. Alternately you can throw an exception. Or you can automatically create a default constructed object in the map with the given index. Which one is the best choice is determined by how you want to use your Get() function.

Share this post

Link to post

Share on other sites

As such, there is solution that would make sense from language perspective.

One way is to return pointers (or store pointers to value in the first place), other is to rework the logic, third is to throw an exception (natural design solution), another is to use visitor and IOC:

Share this post

Link to post

Share on other sites

Before you throw an exception, though, decide whether it's actually an exceptional case (i.e. "not finding it is totally unexpected, and some weird error must have occurred [like having a typo in a config file]" as opposed to "well it's not cached yet so not found").