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.
A non-static method is a method that executes in the context of an instance . Without an instance it makes no sense to call one, so the compiler prevents you from doing so - ie it's illegal.
There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Namely, static methods can only use static variables and call static methods—they cannot access instance variables or methods directly, without an object reference. This is because instance variables and methods are always tied to a specific instance, i.e., object of their class.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With