Jessica <je********@yahoo.com> wrote in message
news:76**************************@posting.google.c om...
Hi,
I have a question regarding the object-oriented issue. I understand
that a class is a type. I have an array class. Now say that I want
to implement an algorithm A that uses the array class. Does it make
sense to make a class for the algorithm such as
class MyAlg
{
private:
Array A1;
Array A2;
// more data members
public:
// my functions
};
Right now I have my algorithm as an interface to the Array class (i.e.
just a bunch of global functions).
If it's an interface to the Array class then it's not a bunch of global
functions. Someone else recently called member variables 'global'. Is there
a teacher out there teaching the wrong meaning of 'global'? Global functions
are those that are not inside a class and can be called from anywhere.
The problem is that it gets pretty
messy and unorganized since there are so many parameters associated
with the algorithm. Since I now added a GUI for my algorithm, I
thought that maybe if I wrap my algorithm in a class, the code will be
cleaner. So in short, my current design is 3-tiered:
I hope this means that your GUI code is completely separate from your
algorithm code.
GUI -> My algorithm as a set of global functions -> Array class
implementation
I want to make it into a 2-tier design:
GUI -> My algorithm as a class (with Array contained in this
class)
Can someone please tell me if this is the right way to do it?
It's hard to tell without more details. If your algorithm has many inputs,
and some of these are the same while others vary, then it's a good candidate
for a class. Otherwise a single function (a _real_ global function) might be
the most appropriate, regardless of the number of inputs. A class would have
the advantage for some algorithms of being able to do optimizations, such as
caching certain intermediate values. For instance, a FastFourierTransform
object could pre-calculate an array of sines and cosines, or whatever it
needs, for a given number of points, which can then be used until the number
of points changes.
If possible, it's best not to limit an algorithm to using something like
Array objects. If your array is a simple Array of doubles, for example, then
it would be better for your algorithm to take pointers to doubles, e.g.,
void someAlgorithm(const double *begin, const double *end, /* other
parameters */);
Then you can use any kind of array of doubles, e.g.,
void f()
{
std::vector<double> v;
// fill vector with numbers
someAlgorithm(v.begin(), v.end(), /* other parameters */);
}
Try to make your algorithm is flexible as possible, rather than limiting its
use to such specific types as Array.
I agree that your algorithm should not be in the Array class. Again, that
would be a very-specific, very limiting design. Arrays should just be
containers.
Do you have a good reason for using your own Array class rather than a
container supplied by the standard library?
DW