Friday, June 19, 2020

Letters to a novice programmer

I decided to move software related posts to this blog. See my latest letter. Recently I saw C++ code similar to the following:
myAlgo.setInputs(inputStruct);
myAlgo.calculate();
myAlgo.getOutputs(outputStruct);
The correct way is to refactor calculate() method as follows:
outputStruct out = calculate(inputStruct)
Using this version would save the user of myAlgo from a couple of lines, he would not face the risk of forgetting to set inputs. In the previous version, if you forget to call setInputs(), the compiler will happily build your code and you will waste time finding the bug at run time. In the new version, if you forget to pass inputs to calculate(), it won't build and you will instantly see the bug.

Whenever you have multiple public initialization functions, try to combine them into a constructor. Your design should be such that when your code builds successfully, you should be confident that it has no initialization or finalizations related bugs. Let the compiler help you.

Tuesday, June 16, 2020

From Workspace uses first element as time

If you create a Simulink model with a From Workspace block and use it to get a vector, you will be surprised to see that the first element is missing:


The reason is that From Workspace treats the first element of a vector as time and the rest as data.