2

What is the best way to handle invalid function arguments? (I understand there is no sinuglar best way, because it depends on the situation, but read "best" here as "a common practice").

Let's say I have the function

template<typename T> std::pair<T,T> min_max(const T* v, const size_t n){ if(n <= 0){ throw std::invalid_argument("Array of size zero passed as argument."); } T min = v[0], max = v[0]; for(size_t i = 0;i < n;++i){ if(v[i] < min){ min = v[i]; } if(v[i] > max){ max = v[i]; } } return std::make_pair<T,T>(min, max); } 

which returns a pair containing the smallest and the largest value in the array v. But if the size n is less than or equal to zero, there are no values to extract, so I can't really return anything. Should I throw an exception (like done in this example)?

Thank you.

7
  • 2
    Your function, your semantics. Just remember to document them well. You may be interested in some options I discussed in an answer to this related question. Commented Sep 10, 2014 at 12:15
  • 3
    size_t is an unsigned type. It cannot be less than zero, so you might as well compare t for equality to zero. Commented Sep 10, 2014 at 12:15
  • 2
    IMO, if the preconditions are documented and the caller can reasonably ensure they are met, throwing is the right thing to do. If this is not desired, you can rename the function to something like try_min_max and return something like boost::optional<std::pair<T,T>>. However, then you are burdening the well-behaved callers with extra work to accommodate the badly-behaved ones. Commented Sep 10, 2014 at 12:18
  • 2
    Raymond Chen has something interesting to say about this topic. Commented Sep 10, 2014 at 12:26
  • 1
    There are two major schools of thought on this. In Defensive Programming, you would definitely validate all of your inputs. In Design by Contract, you explicitly specify what the valid inputs to your method are and leave it up to the caller to ensure that your method was called with valid parameters. Commented Sep 10, 2014 at 12:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.