Ever wondered what is the response given to an amateur who is auditioning in Hollywood or What about you calling up every recruiter out there for a job opening ? The response on either case is the same . You guessed it , “Don’t call us, we’ll call you” . Congratulations !! ,
you learned “Hollywood principle” in software programming
So let’s understand this principle in detail . When you do programming for a high cohesive and low coupled application , you use function callbacks most of the time , knowingly or unknowingly . So what is a function callback ? Is it like rather than your code calling a function , the function calls back your code ?
Here is an example . Let’s assume you need to create a function that calculates discount .This function take in the billAmount as a parameter and a callback function reference as second parameter. The advantage of this approach is the client code can change discount strategy , based on requirement with ease . Let’s say you can select different discount strategy on Monday , Tuesday ,Wednesday without changing other part of the code ,there by bringing in a loosely coupled approach . On Monday a 50% discount ,Tuesday 40% discount and Wednesday 30% discount .
This is a pseudo code, we will implement the same in Java using interfaces, and in C #you could use delegates to achieve the same. Here we will discuss how to use callback in Java via interface.
First you need an interface , which will define the callback method . IDiscount interface has getDiscountRate() as the callback method
Now we need the Discount Strategy classes for Monday ,Tuesday,Wednesday.
We need a concrete class which does the discount calculation. This function will take IDiscount as parameter , callBackDiscount.getDiscountRate() will invoke either MondayDiscount or TuesdayDiscount based on runtime .
Let’s test the code and find the output.