Avoiding Temporal Coupling

Ahh, I just love getting back to my blogging time. Its been a busy month with lots of caffeine and code. But that's divine isn't it? So, getting back to basics, I hate coupling in my code, umm.. Everyone does. I just wanted to highlight one not so apparent coupling seen all over the “bathroom wall of code”, Temporal Coupling. For the definition freaks, Temporal Coupling is when your functions need to be called in a specific timeline/order to get the desired output. Well, look for yourself,

internal void BeAGuitarist()
{
BuyAGuitar();
TuneGuitar();
StartRocking();
}


To BeAGuitarist, the order in which the functions are called inside it are important. If you are developing an application framework which will be used by gazzilion developers to build their applications, how would you instruct each one of them to follow this order. Sooner or later it will get out of control and you would get mails like your framework sucks to the core.

One of the primary reasons for Temporal Coupling is global variables. In the earlier snippet, probably there is a variable “guitar” which is being modified by each of the functions. If we can localize that variable and pass it as an argument to the functions, we eventually force the usage in a particular way. The above code can also be written something like this,



internal void BeAGuitarist()
{
BuyAGuitar();
TuneGuitar(guitar);
StartRocking(tunedGuitar);
}


I hope you get the point, if not, just fuck it, I am too cynical about many things in life!

Happy Programming!

Abhang Rane


1 comment :

Reader's Comments

  1. To hammer the point home, possibly write it as:

    void BeAGuitarist() {
    RawGuitar rawGuitar = BuyAGuitar();
    TunedGuitar tunedGuitar TuneGuitar(rawGuitar);
    StartRocking(tunedGuitar);
    }

    Some details are hidden though:
    - what happens to 'rawGuitar' once tunedGuitar appears..
    is it consumed, or does it magically upgrade its type?
    (if the guitar-pointer was a pImpl, it could actually internally switch class?)

    ReplyDelete