Wednesday 1 October 2014

Procedural degeneration

I've degenerated back to procedural programming! Well, not entirely, but while I was reading stuff about functional programming it made me rethink some things in C++ and OOP. Classes are ok, but sometimes there are clumsy situations where you simply create a class without member variables (data) and use it as "empty" instance, then access functions to do something. It took some time for me to realize that these strange functions are actually... functions. Or "procedures" as in procedural paradigm.

Of course "pure" functions have been always lurking in C++ in form of the standard library (functions like printf etc.). But you can also write your own functions and use them in classes without breaking OOP principles. Functions that are good candidates are generic and algorithmic, they take in simple parameters and return simple values. It's possible to go further than that, but then it starts to be too much like traditional C with all problems it has.

In C++ context it's great to reduce some of burden from classes and also avoid copying source code in member functions when you could use external pure function in all similar places. If those functions are generic enough they can also be reused in other projects really easily, because they don't have any dependencies to the current project. So I've started to create a small function library for Kaduria (rather than creating any game content..) and already removed one of those clumsy empty classes. C++ has the neat feature of closing stuff in a namespace. I've named it "Function" so functions are called as Function::do_something(); which is not only clearly showing that the function library is used, but also protects from name clashes.

I think the function library will stay rather small, because OOP doesn't easily become functional, because member functions work closely with class data and if you try to make it generic function style it probably wont look nice.

No comments:

Post a Comment