I have been reading about solid OOP principles (Dependency Inversion Principle) and did not quite get how does this work.
When one class knows explicitly about the design and implementation of another class, changes to one class raise the risk of breaking the other class.
let say I have student which depends on Course if I will change course how it will affect to student. is it the same to use DI I mean DI replace new operator so whats then? student still depends on course
can you give some examples please.
thanks
public class Student {
.....
private Course course = new Course();
}
updated 1
(scenario) if I will assume that class has only default constructor and it will never use any instance variables to instantiate like new Course(name, .......)
updated 2
Example
public class Copy {
@Autowired
private Writer writer;
.....
}
public interface Writer{
void write();
}
public class PrinterWriter implements Writer {
.....
}
public class DiskWriter implements Writer {
....
}
Now what happens is that our copy module needs to know about a printer and a disk, you can imagine those magical if-else statements that come to rescue us in these situations. As the new requirements emerge along the way, you probably add more and more dependencies to this copy module. At the end of the day, you would end up with a very complex, hard to maintain and hard to understand design.
Can you show in this example where specifically dependency inversion eliminates use of magical if-else statements with simple example please
I'd add a level of indirection:
class Curriculum
. The class coordinates the participants of a course and may be the single point of change.From here you could implement concrete
Professor
,Student
orStaff
classes, which have dedicated privileges etc.