lundi 26 octobre 2020

Does changing parameter and return types in a child class, means breaking SOLID design principles?

I am building an application which uses API to retrieve data from a third party source. The data that is consumed needs to be formatted so I have decided to create an ConvertTypeInterface that forces child classes to implement convert($data) method which will convert/format any data into any other format.

ConvertTypeInterface

interface ConverterTypeInterface
{
    public function convert($data);
}

Now the problem with this I think I might be breaking Liskov's Substitution principle by not forcing stricter types on parameters or return types, however in this case I can't use type hinting for a parameter or a return type because $data parameter can be anything: string, integer, object, array etc. same with the return type.

Converter Example

class ConvertToInteger implements ConverterTypeInterface
{
    public function convert($data)
    {
        return (int) $data;
    }

}

Usage Example

/* I have an array of data field names and type of conversion that should be made for that field,
 * I loop through each of the fields that need to be converted and based on a converter type conversion 
 * changes the value of that field.
 */
    foreach ($convertFields as $field=>$type){
       if(isset($this->converters[$type])) {
           $data[$field] = $this->converters[$type]->convert($data[$field]);
       }else {
           throw new \Exception("Converter type `".$type."`` doesn't exist");
       }
    }

Question

Is this breaking Liskov's substitution principle or another SOLID design principle? Is there a way to improve this ?

Aucun commentaire:

Enregistrer un commentaire