V
V
vitaly_742020-02-09 10:38:09
PHP
vitaly_74, 2020-02-09 10:38:09

The principle of closeness / openness, how to add a new method?

Good afternoon, I chose the PHP tag because. I write in php and it would be good luck to get an answer to my question.
Actually the principle says: The class should be immutable, but open to extension.
How to correctly add a new method to an extended class? Should I use inheritance or is there something else I can suggest?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
doctrine, 2020-02-09
@vitaly_74

Here are two examples. But it all depends on the specific case.

public interface EngineStartOperation {
    void start();
}

public interface EngineStopOperation {
    void stop();
}

public interface NewWhatEverMethod {
    void whatEver();
}





public class Engine implements EngineStartOperation, EngineStopOperation {
    @Override
    public void start() {
        // existing method
    }

    @Override
    public void stop() {
        // existing method
    }
}



public class WhatEverEngine1 implements NewWhatEverMethod, EngineStartOperation, EngineStopOperation {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void whatEver() {
        // new  logic here
    }
}


public class WhatEverEngine2 implements NewWhatEverMethod, EngineStartOperation, EngineStopOperation {
    private final Engine engine;

    public WhatEverEngine2(final Engine engine) {
        this.engine = engine;
    }

    @Override
    public void start() {
        engine.start();
    }

    @Override
    public void stop() {
        engine.stop();
    }

    @Override
    public void whatEver() {
        // new  logic here
    }
}

F
fix0_o, 2020-02-09
@fix0_o

Tweak interfaces in PHP

interface EngineInterface
    {
        public function ArrayMerge($item_1);

        public function value_search($item_1, $item_2);
    }

class ArrayFunct
    {
        private $Engine;
      
        function __construct(EngineInterface $Engine)
        {
            $this -> Engine = $Engine;
        }

        public function ArrMerge($array)
        {
            return $this -> Engine -> ArrayMerge($array);
        }

        public function value_search($array, $search)
        {
            return $this -> Engine -> key_search($array, $search);
        }
    }

class Engine implements EngineInterface
    {

        private $array_result;
        private $array_count;

        public function ArrMerge($array) {

            // ваш функционал

            return $result;
        }

        public function value_search($array, $search) {

            // ваш функционал
                
            return $result;
        }
    }

$engine = new Engine;
    $ArrayFunct = new ArrayFunct($engine);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question