Assistance with the Open-Closed Principle

104 views Asked by At

I was assigned a homework project to figure out why a code snippet does not fit the Open-Closed principle, but I'm having trouble figuring it out. I'm only here asking for someone to set me on the correct path, not to get my homework done for me. If anyone can help me out by telling me what I'm looking for in this code, that would be much appreciated.

public class MyQueue<T> extends ArrayList<T> implements Queue<T> {
    int front = 0;
    int back = 0;
    void put(T e) {
        add(back++, e);
    }
    T get() {
        return get(front++);
    }
    // ... other methods from Queue interface
} 
1

There are 1 answers

0
Pelit Mamani On

Please note the "open closed" principal isn't exact science - it requires human guesswork as to "what people might want to extend". If I create an application that draws a rainbow - would you expect hooks to change color shades? Image size? Or would you expect me to go further and allow hooks to change the image altogether - say to an elephant? Go even further and allow animation... ?

So I can't be a 100% sure what extensions you instructors expects. But it springs to mind that inheritance from ArrayList isn't very nice, don't you think? It violates other principals such as encapsulation, but to the subject at hand - what if I wanted to "plug in" my own List, say one that is backed up by a file? Or one that is replicated on several machines?

You can use your imagination to consider other possible extensions. But that really depends on the level and emphasis of your course. E.g. are you expected to be able to write a Queue that is flexible enough to support a priority queue?