Reputation: 3829
If I am calling a function:
public User GetUserById(int UserId)
{
User someUser = new User();
//Look up this UserId in the database
...
someUser.Name = dbResult["Name"];
return someUser;
}
Let's say I pass in a UserId that has no "User information" associated with it.
Suddenly the 'someUser' I'm passing back is instantiated, but empty. What's the best way to check that it's "empty" so I don't try and display data from it?
The caveman in me wants to check if someUser.Name has a length of greater than zero. I know that's awful, so if you know what I'm missing - I'd appreciate your help!
Upvotes: 1
Views: 356
Reputation: 178790
The real question is, why would GetUserById()
return an uninitialized object if the ID is invalid? Wouldn't it be better to throw an exception or - at worst - return null
?
Upvotes: 7
Reputation: 6773
Why not just check the result of your database call to see if any record at all was returned? If there are 0 results, you'll know there's no such user, and you won't have to create a User object at all.
Upvotes: 1
Reputation: 30963
Given your implementation in the question
Implement an "isEmpty" method that checks each instance variable for being in an uninitialized or default state (null for refs, zero for numerics, etc.) The class should know about its own state; it's bad form for external code to pull state out of an instance and then do logic against it. You'll also need to deal with possible ambiguities, such as whether both null and zero length are considered "empty" for string-valued instance variables.
Alternatives
Return null
to indicate "no such user".
Throw an illegal argument exception to indicate "no such user".
Use the NullObject pattern and return a subclass of User
for which isNull()
is true
.
Upvotes: 4
Reputation: 115857
The definition of "empty" is very unclear. If there is no record in the database, it's quite logical not to return anything. That is, return null
if no record exists.
Upvotes: 1
Reputation: 1064044
Personally, if the id doesn't exist, I'd either return null
, or (less preferred) I'd throw an ArgumentException
or KeyNotFoundException
. That avoids the whole question - you just check against null
...
Upvotes: 5