Reputation: 43813
I have been working with an MVC app and creating Repositories that manipulate, validate, update, and read/write data. All of them are static. Here is an example:
public static int Create(user u)
{
using(DataContext db = new DataContext())
{
//do the thing and submit changes...
}
//return the new user id
}
(Note: this is just a sample, I am not looking for tips about creating users or returning user ids, etc.)
Then I can just call int id = RepoClassName.Create(userVariable);
Is there anything wrong with using static methods like this? I just don't see why I should need to instantiate an object to do this.
Upvotes: 11
Views: 3227
Reputation: 51624
Well if you don't intend to decouple, test, and easily maintain your "repository", I guess static is just fine.
If you want to know more about why static methods are considered a code smell, here's a nice article at the Google Testing Blog. This, of course, assumes that you care about testing your code at all.
But hey, it's 2011, who wouldn't!
Upvotes: 7
Reputation: 4120
I wouldn't encourage the use of static methods in your repository. For one, you cannot use dependency injection with your repositories, because the injected dependencies aren't available in the static methods, only in instance methods. Testing wil be difficult.
Upvotes: 0
Reputation: 12203
May be down the line when you need multiple instances of repository, you may not be able to do so. Also you may not be able to use Dependency Injection if the methods are static.
Upvotes: 1