Re: Is this class design correct? A better way?
* nw:
I was wondering if someone would be able to give me some comments on
the following class structure, it feels to me as if there must be a
better way, but I'm unsure what it is, perhaps I should be using
multiple inheritance?
You should be using /inheritance/ and-or /templating/ instead of a type
switch.
For inheritance, you can represent the integration algorithm directly as
a derived class override of a Body virtual member function, or you can
represent it as an object passed to the Body constructor(s).
[snip]
Compilable example code implementing this design follows. Apologies if
I've been overly verbose.
Any help greatly appreciated!
OK...
#include <iostream>
Formally you also need <ostream>.
using namespace std;
class Body {
public:
double x, y, z;
double a;
Public member variables = ungood.
Name 'a' = ungood.
static const int BODY_INTEGRATE_EULER=1;
static const int BODY_INTEGRATE_VERLET=2;
static const int BODY_INTEGRATE_LEAPFROG=3;
All uppercase for non-macros = ungood.
int integration_type;
'int' to represent something with limited number of possible values =
ungood.
Representing type as value = in general, and in this case, ungood.
virtual bool calculate_force(Body &b) = 0;
Body() {
integration_type=BODY_INTEGRATE_EULER;
}
See the FAQ item titled 'Should my constructors use "initialization
lists" or "assignment"?', currently available at <url:
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6>.
bool integrate() {
if(integration_type == BODY_INTEGRATE_EULER) {
// .. do euler
cout << "Euler integration" << endl;
return true;
} else
if(integration_type == BODY_INTEGRATE_VERLET) {
// .. do verlet
cout << "Verlet integration" << endl;
return true;
} else
if(integration_type == BODY_INTEGRATE_LEAPFROG) {
// .. do leapfrog
cout << "Leapfrog integration" << endl;
return true;
}
}
This type selection is what you need to avoid.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?