As Linus suggests to us in his wisdom, let's look at some code.
Say, you have your "static" class (not a thing):
class MyClass
{
public static function doThing(): void
{
// Do something
}
}
Now, say you wanna add another method, which shares some logic with the first one:
class MyClass
{
public static function doThing(): void
{
// Do something
// Then, do this particular thing
}
public static function doOtherThing(): void
{
// Do something else
// Then, do the same particular thing
}
}
Makes sense to extract that same particular thing that both doThing()
and doOtherThing()
to a method of its own, right?
class MyClass
{
public static function doThing(): void
{
// Do something
static::doParticularThing();
}
public static function doOtherThing(): void
{
// Do something else
static::doParticularThing();
}
public static function doParticularThing(): void
{
// Some more generic or repetitive logic
}
}
Great! Now consumers of MyClass
can also start using doParticularThing()
. Like with any other public API, this can lead to a situation where you remove that method because no other logic of yours depends on it anymore, and break all consummers of doParticularThing()
. They come and create issues in your tracker. Let's say you don't want that:
class MyClass
{
public static function doThing(): void
{
// Do something
static::doParticularThing();
}
public static function doOtherThing(): void
{
// Do something else
static::doParticularThing();
}
protected static function doParticularThing(): void
{
// Some more generic or repetitive logic
}
}
Now you have a class that other code can use to doThing()
and to doOtherThing()
, but they are safe from doParticularThing()
that you might change or remove later. This is good API design, and your consumers will thank you if you use this approach correctly.
protected static function
is legit, it can be used as helper method for other static methods. – Chase