Sounds fancy?
So, I’ve Been Exploring Java Spring, and that’s when I stumbled upon the Hollywood Principle, which is a software design principle that states “don’t call us, we’ll call you.” In other words, it encourages loose coupling between modules by having high-level modules depend on abstractions rather than concrete implementations. This makes it easier to swap out implementations without affecting the rest of the system.
In Java, this principle can be implemented using interfaces and dependency injection. Interfaces allow for the creation of abstractions that can be implemented by multiple classes. Dependency injection allows for the injection of a concrete implementation at runtime, rather than having the class create its own dependencies.
Example code that violates the Hollywood Principle:
//Bad Example, Tight Coupling
class BadMoviePlayer {
public void playMovie() {
//creating instance of concrete class
MobileDevice mobileDevice = new MobileDevice();
mobileDevice.playMovie();
}
}
In this example, the BadMoviePlayer
class creates an instance of MobileDevice
and calls its playMovie()
method. This creates a tight coupling between the BadMoviePlayer
class and the MobileDevice
class, making it difficult to swap out the implementation without affecting the rest of the system.
A better way to implement this would be to use interfaces and dependency injection:
interface Device {
void playMovie();
}
class GoodMoviePlayer {
private Device device; public GoodMoviePlayer(Device device) {
this.device = device;
} public void playMovie() {
device.playMovie();
}
}class MobileDevice implements Device {
public void playMovie() {
// Perform action
}
}
In this improved example, GoodMoviePlayer
doesn’t care what specific device it’s working with. It only needs a Device
. You can pass in any class that implements the Device
interface, making it super easy to swap out one device for another.
Real-World example
Let’s say you’re working on an Android app, and you need to change the network library. Instead of hunting down every instance of the old library in your code, you just create a new implementation of your Network
interface and inject it where needed. Boom—problem solved.
Another great use case is with payment gateways. Imagine your app supports multiple payment options like PayPal and Stripe. By creating an interface that outlines the required payment methods, you can easily switch between different payment gateways without touching the rest of your code.
So, in conclusion, The Hollywood Principle is your ticket to writing flexible, maintainable code. Java makes it easy to implement, especially with tools like Spring.
And just like in Hollywood, remember — you’re not the star, the code is. 👀