This tool is currently proof-of-concept. Your feedback and evaluation is valuable in helping to improve it and ensure its reports are meaninful.
Please click here to complete a short survey to tell us what you think. It should take less than 5 minutes and help further this research project!
Symfony\Component\Routing\Router
Detected issues
Issue | Method | Line number |
---|---|---|
Multiple roles | N/A | 1 |
Using `new` in constructor | __construct | 105 |
Global/Static variables | NA | 95 |
Use of static methods | string | 374 |
Code
Click highlighted lines for details
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing;
use Psr\Log\LoggerInterface;
use Symfony\Component\Config\ConfigCacheFactory;
use Symfony\Component\Config\ConfigCacheFactoryInterface;
use Symfony\Component\Config\ConfigCacheInterface;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\CompiledUrlGenerator;
use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface;
use Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper;
use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;
use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
/**
* The Router class is an example of the integration of all pieces of the
* routing system for easier use.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
File has multiple roles
This file does more than one thing. For example, it creates some variables in global scope and then defines a class.
This is inflexible because it means you cannot load the class without first running this code that exists in global scope. There may be situations where you wish to load the class without running this code.
To fix
Move the class into its own file and autoload (or
require
/include
) the class where it's needed.{
/**
* @var UrlMatcherInterface|null
*/
protected $matcher;
/**
* @var UrlGeneratorInterface|null
*/
protected $generator;
/**
* @var RequestContext
*/
protected $context;
/**
* @var LoaderInterface
*/
protected $loader;
/**
* @var RouteCollection|null
*/
protected $collection;
/**
* @var mixed
*/
protected $resource;
/**
* @var array
*/
protected $options = [];
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* @var string|null
*/
protected $defaultLocale;
/**
* @var ConfigCacheFactoryInterface|null
*/
private $configCacheFactory;
/**
* @var ExpressionFunctionProviderInterface[]
*/
private $expressionLanguageProviders = [];
Global variables
Note: A future update will differentiate between
private static
variables andpublic static
orglobal
variables asprivate static
variables do not cause as much of a problem.Summary
- Hidden dependencies
- Broken encapsulation
- One component can accidentally overwrite data required by another component (action at a distance)
- You can only every have one copy of the variable
- Adding code requires knowing exactly what variables are already in use
- When working in teams, name clashes can be easily introduced
- Global state makes it difficult to reuse the code. E.g. having two files open at the same time would require writing the code twice, three times for three files, etc.
Background
The identification of global variables as a bad practice dates as far back at least as far back as 1973[1] and are one of the most widespread and well known bad practices related to flexibility. This is likely due to being available in almost every programming language, ease of use and speed to learn. They also cause severe problems in code and it's very easy to get caught out by using them, even in a small application.
Global vairables are widely labelled "bad practice" and have been for some time, for example back in 1999 Kernighan wrote:
Avoid global variables; wherever possible it is better to pass references to all data through function argumentsKernighan[2]
And Hevery[3] states:
I hope that by now most developers agree that global state should be treated like GOTO.This attitude is widespread and Sayfan[4] sums up the problem:
Whenever shared mutable state is involved, it is easy for components to step on each other's toes.Although "global variables are bad" is a common thing to here, for novice developers it's not immediately obvious why this is. However, the reasons have been covered frequently by developers of varying prominence. While writing about desiging the Eiffel programming language, [5] stated several problems with global variables:
Since global variables are shared by different modules, they make each of these modules more difficult to understand separately, diminishing readability and hence hampering maintenance.As global variables constitute a form of undercover dependency between modules, they are a major obstacle to software evolution, since they make it harder to modify a module without impacting others.They are a major source of nasty errors. Through a global variable, an error in a module may propagate to many others. As a result, the manifestation of the error may be quite remote from its cause in the software architecture, making it very hard to trace down errors and correct them. This problem is particularly serious in environments where incorrect array references may pollute other data.Action at a distance
This problem is commonly referred to as action at a distance and described by Hevery[6] as:
Spooky Action at a Distance is when we run one thing that we believe is isolated (since we did not pass any references in) but unexpected interactions and state changes happen in distant locations of the system which we did not tell the object about. This can only happen via global state.Broken encapsulation
The biggest issue with global variables (even private static variables) is that they break encapsulation. A class no longer has its own state and one instance of a class can affect the state of another. Although private static variables are the by far the least worst type of global variables they should still be refactored out where possible.
> Encapsulation refers to the bundling of data with the methods that operate on that dataBy making the data globally accessible, encapsulation has been lost. Any part of the program has access to the data and can modify it. Even when using private static variables, each instance no longer has control of its own sate.
Tight coupling
Global variables introduce tight coupling. In Object Oriented Programming an object should be self-contained[7][8]. If a class depends on a global (or static) variable, then moving the class to a different project requires defining the required global variables in the new project. Private static variables do not not introduce additional coupling.
Name Clashes
Global variables can introduce name clashes:
everywhere in the program, you would have to keep track of the names of all the variables declared anywhere else in the program, so that you didn't accidentally re-use one.Summit[9]
The problem of name clashes is magnified by the size of a team. If two people are working on a piece of software and both use global variables, it's possible they'll write some code using the same variable names. During execution this might cause the two peices of code to interfere with each other.
Examples
As a very crude example, imagine the following:
function getUser($id) {
$connection = Database::$connection;
$connection->query('SELET * FROM user ...')
}
This code assumes that
Database::$connection
has been set correctly and not overwritten. If any part of the application accidently runs the codeDatabase::$connection = null;
(or sets it to anything other than a database connection) then the code will fail. This is due to broken encapsulation and action and a distance.Anything in the code is able to change the property and cause unexpected behaviour when further methods are called on the instance.
This can also happen with private static properties:
class FileReadWrite {
private static $fileName;
public function __construct(string $file) {
self::$fileName = $file;
}
public function read() {
return file_get_contents(self::$fileName);
}
public function write(string $data) {
file_put_contents(self::$fileName, $data);
}
}
//Works as expected:
$file = new FileReadWrite('./one.txt');
$file->write('data');
//cause a problem
$file1 = new FileReadWrite('./one.txt');
$file2 = new FileReadWrite('./two.txt');
$file1->write('data1');
$file2->write('data2');This causes a problem because there is a global variable storing the file name. Assuming a class requires only one value of a variable across the whole application always limits flexibility. There are occasionally practical reasons for this such as keeping track of and limiting the number of open files/connections but flexibility is always reduced. Even in these practical exceptions, it introduces a new issue of separation of concerns: Should the class be concerned with the number of open connections throughout the application or should that be managed at an application level rather than a class level?
Although this is a contrived example, the same kind of bugs can occur any time a static variable is used. If it's set by one instance and read by another then unexpected changes can cause bugs.
Further reading
- What is tight coupling?
- Why Static is Bad and How to Avoid It
- Flaw: Brittle Global State & Singletons
- What's Wrong With Global Variables
References
- Wulf, W., Shaw, M. (1973) Global varaibles considered harmful. ACM SIGPLAN Notices , pp.28-34.
- Kernighan, B. (1999) The Practice of Programming ISBN: 978-0201615869. Addison Wesley.
- Hevery, M. (2008) Top 10 things which make your code hard to test [online]. Available from: http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/
- Sayfan, M. (n.d.) Avoid Global Variables, Environment Variables, and Singletons [online]. Available from: https://sites.google.com/site/michaelsafyan/software-engineering/avoid-global-variables-environment-variables-and-singletons
- Meyer, B. (1988) Bidding farewell to globals. JOOP(Journal of Object-Oriented Programming) , pp.73-77.
- Hevery, M. (2008) Brittle Global State & Singletons [online]. Available from: http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/
- Yaiser, M. (2011) Object-oriented programming concepts: Objects and classes [online]. Available from: http://www.adobe.com/devnet/actionscript/learning/oop-concepts/objects-and-classes.html
- Caromel, D. (1993) Toward a method of object-oriented concurrent programming. Communications of the ACM , pp.90-102.
- Summit, S. (1997) Visibility and Lifetime (Global Variables, etc.) [online]. Available from: https://www.eskimo.com/~scs/cclass/notes/sx4b.html
/**
* @param mixed $resource The main resource to load
*/
public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
{
$this->loader = $loader;
$this->resource = $resource;
$this->logger = $logger;
Usage of the new keyword in a constructor
Summary of issues
- Tight Coupling
- Hidden dependencies
- Broken Encapsulatioin
Background
If a dependency is constructed inside the object that requires it rather than passed in as a reference then flexibility is lost[1][2]
public class Car {
private Engine engine;
public Car() {
this.engine = new Engine();
}
}Here, the
Car
constructor creates theEngine
instance. This is inflexible as it forces allCar
objects to use the exact sameEngine
type. Instead, it would encourage reuse if the program supported different engine types (e.g.DieselEngine
,PetrolEngine
orHybridEngine
).The same is true when an instance variable is created when the class is defined:
public class Car {
private Engine engine = new Engine();
}By using the
new
keyword to instantiate a dependency, the specific implementation of that dependency is hardcoded and cannot be substituted.Instead, the dependency should be constructed outside the class and injected in:
public class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
}Using dependency injection it is possible to pass in any engine type:
//Instead of
Car myCar = new Car();
//It's now possible to construct different types of car:
Car petrolCar = new Car(new PetrolEngine);
Car electricCar = new Car(new ElectricEngine);A secondary advantage to Dependency Injection with regards to flexibility and encapsulation is that the class which has the dependency (
Car
, in this example) it not aware of the dependencies of theEngine
class.For example, if the
Engine
class required aGearbox
instance as a constructor argument, theCar
class would need to instantiate and pass in the relevantGearbox
instance. And provide any dependencies of theGearbox
class when instantiating it.If the constructor arguments of any of the classes which need to be instantiated are modified during development, any class which creates an instance of the class must also be modified. A change to the constructor for
Engine
would require modifying theCar
class. Instead, if the fully constructedEngine
instanceBy loosely coupling the
Engine
class to theCar
class, the author of theCar
class does not need to know anything about the implementation ofEngine
class or have knowledge of what dependencies it has.
public Car() {
this.engine = new Engine(new Gearbox());
}Further reading
Additional resources:
References
- Hevery, M. (2008) How to Think About the “new” Operator with Respect to Unit Testing [online]. Available from: http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
- Hevery, M. (2008) Code Reviewers Guide [online]. Available from: http://misko.hevery.com/code-reviewers-guide/
Please note: This feature is currently proof-of-concept, the instructions may not always be completely accurate.
\Symfony\Component\Routing\RequestContext
is instantiated inside the constructor ofSymfony\Component\Routing\Router
1) Remove the new expression and replace it with a variable:
$this->context = $context ?? new RequestContext();
becomes:
$this->context = $context ?? $requestContext;
2) Add a constructor argument for the new variable: Replace:
public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
with:
public function __construct(\Symfony\Component\Routing\RequestContext $requestContext, LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
3) Find any occurance of
new Symfony\Component\Routing\Router
and provide the new dependency.Please note: This feature is currently proof-of-concept, this patch may not work, please don't blindly apply it.
diff --git a/Loader/Configurator/CollectionConfigurator.php b/Loader/Configurator/CollectionConfigurator.php index 09274cc..f53cb00 100644 --- a/Loader/Configurator/CollectionConfigurator.php +++ b/Loader/Configurator/CollectionConfigurator.php @@ -28,12 +28,12 @@ class CollectionConfigurator private $parentPrefixes; private $host; - public function __construct(RouteCollection $parent, string $name, self $parentConfigurator = null, array $parentPrefixes = null) + public function __construct(\Symfony\Component\Routing\Route $route, RouteCollection $parent, string $name, self $parentConfigurator = null, array $parentPrefixes = null) { $this->parent = $parent; $this->name = $name; - $this->collection = new RouteCollection(); - $this->route = new Route(''); + $this->collection = $routeCollection; + $this->route = $route; $this->parentConfigurator = $parentConfigurator; // for GC control $this->parentPrefixes = $parentPrefixes; } @@ -122,4 +122,4 @@ class CollectionConfigurator { return (clone $this->route)->setPath($path); } -} +} \ No newline at end of file diff --git a/Loader/Configurator/RoutingConfigurator.php b/Loader/Configurator/RoutingConfigurator.php index 4687bf6..8ebc32e 100644 --- a/Loader/Configurator/RoutingConfigurator.php +++ b/Loader/Configurator/RoutingConfigurator.php @@ -57,7 +57,7 @@ class RoutingConfigurator final public function collection(string $name = ''): CollectionConfigurator { - return new CollectionConfigurator($this->collection, $name); + return new CollectionConfigurator(new \Symfony\Component\Routing\Route(''), new \Symfony\Component\Routing\RouteCollection(), $this->collection, $name); } /** diff --git a/Router.php b/Router.php index 6074037..49d9973 100644 --- a/Router.php +++ b/Router.php @@ -97,12 +97,12 @@ class Router implements RouterInterface, RequestMatcherInterface /** * @param mixed $resource The main resource to load */ - public function __construct(LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null) + public function __construct(\Symfony\Component\Routing\RequestContext $requestContext, LoaderInterface $loader, $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null) { $this->loader = $loader; $this->resource = $resource; $this->logger = $logger; - $this->context = $context ?? new RequestContext(); + $this->context = $context ?? $requestContext; $this->setOptions($options); $this->defaultLocale = $defaultLocale; } @@ -387,4 +387,4 @@ class Router implements RouterInterface, RequestMatcherInterface return self::$cache[$path] = require $path; } -} +} \ No newline at end of file$this->setOptions($options);
$this->defaultLocale = $defaultLocale;
}
/**
* Sets options.
*
* Available options:
*
* * cache_dir: The cache directory (or null to disable caching)
* * debug: Whether to enable debugging or not (false by default)
* * generator_class: The name of a UrlGeneratorInterface implementation
* * generator_dumper_class: The name of a GeneratorDumperInterface implementation
* * matcher_class: The name of a UrlMatcherInterface implementation
* * matcher_dumper_class: The name of a MatcherDumperInterface implementation
* * resource_type: Type hint for the main resource (optional)
* * strict_requirements: Configure strict requirement checking for generators
* implementing ConfigurableRequirementsInterface (default is true)
*
* @throws \InvalidArgumentException When unsupported option is provided
*/
public function setOptions(array $options)
{
$this->options = [
'cache_dir' => null,
'debug' => false,
'generator_class' => CompiledUrlGenerator::class,
'generator_dumper_class' => CompiledUrlGeneratorDumper::class,
'matcher_class' => CompiledUrlMatcher::class,
'matcher_dumper_class' => CompiledUrlMatcherDumper::class,
'resource_type' => null,
'strict_requirements' => true,
];
// check option names and live merge, if errors are encountered Exception will be thrown
$invalid = [];
foreach ($options as $key => $value) {
if (\array_key_exists($key, $this->options)) {
$this->options[$key] = $value;
} else {
$invalid[] = $key;
}
}
if ($invalid) {
throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid)));
}
}
/**
* Sets an option.
*
* @param mixed $value The value
*
* @throws \InvalidArgumentException
*/
public function setOption(string $key, $value)
{
if (!\array_key_exists($key, $this->options)) {
throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
}
$this->options[$key] = $value;
}
/**
* Gets an option value.
*
* @return mixed The value
*
* @throws \InvalidArgumentException
*/
public function getOption(string $key)
{
if (!\array_key_exists($key, $this->options)) {
throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
}
return $this->options[$key];
}
/**
* {@inheritdoc}
*/
public function getRouteCollection()
{
if (null === $this->collection) {
$this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
}
return $this->collection;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
if (null !== $this->matcher) {
$this->getMatcher()->setContext($context);
}
if (null !== $this->generator) {
$this->getGenerator()->setContext($context);
}
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* Sets the ConfigCache factory to use.
*/
public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
{
$this->configCacheFactory = $configCacheFactory;
}
/**
* {@inheritdoc}
*/
public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH)
{
return $this->getGenerator()->generate($name, $parameters, $referenceType);
}
/**
* {@inheritdoc}
*/
public function match(string $pathinfo)
{
return $this->getMatcher()->match($pathinfo);
}
/**
* {@inheritdoc}
*/
public function matchRequest(Request $request)
{
$matcher = $this->getMatcher();
if (!$matcher instanceof RequestMatcherInterface) {
// fallback to the default UrlMatcherInterface
return $matcher->match($request->getPathInfo());
}
return $matcher->matchRequest($request);
}
/**
* Gets the UrlMatcher or RequestMatcher instance associated with this Router.
*
* @return UrlMatcherInterface|RequestMatcherInterface
*/
public function getMatcher()
{
if (null !== $this->matcher) {
return $this->matcher;
}
if (null === $this->options['cache_dir']) {
$routes = $this->getRouteCollection();
$compiled = is_a($this->options['matcher_class'], CompiledUrlMatcher::class, true);
if ($compiled) {
$routes = (new CompiledUrlMatcherDumper($routes))->getCompiledRoutes();
}
$this->matcher = new $this->options['matcher_class']($routes, $this->context);
if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
foreach ($this->expressionLanguageProviders as $provider) {
$this->matcher->addExpressionLanguageProvider($provider);
}
}
return $this->matcher;
}
$cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_matching_routes.php',
function (ConfigCacheInterface $cache) {
$dumper = $this->getMatcherDumperInstance();
if (method_exists($dumper, 'addExpressionLanguageProvider')) {
foreach ($this->expressionLanguageProviders as $provider) {
$dumper->addExpressionLanguageProvider($provider);
}
}
$cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
}
);
return $this->matcher = new $this->options['matcher_class'](self::getCompiledRoutes($cache->getPath()), $this->context);
}
/**
* Gets the UrlGenerator instance associated with this Router.
*
* @return UrlGeneratorInterface A UrlGeneratorInterface instance
*/
public function getGenerator()
{
if (null !== $this->generator) {
return $this->generator;
}
if (null === $this->options['cache_dir']) {
$routes = $this->getRouteCollection();
$compiled = is_a($this->options['generator_class'], CompiledUrlGenerator::class, true);
if ($compiled) {
$routes = (new CompiledUrlGeneratorDumper($routes))->getCompiledRoutes();
}
$this->generator = new $this->options['generator_class']($routes, $this->context, $this->logger, $this->defaultLocale);
} else {
$cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_generating_routes.php',
function (ConfigCacheInterface $cache) {
$dumper = $this->getGeneratorDumperInstance();
$cache->write($dumper->dump(), $this->getRouteCollection()->getResources());
}
);
$this->generator = new $this->options['generator_class'](self::getCompiledRoutes($cache->getPath()), $this->context, $this->logger, $this->defaultLocale);
}
if ($this->generator instanceof ConfigurableRequirementsInterface) {
$this->generator->setStrictRequirements($this->options['strict_requirements']);
}
return $this->generator;
}
public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
{
$this->expressionLanguageProviders[] = $provider;
}
/**
* @return GeneratorDumperInterface
*/
protected function getGeneratorDumperInstance()
{
return new $this->options['generator_dumper_class']($this->getRouteCollection());
}
/**
* @return MatcherDumperInterface
*/
protected function getMatcherDumperInstance()
{
return new $this->options['matcher_dumper_class']($this->getRouteCollection());
}
/**
* Provides the ConfigCache factory implementation, falling back to a
* default implementation if necessary.
*/
private function getConfigCacheFactory(): ConfigCacheFactoryInterface
{
if (null === $this->configCacheFactory) {
$this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);
}
return $this->configCacheFactory;
}
Static methods
Summary of issues
- Tight Coupling
- Hidden dependencies
- Global state (if also using static variables)
Tight Coupling
Use of static methods always reduces flexibility by introducing tight coupling[1]. A static method tightly couples the calling code to the specific class the method exists in.
function totalAbs(double value, double value2) {
return abs(value) + abs(value2);
}Here, the method
totalAbs
has a dependency on theMath
class and the.abs()
method will always be called. Although for testing purposes this may not be a problem, the coupling reduces flexibility because thetotal
method can only work with doubles/integers, as that's all theMath.abs()
function can use. Although type coercion will allow the use of any primitive numeric type, these types have limitations. It's impossible to use another class such asBigInteger
or a class for dealing with greater precision decimals or even alternative numbering systems such as Roman numerals.The totalAbs function takes two doubles and converts them to their absolute values before adding them. This is inflexible because it only works with doubles. It's tied to doubles because that's what the
Math.abs()
static method requires. If, instead, using OOP an interface was created to handle any number that had this method:interface Numeric {
public function abs(): Numeric;
}It would then be possible to rewrite the
totalAbs
method to work with any kind of number:function totalAbs(Numeric value, Numeric value): Numeric {
return value.abs() + value2.abs();
}
By removing the static method and using an instance method in its place the
totalAbs
method is now agnostic about the type of number it is dealing with. It could be called with any of the following (assuming they implement theNumeric
interface)
totalAbs(new Integer(4), new Integer(-53));
totalAbs(new Double(34.4), new Integer(-2));
totalAbs(new BigInteger('123445454564765739878989343225778'), new Integer(2343));
totalAbs(new RomanNumeral('VII'), new RomanNumeral('CXV'));
Making the method reusable in a way that it wasn't when static methods were being used. By changing the static methods to instance methods, flexibility has been enhanced as the method can be used with any numeric type, not just numeric types that are supported by the
Math.abs()
method.Broken encapsulation
Static methods also break encapsulation. Encapsulation is defined by Rogers[2] as:
the bundling of data with the methods that operate on that dataBy passing the numeric value into the
abs
method, the data being operated on is being separated from the methods that operate on it, breaking encapsulation. Instead usingnum.abs()
the data is encapsulated in thenum
instance and its type is not visible or relevant to the outside world.abs()
will work on the data and work regardless ofnum
's type, providing it implements theabs
method.This is a simple example, but applies to all static methods. Use of polymorphic instance methods that work on encapsulated data will always be more flexible than static method calls which can only ever deal with specific pre-defined types.
Further reading
- What is tight coupling?
- Why Static is Bad and How to Avoid It
- Static Methods Will Shock You
- Flaw: Brittle Global State & Singletons
- Static Methods are Death to Testability
Exceptions
The only exception to this rule is when a static method is used for object creation in place of the
new
keyword[3]. This is because thenew
keyword is already a static call. However, even here a non-static factory is often preferable for testing purposes[4][5].References
- Popov, N. (2014) Don't be STUPID: GRASP SOLID! [online]. Available from: https://nikic.github.io/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html
- Rogers, P. (2001) Encapsulation is not information hiding [online]. Available from: http://www.javaworld.com/article/2075271/core-java/encapsulation-is-not-information-hiding.html
- Sonmez, J. (2010) Static Methods Will Shock You [online]. Available from: http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/
- Hevery, M. (2008) Static Methods are Death to Testability [online]. Available from: http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/
- Butler, T. (2013) Are Static Methods/Variables bad practice? [online]. Available from: https://r.je/static-methods-bad-practice.html
{
if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) {
self::$cache = null;
}
if (null === self::$cache) {
return require $path;
}
if (isset(self::$cache[$path])) {
return self::$cache[$path];
}
return self::$cache[$path] = require $path;
}
}