Search code examples
javaopen-closed-principle

Open-Close Principle Example


I want to apply the Open-close principle on this following example by re-writing this code.

class MyQueue<E> extends ArrayList<E> implements Queue<E> {
   int front=0, back=0;
   MyQueue() { }
   …
   void put(E e) { add(back++, e); ...}
   E get () { E elem = get(front++); …}
}

What design pattern would the solution most closely match, and why? Explain why it’s a better match than the next best match.

I am having trouble thinking of what features this class would extend. It already has the getter and setter. Without knowing what type of extensions can be applied, I am not sure how to rewrite this code.

What I know: OCP is open for extension-closed to modification. Thus, a general approach is to figure out how to abstract it. So my initial thought was to make this an abstract class with abstract methods. Then, every class that would extend MyQueue() would be able to implement the getter and setter methods however it wanted. And, if I do this, then I'd assume that this closely matches the adaptor pattern.

Please correct any mis-understandings I have with my understanding.


Solution

  • From my perspective this is an example of making Queue based on ArrayList implementation. First of all I will try to expose only Queue interface method. All methods that will be inherited from ArrayList should be somehow hidden.

    Thing is, we know that in Java you can't hide public method during inheritance. Then, only approach you can take is to override them and throw UnsupportedOperationException or sth like this.

    You need to make sure you will implement correctly Queue interface based on ArrayList inside. You should implement correctly add, offer, remove, pool, element, peek. Other methods originating from ArrayList should throw some exception.

    This is my opinion on this subject.