If DataPortal_Fetch does not find an object

If DataPortal_Fetch does not find an object

Old forum URL: forums.lhotka.net/forums/t/10482.aspx

Alejandro posted on Thursday, June 30, 2011

I'm implementing a function DataPortal_Fetch. The expected behavior is to get the object from the database and to fill out the business object with this data. But what happens if the object is not found. I don't want to throw an error, I just want to return nothing (or null in C#). Is this possible? How can I do it?



tetranz replied on Thursday, June 30, 2011

I do this by having a boolean _objectExists property in my BOs. DataPortal_Fetch sets this. If the object is not found in the database then the dataportal returns a meaningless object with objectExists = false.

My factory method does something like:

var obj = DataPortal.Fetch<MyClass>(new SingleCriteria<MyClass, int>(id));
if (!obj._objectExists)
  obj = null;

return obj;

This has always worked well for me although I think the purists would say you should throw and catch and exception. It probably depends on the situation.

Alejandro replied on Thursday, July 07, 2011

Thanks, I implemented this solution and worked very well.

ajj3085 replied on Saturday, July 02, 2011

Personally I think an exception is the way to go.  The fetch factory method cannot fullfil its contract in any meaningful way.

Returning null is a problem because at some point people usually forget to check for a null return, and then you end up with a potentially hard to find NullReferenceException.  Throwing a NotFoundException is more likely to be found, and the caller has no choice but to account for it.

Alejandro replied on Thursday, July 07, 2011

I agree that the solution could create problems by not following the standard. And I took into consideration your advice. What I did was to change the factory method from "GetObject" to "GetOrNewObject". This new name remove any possibility of confusion about what the function does and differentiate it from how the other functions work. Thanks.

Copyright (c) Marimer LLC