I know that it's possible in principle to turn even procedural languages such as C or MATLAB into object-oriented ones. This question has been fairly well discussed here and here.
What I found missing from these discussions and the references therein was an exposition on whether one should apply such principles. Is there anything concrete to be gained from doing so? It's clearly possible, but is it advisable to do so? Are there any examples among open-source projects where this practice led to clear advantages?
CLARIFICATION
Perhaps an example is in order.
I've inherited some MATLAB code that implements some machine-learning algorithm. There's basically a single function building_model
that, depending on a flag being passed, will either train a model or use it to predict a future value:
building_model('train', ...) % ... stands for the data with which the model is trained
and
value = building_model('predict')
The model itself is implemented with MATLAB persistent variables inside building_model
.
I've torn apart building_model
into two functions, one for training and one for predicting. The model that used to be implemented as persistent variables is now externalized, so to speak:
model = new_model()
model = model_train(model, ...)
prediction = model_predict(model)
This is, roughly speaking, as far as I could manage emulating some features of OOP in MATLAB. My building model module now acts pretty much like a class, with a constructor and two methods model_train
and model_predict
. I've achieved some degree of encapsulation (though nothing prevents the caller from fiddling with the internals of model
), and polymorphism could in principle also be accommodated. As an extra bonus, I get Command/Query separation almost for free since model_predict
doesn't return model
, and thus may not alter model
.
(Astute readers will point out that MATLAB already has an object-oriented system. For various reasons, including performance and compatibility with older versions, I cannot use it.)
I could imagine a similar mechanism in C where you would design some data structure and write functions whose first argument would be an instance of that data structure.
What I'd like to know is, how far can I push this way of programming? Is this a commonly accepted pattern (there, I've said the word)? Are there any performance issues I should watch out for?