using indexer to retrieve Linq to SQL object from datastore
- by fearofawhackplanet
class UserDatastore : IUserDatastore
{
...
public IUser this[Guid userId]
{
get
{
User user = (from u in _dataContext.Users
where u.Id == userId
select u).FirstOrDefault();
return user;
}
}
...
}
One of the developers in our team is arguing that an indexer in the above situation is not appropriate and that a GetUser(Guid id) method should be prefered.
The arguments being that:
1) We aren't indexing into an in-memory collection, the indexer is basically performing a hidden SQL query
2) Using a Guid in an indexer is bad (FxCop flagged this also)
3) Returning null from an indexer isn't normal behaviour
4) An API user generally wouldn't expect any of this behaviour
I agree to an extent with (most of) these points.
But I'm also inclined to argue that one of the characteristics of Linq is to abstract the database access to make it appear that you're simply working with a bunch of collections, even though the lazy evaluation paradigm means those collections aren't evaluated until you run a query over them. It doesn't seem inconsistent to me to access the datastore in the same manner as if it was a concrete in-memory collection here.
Also bearing in mind this is an inherited codebase which uses this pattern extensively and consistently, is it worth the refactoring? I accept that it might have been better to use a Get method from the start, but I'm not yet convinced that it's completely incorrect to be using an indexer.
I'd be interested to hear all opinions, thanks.