Debunking The Myth Of Static Classes, Methods and Variables

An example:interface MyInterface { public function doThis(); public function doThat(); public function setName($name);}class MyClass implements MyInterface { protected $name; public function doThis() { // code that does this } public function doThat() { // code that does that } public function setName($name) { $this->name = $name; }}Now the same functionality can be achieved through static methods..The Helium SessionService is an example that sets up interfaces using static class:With this, we now can achieve Polymorphism by having all children classes required to enforce methods above..We will get into a use case later on how this relates to testing.Hard To Test & Hidden DependenciesFalse..A method being static or not has no bearing on its testability, especially if it does not have a state..An example:class Math { public static function add($a, $b) { return $a +$b; }}Math::add($a, $b);This will have the same testability if we did functional programming:$add = function($a, b) { return $a +$b;}add($a, $b);When ran through testing frameworks like PHPUnit, both functions will deliver the same result..Testing becomes more difficult with changing states that cause side effects, which is an object-oriented problem regardless if its an instance or static..Same for hidden dependencies, its how you design your application and is not related to static methods.Tightly Coupling and TestingIn this answer, we are going to start combining some of the different points discussed above..We’ve proven that with static methods we can have interfaces and abstract classes which creates the ability to have an inversion of control..This means loose coupling and testing different cases.Going back to our example of the session class from Helium, we can throw in a class that injects a Redis Session Handler..Using the code below as an example:SessionService For Dependency InjectionRedisSession To Be Injected In SessionServiceNow with dependency injection, we can create an inversion of control like so:$redis = new Redis();$redisSession = RedisSession::ServiceinitializeSession($redis);SessionService::initializeSession($redisSession);SessionSerivce::read(‘user_id’);Tie this in which the ability to swap session handing with Redis, with Cookies, or the database, we have the ability to test different interfaces as long as the SessionService class is the one being called..Again, static does not create a tight coupling and impede testing if implemented correctly.The Real Pros and Cons of Static is The StateSome applications have requirements that adhere to a global state where you want everything to function the same..In other applications, we may want certain routines to exist only for specific use cases that are changeable throughout an application.For example, caching.. More details

Leave a Reply