It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application.
So, I would return strdup(""), so you can free it safely.
It is not good idea to return "". Because, it is const char and you may try to dealloc it in where you get it from the function and this likely crashes your application.
So, I would return strdup(""), so you can free it safely.
return '\0' is not correct; it is a null character.
return "";
is more correct.
And you can make a small test function to test returning an empty string, before your data structure is implemented.
I think you need something like
CopyNormal* 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;
There are several fairly standard ways of doing this. There are different tradeoffs for the methods, which I'm not going to go into here.
Method 1: Throw an exception on failure.
CopyNormal Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
throw InvalidIntersection;
}
//other stuff
return Normal(something, somethingElse);
}
void example(Ray r)
{
try {
Normal n = s.hit(r);
... SUCCESS CASE ...
}
catch( InvalidIntersection& )
{
... FAILURE CASE ...
}
}
Method 2 return a pointer to a newly allocated object. (You could also use smart pointers, or auto_ptrs to make this a little neater).
CopyNormal* Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
return NULL
}
//other stuff
return new Normal(something, somethingElse);
}
void example(Ray ray)
{
Normal * n = s.hit(ray);
if(!n) {
... FAILURE CASE ...
} else {
... SUCCESS CASE ...
delete n;
}
}
Method 3 is to update an existing object. (You could pass a reference, but a convention I use is that any output parameter is passed by pointer).
Copybool Sphere::hit(Ray ray, Normal* n)
{
//stuff is done here
if(something happens) {
return false
}
//other stuff
if(n) *n = Normal(something, somethingElse);
return true;
}
void example(Ray ray)
{
Normal n;
if( s.hit(ray, &n) ) {
... SUCCESS CASE ...
} else {
... FAILURE CASE ...
}
}
Method 4: Return an optional<Normal> (using boost or similar)
Copyoptional<Normal> Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
return optional<Normal>();
}
//other stuff
return optional<Normal>(Normal(something, somethingElse));
}
void example(Ray ray)
{
optional<Normal> n = s.hit(ray);
if( n ) {
... SUCCESS CASE (use *n)...
} else {
... FAILURE CASE ...
}
}
Should I return null or an empty object?
c# - Should functions return null or an empty object? - Stack Overflow
object oriented - Is it better to return NULL or empty values from functions/methods where the return value is not present? - Software Engineering Stack Exchange
Best Practice: Should functions return null or an empty object? - Stack Overflow
My company uses files that are essentially merged XML files into one. I wrote a pretty basic parser and node object that contains the tag name, text, and child node objects. Recently I ran into an error where the file couldn't be found, and my function that searches for child nodes returned null (as it should). But it caused a runtime error, so I'm trying to figure out the best way to address issue. Should I return an empty object so that the code doesn't crash, or should I continue returning null and wrap it in a try/catch?
Returning null is usually the best idea if you intend to indicate that no data is available.
An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.
It depends on what makes the most sense for your case.
Does it make sense to return null, e.g. "no such user exists"?
Or does it make sense to create a default user? This makes the most sense when you can safely assume that if a user DOESN'T exist, the calling code intends for one to exist when they ask for it.
Or does it make sense to throw an exception (a la "FileNotFound") if the calling code is demanding a user with an invalid ID?
However - from a separation of concerns/SRP standpoint, the first two are more correct. And technically the first is the most correct (but only by a hair) - GetUserById should only be responsible for one thing - getting the user. Handling its own "user does not exist" case by returning something else could be a violation of SRP. Separating into a different check - bool DoesUserExist(id) would be appropriate if you do choose to throw an exception.
Based on extensive comments below: if this is an API-level design question, this method could be analogous to "OpenFile" or "ReadEntireFile". We are "opening" a user from some repository and hydrating the object from the resultant data. An exception could be appropriate in this case. It might not be, but it could be.
All approaches are acceptable - it just depends, based on the larger context of the API/application.
StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:
Returning null is usually the best idea if you intend to indicate that no data is available.
An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.
Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.
However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.
In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.
In all the code I write, I avoid returning null from a function. I read that in Clean Code.
The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.
In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.
The analogous C# (anti-)pattern is the Try... method:
public bool TryFindPerson(int personId, out Person result);
Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:
class FindResult<T>
{
public FindResult(bool found, T result)
{
this.Found = found;
this.Result = result;
}
public bool Found { get; private set; }
// Only valid if Found is true
public T Result { get; private set;
}
public FindResult<Person> FindPerson(int personId);
...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).
So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.
If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:
public Person GetPerson(int personId);
...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.
If you're using C++17 or above, use std::optional.
Alternatively, return a value that would convey a similar meaning, e.g. a std::pair<bool, Person> Note that this would still require a Person object to be there, it merely does not need to be valid. If the objects are too large to be returned emptily like that, you'll have to find a workaround, like a union, or a pointer.
There's one more problem to the above code - the C++ version is inefficient. In C++, returning Person by-value always returns a copy of it (except for RVO, which is not applicable here).
Unlike C++, Java has no value semantics for objects, in Java returning Person always returns a reference to an object. A reference in Java works more like a pointer in C++, e.g. it can be null.
So the equivalent C++ code would actually be:
Person* getGetByName(std::string const& name) {
for(int i = 0 ;i<10 ;i++) {
if(people[i].name == name){
return &people[i];
}
}
return nullptr;
}
Now you can do
Person* p = getGetByName("blah");
if (p == nullptr) {
// not found ...
} else {
// use p->name etc.
}
C++ has no automatic memory management. The lifetime of the people vector must thus outlast the returned pointer. If that's not the case then it's more idiomatic to work with smart pointers instead (e.g. unique_ptr or shared_ptr). Thinking about object lifetimes is the responsibility of the C++ developer.
Not exactly the same, but you can get your string as a function parameter instead of as a return value and rely on the fact that temporaries bind to const references.
As an example:
#include <string>
#include <iostream>
#include <utility>
struct S {
template<typename F>
void get(bool b, F &&f) {
std::forward<F>(f)(b ? s : "");
}
std::string s{"foo"};
};
int main() {
S s;
s.get(true, { std::cout << str << std::endl; });
s.get(false, { std::cout << str << std::endl; });
}
This can be a valid alternative if libraries like Boost are not already part of your project and you don't want to include them.
Otherwise, as others have mentioned, you can pick up an upcoming utility called std::optional and combine it with std::reference_wrapper as it follows:
#include <string>
#include <iostream>
#include <experimental/optional>
#include <functional>
struct S {
std::experimental::optional<std::reference_wrapper<std::string>> get(bool b) {
return b ? std::ref(s) : std::experimental::optional<std::reference_wrapper<std::string>>{};
}
std::string s{"foo"};
};
int main() {
S s;
auto opt1 = s.get(true);
std::cout << (opt1 ? opt1->get() : "-") << std::endl;
auto opt2 = s.get(false);
std::cout << (opt2 ? opt2->get() : "-") << std::endl;
}
Pretty ugly indeed. Note that a std::optional should be verified through its operator bool or the member method has_value to be sure that it contains a value.
Unfortunately you cannot use directly a std::reference_wrapper as return value, for it cannot be (let me say) _empty). In other terms, if you want to construct such an object, you must pass a valid reference to its constructor.
Another approach would be by using a template class like the following one:
#include <string>
#include <type_traits>
#include <iostream>
template<typename T>
struct defval {
static const std::decay_t<T> value;
};
template<typename T>
const std::decay_t<T> defval<T>::value = T{};
struct S {
const std::string & get(bool b) {
return b ? str : defval<std::string>::value;
}
std::string str{"foo"};
};
int main() {
S s;
std::cout << s.get(true) << std::endl;
std::cout << s.get(false) << std::endl;
}
Note that you must specialize it for those types that are not default constructible.
References must be bound to an object. So you can't return a reference in your case. Your options are:
- Return a (non-owning) pointer.
- Return something like
boost::optional, which can hold a reference (unlike the soon to be addedstd::optional).
Any C-based language would help with this question. Doing some LeetCode and I need to return an empty list object but there is no option for an empty constructor, in fact it automatically adds a 0 value once instantiated. I looked at a few different languages and they all seem to do the same thing. Here's the class definition:
* public class ListNode {* public int val;* public ListNode next;* public ListNode(int val=0, ListNode next=null) {* this.val = val;* this.next = next;* }* }
Empty ListNode objects can be given to the method, as stated in the constraints section. I'm currently just returning one of those for the edge case, but how could I possibly make my own?
I don't want to return a copied value because it's inefficient
Prove it.
Look up RVO and NRVO, and in C++0x move-semantics. In most cases in C++03, an out parameter is just a good way to make your code ugly, and in C++0x you'd actually be hurting yourself by using an out parameter.
Just write clean code, return by value. If performance is a problem, profile it (stop guessing), and find what you can do to fix it. It likely won't be returning things from functions.
That said, if you're dead set on writing like that, you'd probably want to do the out parameter. It avoids dynamic memory allocation, which is safer and generally faster. It does require you have some way to construct the object prior to calling the function, which doesn't always make sense for all objects.
If you want to use dynamic allocation, the least that can be done is put it in a smart pointer. (This should be done all the time anyway) Then you don't worry about deleting anything, things are exception-safe, etc. The only problem is it's likely slower than returning by value anyway!
Just create the object and return it
CopyThing calculateThing() {
Thing thing;
// do calculations and modify thing
return thing;
}
I think you'll do yourself a favor if you forget about optimization and just write readable code (you'll need to run a profiler later - but don't pre-optimize).
Always wondered this. If you have a scenario where an object might not have a value for example I don't know a query from a database should you...
-
Return null and handle that client side
-
Return a new empty list or object of whatever class the method returns and then handle it client side
-
Throw an exception
Short Answer:
const char *get_string() { return ""; }
or
char *get_string() { return const_cast<char *>(""); }
or
char *get_string() { return NULL; }
or
std::string get_string() { return std::string(); }
Detailed Answer:
Implicit conversion from string literal to char * is supported in C and C++98/C++03, but apparently not in C++11. The deprecation warning is just there to let you know that this should be addressed, particularly if you want to be able to migrate your code C++11.
The empty string literal ("") is not actually empty, it is a string containing a single null character (\0). When you use return "";, you are actually returning a pointer to the memory location of the const string literal so the function return type should be const char *.
If you really must return a non-const pointer to a string literal, you can use the const_cast operator to cast away the const.
A better practice would be to return NULL (or nullptr) for functions that are returning empty, non-const, C-style strings, but only if the calling code is checking for NULL pointers.
Note that C++ has its own string type (std::string), and an even better practice would be to use this rather than a C-style string when possible.
char* foo()
{
static char empty[1];
return empty;
}
Just be aware that this function is absolutely stupid, and whatever your actual problem is, this is not likely the correct solution. But, since you refuse to expound upon your actual problem, here you go.