Static function

Hi,

Our team is doing PHPUnit testing, one of my colleagues created a class and she makes it all the function to public static. the reason she makes it static because it is easy to test as she said.and also it’s because she did not use a design pattern that’s why she did that?. can I ask some help what would be the design pattern to use so that we will not make all the function to be static. and can easy to test ?

Thank you in advance.

Not sure why she says static methods are easier to test:

  1. In isolation, when testing the class that contains the method it really doesn’t matter whether it’s static or not - both are as easy to test.

  2. In a larger system, when collaborating with other classes, using static functions is harder to test because you can’t1 swap them out at runtime. So if the static method accesses a database for example, it’s not possible to write to a fake (in-memory) database during tests, while this would be possible if it was a dynamic method on class that was injected.

Why exactly does she state that static methods are easier to test?

Also, it’s not a design pattern, but using static methods all over the place is usually a violation of the Depency Inversion Principle.

As far as I know there is no design pattern that really cares about static methods - that’s not what design patterns are about.

1 edited; it said can, but that’s incorrect

1 Like

Yeah I agree on that it will violate on the principle.

As far as I know there is no design pattern that really cares about static methods

Ok, since we are not using design pattern, what are normally used design pattern when building system ?..

Well, it depends on what your building. A design pattern is a solution to a known problem. You can’t just take a design pattern and solve everything with it. That would be an architecture.
But you start learning more about design patterns first. You need to learn to walk before you should run and all that.

Thank you :slight_smile: