Reputation: 464
Everyone knows this
using (var db = new DatabaseEntites())
{
var row = db.SomeTable.SingleOrDefault(r => r.Id == 5)
}
I planned to create a static class with a static method like this
public static class SomeTableRepository
{
public static class GetSomeTableRow(DatabaseEntities db, int id)
{
return db.SomeTable.SingleOrDefault(r => r.Id == 5);
}
}
and the first code would then look like this
using (var db = new DatabaseEntites())
{
var row = SomeTableRepository.GetSomeTableRow(db, id);
}
If this would be a web app...would that kind of programming be ok...or could that kind of programming cause some trouble?...or is this perfectly good code :)
Upvotes: 0
Views: 1141
Reputation: 67115
As Kirk said, I think the only gain is minor readability. However, if you add this
in front of your first parameter and make this an extension method, then you might gain some readability for potential readers of your code:
UPDATE
I also noticed that public static class GetSomeTableRow
would not compile. I changed it to be more generic and less confusing for future readers (class
to YourClassName
)
public static class SomeTableRepository
{
public static YourClassName GetSomeTableRow(this DatabaseEntities db, int id)
{
return db.SomeTable.SingleOrDefault(r => r.Id == 5);
}
}
...
database.GetSomeTableRow(id);
Furthermore, you could rename this to make it read more like what it actually is:
database.GetOneRowFromSomeTableById(id);
Yes, it is lengthy, but the only reason to abstract such a simple method as SingleOrDefault
would be to make the code even readable at a glance. The ById
part is debatable since the parameter is named id
(and it makes it seem redundant), however that only shows up while coding with intellisense. You could leave it out (or take it down to just By
without Id
...but that leaves too much for each implementer IMO)
database.GetOneRowFromSomeTable(id);
Upvotes: 3
Reputation: 77586
The code is technically acceptable, but why would you do it? It's creating an indirection without making the code substantively more concise. Thus you make your code harder for most people to understand. The benefit is your code is two characters shorter. That doesn't seem like a win to me.
Myself, I would use the standard LINQ operators unless I'm genuinely adding some real value.
Upvotes: 5