---
# System prepended metadata

title: Open-Close Principle (OCP)

---

# Open-Close Principle (OCP)
    Software design should be open for extension, but closed for modification.
    
For those who are resolved to beat our design bonus, this document clarifies our criteria of Open-Close principle.

* To follow OCP, your code (except the Main class) **must not**:
    * Directly couple to your Main class (or any static fields/methods declared in the Main class) 

The following code shows an example of direct coupling to the `Main` class. 
```java=
public class MusicPlayer {
    pudlic void play(Song song) {
        if (Main.hasSupport(song)) {
            System.out.println("Playing the song ..." + song.getName());
        }
    }
}
```

This is the most common case that traps many students in, but unfortunately, this will break our OCP. 

We always want to decouple our domain/core modules (In our case, `Big2`) from the module's client (In our case, `Main`). Let's say, if you want to reuse your Big-2 module on **Android app's development, your program's entry class will be changed** and hence will break all of your classes that direclty couple `Main`.

That's the reason, no classes should be directly coupling to the `Main` class.

> We say that A couples B, which means that if B doesn't exist then A can't compile as well as if B is modified then A has to be re-compiled.

* OCP states that, if you have followed OCP, in case that you want to extend your program with new features, **you only have to**:
    * Modify the **initialization procedure** within your program's entry (In our case, `Main` class).

* Initialization includes:
    * Object instantiations (`new` operators)
    * Dependency Injection (DI)

What is **Dependency Injection (DI)** ?

**Dependency Injection**: Inject values or objects into another object **via its constructor or setters**.

For example: You inject an apple into a student by writting the following:

```java=
Apple apple = new Apple();
Student student = new Student("Johnny", apple);

or

student.setApple(apple);
```

Because the student depends on the apple's instance (maybe he wants to eat and can't live without it?) and the instance is resolved by injecting it so we call it dependency-injection. (There will be a lot of discussions about DI in Homework 2)

Yes, it's simple as how it's termed, but we are here to formalize its definition.

That's all! Let's meet the 'advanced design' together there :)


-- Waterball


