tl; dr Do you use static methods? Yes, when they do not depend on the internal state of the object.In the discussions on the
post (
translation ) about the named constructors, the opinion was expressed that static methods are bad and should not be used at all. In my opinion, this is too big a generalization.
Static methods are essentially just a way of organizing global functions into namespaces. Using namespaces, I think you will agree - good form. As for global functions, we always use them; the built-in functions of PHP form the basis of our code.
')
The main problem here is the lack of a shared global state. Here is an example from the last post:
<?php $time = Time::from("11:45");
In this example, the returned result is free from side effects and quite predictable, because depends only on the arguments supplied to the input. Every time you call a method, you will be returned an identical result (a Time object with a value of 11:45), regardless of the system state, context, or anything else.
Another example:
<?php $sum = Calculator::sum(1, 2);
And again - the result is predictable,
Calculator::sum(1, 2);
provides us with a stateless service that does not depend on anything but arguments. Moreover, this implementation cannot be polymorphic or have different implementations, since any result except
3
will be an error. Yes, you can change the internal implementation of the method by improving the algorithm for adding numbers, but this should not affect the result of its use.
Take the reverse example, this time with the state:
<?php Counter::increment(1); $count = Counter::getCount();
The example is elementary, but in more difficult situations it may not be as intelligible. Imagine that two developers use counters in their code. When they test their solution in isolation - there are no problems. But after integrating their solutions, the counter does not start working as expected, because it uses the global state, instead of using a separate counter instance.
Abstraction
Perhaps you still feel rejection against the code, like
Calculator::sum($x, $y)
, since we cannot simulate or expand it. But do not forget that this is a rather low level of abstraction. You also cannot simulate and extend the
+
operator in PHP, but I don't think you ever felt the need for it. If you need a higher level of abstraction, then composition is your faithful companion. But I want to note that there is a rather interesting difference between
Calculator::sum($x, $y)
and
+
, the first can be like this, but the second is not:
<?php $result = array_reduce([1,2,3], 'Calculator::sum', 0);
All this may seem redundant, but do not forget about the functions and static methods, because they can be very useful when properly applied.
Part 1:
How to use named constructors in PHP