开发者

Is there any reason why my repository methods should not be static?

开发者 https://www.devze.com 2023-03-29 13:47 出处:网络
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:

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(userVar开发者_如何学Pythoniable);

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.


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!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消