The Cybiko video converter Avi2Cvc and image converter Bmp2Cvi have a lot in common:
They both take a 16/24bit colour image and reduce it to a 2bit grayscale image, this may be by ordered dithering or error diffusion.
They both make a choice from the same list methods on how to best compress this 2bit image.
Before using D's modules, both programs had seperate folders each with their own, almost identical, versions of the above functions. This breaks the rule of 'Don't Repeat Yourself' and means duplicating effort improving and bugfixing each of the programs.
Both of these program's had been remade using the D Programming Language, that gave the option of using modules.
The solution to the code duplication issue was to put the compression functions in one module (cv1.d) and the colour reduction functions in another module (utils.d). Each did require a little tweaking to work with both programs but it was very minor.
Modules are made simply by adding module and the name at the top of the source code e.g. module cv1; and then included in the main program with an import statement e.g. import cv1;
Both Avi2Cvc and Bmp2Cvi have import cv1,utils; at the start to tell the program where the relevant functions are located.
Probably the best bit is how to compile each of the programs, with all four files (avi2cvc.d, bmp2cvi.d, cv1.d, utils.d) in the same folder, it is simply a case of doing the following:
dmd -i avi2cvc.d
which produces 'avi2cvc.exe' and the following makes 'bmp2cvi.exe':
dmd -i bmp2cvi.d
With the '-i', the compiler will include the imported the needed modules itself, we do not have to specify the extra files, the compiler will do it for us!
Modules are a great way to reduce code duplication and simplify compiling of large programs.
Updated
20/01/2024