find-maint: Factor Out Repeated Code
4.2 Factor Out Repeated Code
============================
Repeated code imposes a greater maintenance burden and increases the
exposure to bugs. For example, if you discover that something you want
to implement has some similarity with an existing piece of code, don't
cut and paste it. Instead, factor the code out. The risk of cutting
and pasting the code, particularly if you do this several times, is that
you end up with several copies of the same code.
If the original code had a bug, you now have N places where this
needs to be fixed. It's all to easy to miss some out when trying to fix
the bug. Equally, it's quite possible that when pasting the code into
some function, the pasted code was not quite adapted correctly to its
new environment. To pick a contrived example, perhaps it modifies a
global variable which it (that [original] code) shouldn't be touching in
its new home. Worse, perhaps it makes some unstated assumption about
the nature of the input arguments which is in fact not true for the
context of the now duplicated code.
A good example of the use of refactoring in findutils is the
'collect_arg' function in 'find/parser.c'. A less clear-cut but larger
example is the factoring out of code which would otherwise have been
duplicated between 'find/oldfind.c' and 'find/ftsfind.c'.
The findutils test suite is comprehensive enough that refactoring
code should not generally be a daunting prospect from a testing point of
view. Nevertheless there are some areas which are only lightly-tested:
1. Tests on the ages of files
2. Code which deals with the values returned by operating system calls
(for example handling of ENOENT)
3. Code dealing with OS limits (for example, limits on path length or
exec arguments)
4. Code relating to features not all systems have (for example Solaris
Doors)
Please exercise caution when working in those areas.