|
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
|
|
|
|
|
I am surprised anyone answered anything other than "Other". Because surely there's no single answer to this that can work for all scenarios. You may have to return null, an empty object, an error code, an indication code, or even throw an exception. (sometimes even a combination of exception/return value).
|
|
|
|
|
|
Returning null is problematic unless it's documented what returning null means. When consuming Microsoft's classes this is usually the case. In a typical "Find" algorithm it's quite usual for a negative result to be valid behaviour. Returning a null object is perfectly fine in this case. However, I've often maintained code where, due to lack of documentation, it's not clear whether returning null from the method you were consuming was possibly valid behaviour or not.
The upshot is that for my own methods, in those cases where I may return null, I document what this means. Design by Contract in .NET 4.0+ will also be useful going forward if developers start using it.
Kevin
|
|
|
|
|
Agreed, there are many scenarios where different approaches are needed.
If my GetConnectionString() method can't find the connection string (maybe somebody fooled around with the config files), I would almost certainly throw an exception. On the other hand, if my GetTradeData() method can't find trade "T12709", I would almost certainly return null.
Cheers,
Vikram. (Proud to have finally cracked a CCC!)
|
|
|
|
|
Nish, I agree with your point as well but the question is about returning "no result" so, I prefer to return "null"!
Try not to become a man of success but rather to become a man of value. - Albert Einstein
Ernest Laurentin
|
|
|
|
|
Chris Maunder wrote: Exceptions, in my book, are to be used to catch exceptional cases, not to control program execution flow.
I agree[^], although there are people who think it is acceptable to use exceptions for the tasks such as breaking from deeply nested loops or ending a numerical computation.
But in general, not finding a value in a collection is not an exceptional event. STL containers usually return the "past-end" element in this case, but an option type object would be even better.
|
|
|
|