|
Bit off topic but no one has mentioned boost tuples, for returning multiple results.
|
|
|
|
|
If you don't know what you must return Do this:
I say it depend on the situation .
But you can use some illegal values.
For example i use -99999.9999 for a double illegal value.
My source code check if the number returned is -99999.9999 then acts for that situation.
I think its worked. because I use this way in all of my projects.
U can find me On quinbee222@yahoo.com I can answer all of your questions.
|
|
|
|
|
For godssake, do what a good Destroy function does: "delete this".
Nuclear launch detected
|
|
|
|
|
So the question was "Do you return null or an empty object when returning "no result"?"
There are no depend on this, depends on that.
It's an IS NULL predicate; this applies to everything, scalar, value, struct, object, pointer, pink giraffe etc.
I see null as the only alternative. This means, at least for me, the meaning of "no result".
Here is your result, caller: null. You asked for int, get a null. You asked for a collection, null.
The value that means "you can't do anything with it except testing for its null state". And this is null.
Nuclear launch detected
|
|
|
|
|
If I ask for a column that doesn't exist?
|
|
|
|
|
Like if you would invoke a vfptr from a base class and end up with a __purecall because of misuse.
In this case, crash, not exception. (That is a design decision, anyway, because you are not anymore in the application scope.)
The same answer would go if you are implementing division on N:N and ask why 3/2 is not integer. Because is not.
Asking for a non-existing column from an SQL statement is not an exception. Is a BSOD>.
Nuclear launch detected
|
|
|
|
|
Cristian Amarie wrote: In this case, crash, not exception.
No, the application decides that. The called method throws Exception, the app may or may not exit (gracefully), and certainly not BSOD.
|
|
|
|
|
Sure application decides that.
(And when I said BSOD, I meant for application, not for system, obviously ...)
Back to the question: "Do you return null or an empty object when returning "no result"?"
When you ask for a non-existing column, it's not a "no result". Is an "error".
Getting an empty result set is not an exceptional event; trying to read data that does not exists is not an exception as well.
Consider that the client can ask for everything. That's not an exception (at most a stupid behavior, programmer error, loose client etc.).
The same null should be returned to client "there is no result" AND an error should be returned to the client. Such as Err object in VB, IErrorInfo in COM etc.
The client can choose to handle the error (or not), but in any case, nor the implementation nor the client should handle this as an exception.
Nuclear launch detected
|
|
|
|
|
Apologies for the length of the post, I just wanted to be thorough in showing how I occasionally do things.
namespace Questionable
{
using System;
public class QuestionableReturn<TResult, TError>
{
private TResult result;
public QuestionableReturn(TResult result)
{
this.HasResult = true;
this.Result = result;
this.Error = default(TError);
}
public QuestionableReturn(TError error)
{
this.HasResult = false;
this.Result = default(TResult);
this.Error = error;
}
public bool HasResult
{
get;
private set;
}
public TResult Result
{
get
{
if (this.HasResult)
{
return this.result;
}
else
{
throw new InvalidOperationException("A result is not available. Check the Error property for more information.");
}
}
private set
{
this.result = value;
}
}
public TError Error
{
get;
private set;
}
}
public enum SampleReturnError
{
None = 0,
ItemNotFound,
SomeOtherError
}
public class SampleReturnClass
{
private static readonly string[] Data = { "FirstItem", "SecondItem", "BadItem" };
public QuestionableReturn<string, SampleReturnError> FindString(int index)
{
QuestionableReturn<string, SampleReturnError> returnValue;
if (index >= Data.Length)
{
returnValue = new QuestionableReturn<string, SampleReturnError>(SampleReturnError.ItemNotFound);
}
else
{
string dataItem = Data[index];
if (dataItem.Contains("Bad"))
{
returnValue = new QuestionableReturn<string, SampleReturnError>(SampleReturnError.SomeOtherError);
}
else
{
returnValue = new QuestionableReturn<string, SampleReturnError>(dataItem);
}
}
return returnValue;
}
}
}
Adam Maras | Software Developer
Microsoft Certified Professional Developer
|
|
|
|
|
It returns results, warnings, errors-
any of the three can contain zero to many entries.
Maruf Maniruzzaman
@ Dhaka, Bangladesh.
|
|
|
|
|
in every cases...
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.
Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
Thanks
Md. Marufuzzaman
|
|
|
|
|
I depends on the environment,
when working with lower(C/C++ are high-level language)-level environment(languages) such as C/C++, null is not well defined(some headers
#define NULL 0 , other
#define NULL (void*) ),
and forgetting to check the method which return null may cause derefferencing a null pointer,
my solutions is declare a global(in the context/namespace/...) null reference object which can be
derefferenced(may at most throw an exception), so it won't crash at runtime.
at higher level languages with full exception support like Java,
you can just return null(or throw a
NullPointerException which extends RuntimeException, so you needn't explicitly declare).
Hope it helps.
pindulajr@hotmail,
pindulajr@gmail.com
|
|
|
|
|
#define NULL (void*)
Where did you see this?
Nuclear launch detected
|
|
|
|
|
I always use <code>Nullable </code> datatypes like <code>int?</code> for basic datatype, and comfortable with nulls.
The thing is to handle <code>NullReferenceException </code> properly whithin your code. otherwise the most popular exception promts... <code>"Object Reference Not Set to an Instance of Object" </code>
|
|
|
|
|
Ya Nullable is fun to use. Especially Nullable.GetValueOrDefault(value to use if the return has no value).
But in reality i prefer empty types first if available... like String.Empty, IntPtr.Zero...
|
|
|
|
|
Usually in my Data layers I do to methods, one which allows a default object to be returned and one which will call the "default" methods passing an empty object. But in some cases, when a value is expected I throw exceptions saying that an expected value was not found. When my active directory classes I have the option in it to automatically convert nulls to string.Empty's when returning a value and string.Empty's to null's when saving values.
My general rule of thumb,
List/Array methods always return a valid object.
Int's will default to int.MinValue.
Bool's will default to false.
Strings will return null's if that is what is needed (settings and optional properties)
Strings will return string.Empty if that is what is what is supposed to be returned for empty values.
And comments will always help.
Those who are too smart to engage in politics are punished by being governed by those who are dumber.
- Aristotle
|
|
|
|
|
In my opinion, anyone who thinks that any one of these answers is always (or even nearly always) the correct choice has a long way to go before they're a mature programmer. I'm with Nishant Sivakumar[^] on this one; the only sane answer given these choices is "other". It's interesting that there's so few sane programmers here....
Steve
|
|
|
|
|
...my dastardly plan to get some serious discussion by dangling the unanswerable survey succeeds...
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
I entered alternate text without clicking "other" so I went uncounted.
|
|
|
|
|
I agree that it depends on what your writing, but I believe for most cases if you are looking for something in a list of items and it is not found, I would return null (whatever the language defines a null).
|
|
|
|
|
The right tool for the job are option types[^]. Unfortunatelly, most mainstream programming languages do not support them directly. In C++, there is the Boost Optional Library[^] that servers this purpose.
We have discussed this topic in the Lounge[^] not so long ago
|
|
|
|
|
Internally at CodeProject we've implemented something very similar using generics, though our use is still a little sporadic since it was a late-comer to the game. We extended the concept to not only include the value and whether or not the value is there, but also error information in case an error was the reason a no-show occurred.
I still check for nulls though!
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
Chris Maunder wrote: I still check for nulls though!
Yes, simply having option types available is not enough. To be foolproof in this regard, a language/environment must both support option types and not support nulls. I think Haskell does it correctly, but there are not many Haskell jobs out there
|
|
|
|
|
I have made myself a Nullable<> template, that I have used with great success. It works a lot like what the Wikipedia-article explains.
--
Kein Mitleid Für Die Mehrheit
|
|
|
|
|
So here's where I stand:
1. If I'm asking you to look up an object or return a list of objects matching some criteria then I do not expect an exception to be thrown. Not finding something, or having an empty list is not exceptional. Having a database fail isn't exceptional. Having all code always work perfectly with butterflies and roses is exceptional. Exceptions, in my book, are to be used to catch exceptional cases, not to control program execution flow.
2. I don't care what you return from a method. Return null. Return a default value. Return a pink giraffe. I will check your return value to ensure it's non-null and to ensure it's a sensible value. I will do this everytime at every point because I do not trust code. I don't trust the code someone else has written. I don't trust the code I wrote 2 years ago. What if we're using different conventions? What if I had too much sugar two years ago and decided I should return a valid object, everytime, always, then in deep, dark Toronto Winter I decided "screw it: you're getting a null".
So the convention I use is: use a common sense convention and be consistent about it but at the end of the day, when everyone's had their fun, I'm going to double check whatever it is you gave me because I'm crabby and cynical and computers hate segfaults[^].
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|