Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should a function return when invalid arguments are passed?

Tags:

c++

I would like to know what this get function should return when the parameters don't meet the if condition

    template <class Object>
    const Object& SparseMat<Object>::get(int c, int r) //const
    {
        if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
        {
            return mObjects[c][r];
        }
        //what should I return here?
    }
like image 296
user2175394 Avatar asked Apr 17 '26 08:04

user2175394


2 Answers

You should throw an exception:

#include <stdexcept>

throw std::out_of_range("Indexes are out of range");
like image 187
David G Avatar answered Apr 18 '26 20:04

David G


You actually have multiple choices, especially if you are willing to change the signature.

Most likely, you want to signal an error, and exceptions are pretty interesting here:

template <class Object>
const Object& SparseMat<Object>::get(int c, int r) const
{
    if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
    {
        return mObjects[c][r];
    }
    throw UnknownCoordinates(c, r, cCapacity, rCapacity);
}

Or, changing the signature, you can include the concept of nullity:

template <class Object>
Object const* SparseMat<Object>::get(int c, int r) const
{
    if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
    {
        return &mObjects[c][r];
    }
    return nullptr;
}

Which can be made more explicit using boost::optional:

template <class Object>
boost::optional<Object const&> SparseMat<Object>::get(int c, int r) const
{
    if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
    {
        return mObjects[c][r];
    }
    return boost::none;
}

Or, without changing the signature, you might wish to use a null object however this is hardly ever the best choice (it restricts you to objects that embed a concept of nullity, and such objects are better refactored not to have a nullity concept and instead rely on boost::optional<Object>)

template <class Object>
const Object& SparseMat<Object>::get(int c, int r) const
{
    if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
    {
        return mObjects[c][r];
    }
    return null; // where null is "static Object const null;" for example.
}
like image 38
Matthieu M. Avatar answered Apr 18 '26 20:04

Matthieu M.