Thursday, March 13, 2014

Avoid flag parameters in public methods

I was recently reading some code that I wrote a while back, and it looked something like this:
run(true);
And then later on in the code I saw
run(false);
At the time I wrote this, it was very clear what this meant, and I was saving myself time by having a single method where a flag would slightly alter the behavior. Reading this code several years later, it wasn't clear at all what it was doing. So how did I write it so it was easier to read? Instead of having the flag in the public method, just have two separate methods, and bury the flag in a private method. After refactoring, my code now looks like:
runSynchronously();
and
runAsynchronously();
Internally, there is still a run method that takes a flag for running asynchronously, but the public API is now a lot easier to understand.

4 comments:

  1. For me, usually a month is enough to forget my code. So being very clean as you go is very important

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Thank you for the fresh content and information you provide. This really helps learner like me. Keep sharing knowledge. Happy to read.

    Java Training in Chennai

    Salesforce Training in Chennai

    ReplyDelete