Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for a class with many members

Tags:

c++

parameters

Any opinions on best way to organize members of a class (esp. when there are many) in C++. In particular, a class has lots of user parameters, e.g. a class that optimizes some function and has number of parameters such as # of iterations, size of optimization step, specific method to use, optimization function weights etc etc. I've tried several general approaches and seem to always find something non-ideal with it. Just curious others experiences.

  1. struct within the class
  2. struct outside the class
  3. public member variables
  4. private member variables with Set() & Get() functions

To be more concrete, the code I'm working on tracks objects in a sequence of images. So one important aspect is that it needs to preserve state between frames (why I didn't just make a bunch of functions). Significant member functions include initTrack(), trackFromLastFrame(), isTrackValid(). And there are a bunch of user parameters (e.g. how many points to track per object tracked, how much a point can move between frames, tracking method used etc etc)

like image 679
Bryan Avatar asked Oct 25 '10 20:10

Bryan


2 Answers

If your class is BIG, then your class is BAD. A class should respect the Single Responsibility Principle , i.e. : A class should do only one thing, but should do it well. (Well "only one" thing is extreme, but it should have only one role, and it has to be implemented clearly).

Then you create classes that you enrich by composition with those single-role little classes, each one having a clear and simple role.

BIG functions and BIG classes are nest for bugs, and misunderstanding, and unwanted side effects, (especially during maintainance), because NO MAN can learn in minutes 700 lines of code.

So the policy for BIG classes is: Refactor, Composition with little classes targetting only at what they have do.

like image 198
Stephane Rolland Avatar answered Sep 21 '22 16:09

Stephane Rolland


if i had to choose one of the four solutions you listed: private class within a class.

in reality: you probably have duplicate code which should be reused, and your class should be reorganized into smaller, more logical and reusable pieces. as GMan said: refactor your code

like image 42
justin Avatar answered Sep 18 '22 16:09

justin