Mixing UI with math

Why mathematical models should not contain any user interface code

The last issue I’m going to deal with in this series is the mixing of UI code with calculating code. It goes like this:

while i < total:
    update_progress_bar(i, total)
    i += 1

Our math code should not contain any UI libraries. It should be possible to just call a function with some input and get some output. In the example above, our math code updates a progress bar. Other cases are showing a message, or asking for input after having calculated intermediate results.

There are always ways to do what you want without such mixing. In the case of the progress bar, you can pass a callback function to the function that makes the calculations. I’m not going into details because it depends on programming language (but feel free to ask me if you have this problem).

One problem when we mix UI with math is that it makes automated tests difficult—typically automated tests are run without UI. Another problem is that, maybe not tomorrow but in a few years, you will want to create another UI. Maybe make your function a DLL and call it from Excel; or maybe put it on the web.