In languages like Java or C# you can declare a certain method (including the constructor) to be only visible to the same package (Java) or project (C#). This makes sure you don't have to jump through the hoops of reflection to let the Factory use the constructor without making it available to the rest of the world. This makes it a lot cleaner.
The main reason you would want a separate class is separation of concerns: one class that deals with the logic of being a Thing (a TimeSpan, in this case), one class that deals with the logic of creating a thing (the TimeSpanFactory).
If the business logic for creating a Thing is more involved than a simple check, this is easier to contain in a ThingFactory class than in the Thing::factory(...) function.
If you need multiple different ways to create a Thing, for example if you have different types of configuration or if you want to mock the factory for testing, it's easier to have that in separate ThingFactory classes than to have it in the Thing.
There are a couple more reasons why you would want this separation, and most of them have to do with rising complexity of having it all in one class. I will concede that it's not always worth it in PHP, where it's a bit harder to separate the classes, but it does pay off as complexity increases.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
In languages like Java or C# you can declare a certain method (including the constructor) to be only visible to the same package (Java) or project (C#). This makes sure you don't have to jump through the hoops of reflection to let the Factory use the constructor without making it available to the rest of the world. This makes it a lot cleaner.
The main reason you would want a separate class is separation of concerns: one class that deals with the logic of being a
Thing
(aTimeSpan
, in this case), one class that deals with the logic of creating a thing (theTimeSpanFactory
).If the business logic for creating a Thing is more involved than a simple check, this is easier to contain in a
ThingFactory
class than in theThing::factory(...)
function.If you need multiple different ways to create a
Thing
, for example if you have different types of configuration or if you want to mock the factory for testing, it's easier to have that in separateThingFactory
classes than to have it in theThing
.There are a couple more reasons why you would want this separation, and most of them have to do with rising complexity of having it all in one class. I will concede that it's not always worth it in PHP, where it's a bit harder to separate the classes, but it does pay off as complexity increases.