Tuesday, 18 March 2014

Functions and classes

Maybe I should write a book about C++ because I'm always talking about programming stuff. But let's continue with the simplifying theme. One of the things that happen when you move from C to C++ (classes) is that functions often become simpler, but their amount increases. It's strongly related to the design of classes: how they return and get information from elsewhere.

In the best situation most actions would happen inside the class and then some simple return value or state can be retrieved from the class. What happens when you move from C's functional paradigm to object-oriented style is that you get maybe too interested about simple functions, especially aiming to decrease the amount of parameters to functions.

It's maybe ironic, but more complex functions with reduced parameter data can actually increase the modular OOP design of classes. I think it's good to look at the size and complexity of the public interface and try to create simpler way to handle the input/output of the class. This is even true for type classes that contain some kind of basic data and calculations based on it. You can add more complexity (in form of higher level functions that handle the data in that class) in those simple classes to reduce the complexity from the calling routines.

With functions one of the thing often happens to me is that I write a function just in case it needs to be used more than once. Then I notice it's called only once and in those cases (when it's clearly a part of the main structure of the program) the function's source code can be fused into the calling routine, removing one function. Less functions is good when dealing with a large scale project, because every function counts and contributes to the overall complexity.

No comments: