C++ – Structuring Procedural vs OO code

cproceduralproject-structure

I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects… so when I create a class I am thinking of:

  • What is this object representing?
  • What can this object do?
  • What do others need to be able to do to it?
  • What do I expose, what do I hide?
  • Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in… but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!

Best Answer

A lot of procedural code is very OOP-like. Basically, instead of object.function(params), you do function(object, params). You can group your files accordingly.

However, what a lot of long-time OOP programmers don't realize is how limiting it is that a function must belong to one and only one class, and that all such functions must be grouped into one file accordingly. Procedural-style allows for many other kinds of groupings that often fit better under certain circumstances:

  • Combinations of two objects, like all functions dealing with both engines and transmissions.
  • Collections of objects, like all functions dealing with lists of cars.
  • All implementations of an interface. For example, the implementations of steer() for different kinds of vehicles could all be grouped into one file.
  • Functions that convert from one kind of data structure to another. For example, functions that take a collection of parts and return a car.

Basically, all those times you couldn't really figure out which class is the best fit for something, in procedural that's not really an issue. Don't get me wrong, the way OOP groups functions is successful because it's a very reasonable default. That doesn't make it the best grouping under all circumstances, though.

Related Topic