0

I have a number of classes (and interfaces) which 'code to an interface'

interface File 
{
    ...
}

interface FileConverter {
    public function convert(File $file); //coding to an interface
    public function success($message);
    public function failure($message);
}

I feel I can make the FileConverter interface even more generic by removing the File class type-hint in this interface to allow conversion between strings, arrays etc rather than just classes that implement File;

interface Converter {
    public function convert($input);
    public function success($message);
    public function failure($message);
}

However, if I do this, I feel I loose the 'coding to an interface' aspect - even though none of my classes directly use the FileConverter interface. Is this a wise choice or should I create a different interface? ie;

interface StringConverter {
    public function convert(string $string); //PHP 7
    public function success($message);
    public function failure($message);
}
  • 2
    It kinda depends on whether or not you want a File Converter. In some languages you can use streams for better abstraction. For instance, in C# you can have a FileStream and a MemoryStream, and they both have the same interface, just different constructors. – Robert Harvey Oct 5 '15 at 15:11
0

All objects implementing a particular interface must not only define methods with matching signatures, but also with matching semantics.

Meaning: you should be able to replace object A which implements I with object B which imolements I and still have things work.

If in your case both A and B define convert(), but A will only work with a string and otherwise crash or return something weird, and B can only work with files, thab they are not substituable, and do not actually implement the same interface.

( It just seems they do, because a dynamically typed language such as PHP doesn't force you to define the types in the method signature. The equivalent Java methods, for example, would be Something convert(String s) and Something convert(File f). Now it's clear that they're not the same interface.

I'm not saying you should always use type hinting in PHP. I'm saying that implementing an interface means matching particular semantics, and not just a signature.

  • Ok, so i'm asking if I can remove the type hinting completely? – myol Oct 5 '15 at 12:37
  • In my opinion you can have a StringConverter and interface and a FileConverter interface, each defining the same convert() method. But they will probably be usable in different places. – Aviv Cohn Oct 5 '15 at 20:20
  • 1
    The type hinting is just a bonus if you want to use it. It shouldn't affect the overall design, in my opinion. – Aviv Cohn Oct 5 '15 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.