Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

David Zentgraf:
How Not To Kill Your Testability Using Statics
Dec 05, 2012 @ 17:57:33

If you've been around PHP for any length of time, you know about the static functionality and keyword that the language offers. You might have used it in the past for a few things, but maybe you're not 100% sure of how to use it right. If this describes you, you should check out this article from David Zentgraf for a great summary of their use and how to not kill the testability of your application by using them,

"Class Oriented Programming" is what people do when they write classes which are all static methods and properties and are never once instantiated. I'll try to explain why this adds virtually nothing vis-a-vis procedural programming, what these people are really missing out on by ignoring objects and why, against all odds, statics don't automatically kill testability. While this article focuses on PHP, the concepts apply equally across many languages.

He talks about code coupling, expectations when using static classes/methods and how it seems a little too similar to some of the procedural PHP we all started out writing. He ponts out that most static method calls are more like function calls than true OOP methods and that their dependencies are a bit more difficult to manage. He suggests that statics are really only good for one kind of thing - dealing with already static data and "utility methods" operating on given data.

tagged: static method testability function method oop

Link:

Reddit.com:
Avoid static methods at all costs? (testability)
Sep 26, 2012 @ 16:59:04

On Reddit.com there's a recent post questioning the (recently) common saying that PHP developers should avoid static methods when concerned about testability:

I get it: testing is important, and building your codebase in a manner that is easy to test should be a priority. However, sometimes I feel like I have to compromise on the elegance of my code in order to maintain testability. Cases where perhaps a static method makes sense, but end up having to perform some coding acrobatics in order to avoid it. Is this a common challenge, something many developers face and must balance between? Or am I misguided in how frequently static methods can be the most elegant solution (before taking testability into consideration)?

Answers point out a few things - that sometimes, state doesn't matter and static is okay or that they can be used if the instance they return is always exactly the same, never altered.

tagged: static methods unittest testability opinion

Link:


Trending Topics: