I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:
typedef std::map<std::string, std::map<std::string, int> > CSVData;
Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?
If this is for some one-off code: sure, use typedefs, why not?
But code rarely is. And the problem with reusable code (or code that will, potentially, at some future point be reused) is: there are 1000 different ways of using it wrongly. Don’t artificially add reasons 1001–1255.
Code should be easy to use, and hard to misuse. Among other things this means: have one obvious interface and forbid all operations that aren’t supported, meaningful, or that are somehow unnecessary. Providing a typedef fails in this regard: your CSV data type supports all kinds of irrelevant operations.
There are multiple other reasons against typedefs: for instance, this makes the interface easy to break when you need to change the underlying implementation of your data structure (change of requirements, performance issues …). Essentially, you cannot do that without breaking all uses of your typedef’d data structure.
But a properly designed, well encapsulated data structure can easily change its internal implementation without breaking consumer code, as long as the interface remains identical.
This is one of the most important concepts of large architectures: information hiding.
Furthermore, it is a logical error (albeit a small one): your typedef models a logical is-a relation. But this isn’t true: CSV data isn’t a map of maps. Rather, it can be implemented in terms of a map of maps. This is a fundamental difference.
That said, C++ does teach that object orientation isn’t needed for large object hierarchies: essentially the whole standard library (except for the IO stream library) isn’t object oriented: it’s algorithm oriented instead. But that doesn’t mean that you don’t have to write your own classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With