1

I have a number of classes with a single public method. Looking at this answer, I tend to agree with what is stated.

The OP lists some examples, which I interpret to be used like

(new VideoCompressor)->compress($raw_video);

While the readability improves slightly by calling the explicit method name, I feel it is almost as readable by simply moving the parameters to a __construct() and calling the compress function from within the constructor.

new VideoCompressor($raw_video);

This however would add a constructor to the class if it didn't have one already.

In my eyes it would be a trade between slightly smaller calls to classes in exchange for more code within the class.

Is there any other reason either method should be preferred other than personal taste?

myol
  • 235
  • 4
  • 11

3 Answers3

5

Would this work? Yes. Is this proper class design? No.

A constructor's purpose is to ensure valid creation (construction) of the instance, no more and no less.

Phil Sandler
  • 560
  • 3
  • 7
3

Calling the compress function is the correct approach. That way you can easily implement multiple compression methods.

interface VideoCompression
{
    public function compress($rawVideo);
}

final class MP4VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}

final class H264VideoCompression implements VideoCompression
{
    public function compress($rawVideo) { }
}

Then later in your app you can get the video compression class based on user's input via a factory, for example.

Update: After checking the original thread I realized MainMa posted exactly the same approach as me with further reasons why to use that way.

Andy
  • 10,238
  • 4
  • 25
  • 50
1

As a quick example. I hope you see that tieing the consturction of an object to the moment of use eliminates dependancy injection, ties you to a concrete type eliminating polymorphism (using a different IVideoCompressor is now impossible) and is generally bad:

    interface IVideoCompressor
    {
        Compress();
    }

    class VideoCompressor : IVideoCompressor
    {
        public byte[] Compress(byte[] input){
             throw new NotImplementedException();
        }
    }

    public class DirectoryFiddler
    {
        IVideoCompressor _videoComp;

        public DirectoryFiddler(IVideoCompressor videoComp, IImageCompressor imageCOmp)
        {
            _videoComp = videoComp;
        }

        public byte[] DoSomething(Idirectory directory)
        {
            // DI, polymorphism, in general good stuff
            return _videoComp.Compress(directory.Video);
        }

        public byte[] DoSomething2(Idirectory directory)
        {
            // Tied to VideoCompressor
            return new VideoCompressor(directory.Video).Compress();
        }
    }
Nathan Cooper
  • 1,319
  • 9
  • 15