Question

Assuming that I have to create a class that takes some text do some processing and return it ... with no dependency and it's a stateless class..

I'd like to know would be better to create a stateless class without constructor or just create a static class (in php it's just Static methods)

class like this:

class ClassName
{
    public function processText($text)
    {
         // Some code
         $text = $this->moreProcessing($text);
         return $text;
    }

    protected function moreProcessing($text)
    {
        return $text;
    }
}

and this:

class ClassName
{
    public static function processText($text)
    {
         // Some code
         $text = static::moreProcessing($text);
         return $text;
    }

    protected static function moreProcessing($text)
    {
        return $text;
    }
}

I Know that dependency injection into the class where these classes are used would be better but assume that I just won't have dependency injection..

My question is mainly would it be better to create static class for the simple example above?

Was it helpful?

Solution

Practically you will see no difference whatsoever.

It's only in the syntax, and the ability of a constructor to perform stuff automatically, though you still have to create instances to invoke the constructor, which in this case is not far off calling some equivalent static member function.

However, non-static member functions are supposed to affect internal state so, if you have no state, static member functions seem more conventional, and will be slightly less surprising to users of the class.

The best approach, though, is to stick your functions in a namespace. Classes are for data and functions operating on that data... even static ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top