Quantcast
Channel: Planet Object Pascal
Viewing all articles
Browse latest Browse all 1725

Žarko Gajić: Fun: Refactoring a Complex Delphi Boolean Function

$
0
0

tfRefactoring your own code is, what I guess, something that you do frequently – at least I am. Maybe a better description of the process I went through would be rewriting, but let’s stick with refactoring. Either the routines get too complex, or there’s an extra parameter needed or there’s some new special case to be handled, never mind the reason, refactoring of your own code is what we all do and should do.

I will not go here into explaining various reasons (and solutions) why and how you would want to rewrite your own functions (maybe originally coded years ago). There are plenty of possible scenarios/solutions: extract some piece of code into a separate routine, optimize sections, replace records with objects (or the opposite), introduce new language constructs and so on.

A few days ago I’ve placed my hands over a Delphi application coded years ago. My task was to extend one function with some special processing. The actual function already had some 2000 (two thousand) lines of code. There were a couple of nested subroutines including more nested subroutines. There were some 20 (twenty) input parameters.

As you might imagine: a mess!

But, a task is a task and one has to finish what was started. After a few hours (read: days) I’ve successfully refactored the entire function (introduced function overloads, removed duplicated code, normal optimization stuff…)

However, and to be honest, my first reaction was “heck, I guess the fastest would be to rewrite the entire function in the following, much simpler manner (code below). After all, a boolean function would either return a false or a true value – only 2 possible outcomes of the 2000 lines of code!

And here’s what my first (virtual) solution was:

function Refactored(const someInputParameters : integer): boolean;
const
  returnValue : array [0..1] of boolean = (false, true);
begin
  result := returnValue[GetTickCount MOD 2];
end;

From the first look, the above implementation of a boolean function is as good as any. After all, it would return either true or false, there’s no 3rd option with booleans :)

You? Had a similar moment?


Viewing all articles
Browse latest Browse all 1725

Trending Articles