Return a NULL object if search result not found
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.
(By the way, I'm a little worried about your method being const
and returning a non-const
attribute. For philosophical reasons, I'd suggest returning const Attr *
. If you also may want to modify this attribute, you can overload with a non-const
method returning a non-const
attribute as well.)
don't return null -- what to return for search function
Throwing an exception is an expensive operation, since there is a context switch and a lot of debug information has to be gathered, so you want to avoid throwing them as a way to control process flow (especially if you can handle the situation without throwing exceptions). Returning a null can be perfectly acceptable in order to avoid catching exceptions.
An example of this in action would be a couple of LINQ functions in C#. These methods can return a null:
SingleOrDefault(); // returns a single instance of an object, or null if not found
FirstOrDefault(); // returns the first matching object, or null if not found
This allows you to check for null without trying to figure out control flow using exception handling.
One exception (pardon the pun) that I can think of is using exceptions to communicate across program boundries. If you had, for example, a data access layer in a separate DLL, and you needed to communicate a database failure back to the parent program, sometimes the best way to do that is through exception handling.
Return null default value if no result found
You can use below aggregation
Mongodb doesn't produce the result if there is not $match
ed data found with the query.
But you can use $facet
aggregation which processes multiple aggregation pipeline within single stage.
So first use $facet
to get the $match
ed documents and use $project
ion if no ($ifNull
) data found.
let searchTerm = "form2"
db.myCollec.aggregate([
{ "$facet": {
"data": [
{ "$match": { "name": searchTerm }},
{ "$project": { "name": 1, "type": 1, "_id": 0 }}
]
}},
{ "$project": {
"name": {
"$ifNull": [{ "$arrayElemAt": ["$data.name", 0] }, searchTerm ]
},
"type": {
"$ifNull": [{ "$arrayElemAt": ["$data.type", 0] }, null]
}
}}
])
How to return NULL object in C++
I think you need something like
Normal* Sphere::hit(Ray ray) {
//stuff is done here
if(something happens) {
return NULL;
}
//other stuff
return new Normal(something, somethingElse);
}
to be able to return NULL;
throw an exception or return NULL object in C++?
You can either return a pointer to an object, or a reference. In C++, unlike C#, you return the object by value, therefore, the object gets copied. To return it by reference, write Step& Config::getStep(string stepName)
.
To throw an exception, just write throw MissingStepException();
and then handle it like this:
try {
Step s = c.getStep("step");
}
catch (MissingStepException& ex) {
// handle
}
You need to define MissingStepException
class first, of course.
Choosing what to do in general: return NULL
or throw exception depends on your logic: if missing step is a logic error or an unlikely condition, it's better to use exception, otherwise returning a NULL
pointer would do.
Should a retrieval method return 'null' or throw an exception when it can't produce the return value?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
will evaluate to true
if value
is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specification at the ToBoolean
section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
Related Topics
Super High Performance C/C++ Hash Map (Table, Dictionary)
Fast Fixed Point Pow, Log, Exp and Sqrt
Remove an Array Element and Shift the Remaining Ones
C++ Filehandling: Difference Between iOS::App and iOS::Ate
What Legitimate Reasons Exist to Overload the Unary Operator&
How to Obtain C++ Type Names in a Constexpr Way
Is Std::Vector Memory Freed Upon a Clear
Pthreads: Thread Starvation Caused by Quick Re-Locking
C++ What Is the Purpose of Casting to Void
Adding Types to the Std Namespace
How to Navigate Through a Vector Using Iterators? (C++)
When Do I Really Need to Use Atomic<Bool> Instead of Bool
What Are the Use Cases for Having a Function Return by Const Value for Non-Builtin Type
How to Read from a Version Resource in Visual C++