March 26, 2023

I see a lot of programmers repeating various sections of code several times in their programs.
This practice reduces readability and thus increases your chances for errors. It also means refactoring your code later is harder. Code should be short, concise and highly readable.

If you are going to do the same operation more than once or maybe twice, you should put it into a procedure or function or method.

Some will point out that calling a function/procedure/method introduces a slight delay, but in reality, the difference is usually negligible – only making a noticeable difference in practice when being called multiple tens of thousands of times in a loop.

Also, when you put repeated sections into functions/procedures/methods, you are more likely to optimize that code and debug it better. And when you do have to change it, you can change it once rather than in 100 places.

The rule of thumb I recommend is that any function you write should not normally be more than a screen-full of lines of code. If you cannot see it all, how can you possibly understand it?

I was tasked with fixing someone’s broken program a while back and ripped out about 90% of the code, replacing bewildering expanse of code with just a few small well written functions. That removed the bugs and made it much more supportable in the long run too.

Consider making a new class if you need more than one of some complex graphics. For example, suppose you are making multiple TBasicPanel’s, each with a header text and a grid inside. Don’t repeat yourself, define a class descending from TBasicPanel, adding TLabel and TGrid inside, then on each invocation you only need to give it a caption for TLabel and a TDataset for TGrid. You can create the TBasicPanel descendant programmatically, or by making a new form in the IDE and adding that new subform into your existing form.