2

Me and my co-workers are having a bit of a discussion about one of the code analysis issues thrown by visual studio:

CA1822  Mark members as static  The 'this' parameter (or 'Me' in Visual Basic) of 'UnitTest.CreateSimulation()' is never used. Mark the member as static (or Shared in Visual Basic) or use 'this'/'Me' in the method body or at least one property accessor, if appropriate.   UnitTests.ModuleSimulator   UnitTest.cs 68

I personally think making methods static is against object orientated programming, it's not necessarily bad practice but, I certainly think it's not good practice either. I do understand that making it static can improve the performance as stated in the msdn library:

Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code.

So my question is as follows, is making static methods/properties/fields against object orientated programming? And if not, should one always declare methods static when the code analysis prompts the option? (Disregarding all exceptions such as overriding the method somewhere else and using a "this" parameter in the overridden method.)

  • 1
    What makes you think that static methods are "against object orientated programming"? UML specifically allows for it. It even has a <<Utility>> stereotype for classes whose methods are all static. – Simon B Oct 26 '15 at 10:37
  • Well I have always been thought (also in the UML course I followed) that if static is not necessary you shouldn't use it. You should try to avoid making it necessary even. – Vincent Oct 26 '15 at 10:40
  • If something is effectively static (doesn't touch the object state and shouldn't be overriden for a method, is a read only identical copy in each instance for fields) then pretending it isn't doesn't change anything – Richard Tingle Oct 26 '15 at 12:32
  • objects with state can be harder to test; hard to setup the state to test specific logic. static methods can be easier to test if state is only passed as arguments. Scala has specific support for this practice in having a static 'companion' singleton object for each class. then you typically try to write algorithmic code as static and stateless in the static companion which is easier to test and invoke that in the instance class. java has little support for this approach which in scala is best practice. used wisely static can improve testability without harming reuse or safety. – simbo1905 Oct 26 '15 at 12:49
  • Oke @simbo1905, but in the case of c#, what's your opinion there then? because, that's quite similar to java (if i'm not mistaking) – Vincent Oct 26 '15 at 13:10