Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

For example, something like one of these declarations:

bool getMethod(double& ret);

double getMethod(bool& ok);

void getMethod(bool& ok, double& ret);

pair<bool, double> getMethod();

bool checkMethod(); // eg if (checkMethod())
double getMethod(); //        result = getMethod();

or something else, like return a struct

The value may exist about 50% of the time.

The existing code already does a lot of the last method, i.e. using a checkMethod() but I was wondering if that's really an efficient way to do it - via two calls (half the time).

share|improve this question

closed as primarily opinion-based by GlenH7, Kilian Foth, DougM, Dynamic, gnat Jan 30 at 6:12

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

    
or return a sentinel value (like NaN, -1 or 0) –  ratchet freak Jan 24 at 11:32
1  
There is no universally agreed best way. For me, any of the first two or the last option (or the option of @ratchetfreak) would be acceptable, with a preference for the one that matches best with the expected usage pattern and the structure of the rest of the code. –  Bart van Ingen Schenau Jan 24 at 11:38
    
Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask –  gnat Jan 24 at 11:45
1  
@gnat Well - it's not really a question of what I've tried, as to be honest all of these methods are used somewhere in the code since it's been developed over some time and by many developers. I have an opportunity (while making other improvements) to refactor some methods like this and was wondering which way to go as there's no one route that seems clearly obvious, given the situation in hand. –  Roger Attrill Jan 24 at 11:51

3 Answers 3

up vote 4 down vote accepted

Given that all else is equal, and there are no coding standards defining the best approach, what would be the recommended way in C++ to check that a value exists and return it if it does?

Starting from C++14, you can use std::optional. (until then, you can use boost::optional).

The class behaves like a pointer, but allocates no dynamic memory and expresses explicitly the fact that the value can be missing:

The following code snippets perform the same function:

bool getMethod(double& ret); // from your code
// client code:
double result = 0.;
if(getMethod(result)) {
    // result has a valid value
}

and:

#include <optional>
std::optional<double> getMethod();
if(auto result = getMethod()) {
    // *result is a valid value
}
share|improve this answer

I cannot recall ever seeing either of

double getMethod(bool& ok);
void getMethod(bool& ok, double& ret);

and they just look ugly to me.

The first one

bool getMethod(double& ret);

seems the most obvious and self-explanatory, but I've seen

std::pair<bool, double> getMethod();

done too, but it doesn't add anything to the first version.

share|improve this answer
    
On the first point, tryFoo(Key, out Value): Bool is something I've seen before, for example in C#'s TryGetValue. Identical semantics to GetValue, except the return value is used as an out parameter and it returns a success boolean. –  Phoshi Jan 24 at 13:11
    
These are one of recommended approaches for code readability in well-known book Code Complete Second Edition. There are commands/methods like printOutput() which have no logical output related to their main functionality. In such a case it is better keeping explicit output parameter for returning a status than transforming printOutput() into a function. Also consider: (1) meaning of return value of printOutput() is not obvious (number of written chars? status code? no... it is ID of used output device) (2) having status as a parameter also gives hint about its purpose by parameter name. –  miroxlav Apr 11 at 15:25

The problem here is that you are trying to create a function that does 2 things. Check if a value exists. Return an existing value. The best advice I can give is to separate your concerns. Write functions that do just one thing. In this case you might right functions such as:

bool HasValue()const; // returns true if the value exists
double GetValue()const; // returns the value, and throws an exception if the value does not exist.

In this way you have 2 clear methods that do exactly what they say they will do. They each do 1 task.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.