Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 233
MetaGuru Avatar asked Aug 19 '11 15:08

MetaGuru


People also ask

Why is it illegal for a static method to invoke a no static method?

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.

How do you fix non-static method Cannot be referenced from a static context?

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.

Why static methods Cannot access instance variables?

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.

Why non-static variables are not allowed in static Block?

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.


1 Answers

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!

like image 101
Dennis Traub Avatar answered Oct 21 '22 09:10

Dennis Traub