javaopen-closed-principle

Testing Open-Close principle in Java


To demonstrate Open/Closed principle of SOLID principle, I implemented the following code.

Code:

interface IFaculty{
    void admin();
}

class ITFac implements IFaculty{
    @Override
    public void admin() {
        System.out.println("IT Fac Admin");
    }
}

class MedFac implements IFaculty{
    @Override
    public void admin(){
        System.out.println("Med Fac Admin");
    }
}

class University{
    public void adminFaculty(IFaculty iFaculty){
        iFaculty.admin();
    }
}

To test the above code, I tried to call the adminFaculty() method in the main method of main class as follows.

Code:

public class Main {
    public static void main(String[] args) {
        University u1 = new University();
        u1.adminFaculty();   // cannot call this method without passing parameters
    }
}

But I cannot call the method without passing the relevant parameter: an object of IFaculty. But I cannot do so. Does anybody knows how to call the adminFaculty(), from the main method? or any way to call the adminFaculty() and run the code to give relavent output.?

Thank you.


Solution

  • From your question I assume you want to be able to call adminFaculty() and always use the same faculty. For that, don't pass the faculty to the method but keep a reference in University. You can also add a default faculty.

    class University {
      private IFaculty faculty;
    
      //default configuration of the university: it has a medical faculty
      public University() {
        this(new MedFac());
      }
    
      //allows to create a university with another faculty type
      public University( IFaculty faculty) {
        this.faculty = faculty;
      }
    
      public void adminFaculty(){
        faculty.admin();
      }
    }
    

    Now you can use it like this:

    University medicalUni = new University();
    medicalUni.adminFaculty();
    
    University anotherMedicalUni = new University(new MedFac());
    anotherMedicalUni.adminFaculty();
    
    University itUni = new University(new ITFac());
    itUni.adminFaculty();
    

    Note that you always need an implementation of IFaculty like MedFac or ITFac. Of course I now could add a new faculty without having to change University:

    class TechFac implements IFaculty{
      @Override
      public void admin() {
        System.out.println("Tech Fac Admin");
      }
    }
    
    University techUni = new University(new TechFac());