This is part of a Particle Swarm Optimization algorithm, a snippet of a Particle class implementation.
/**
* Particle class constructor
* @param p - the position of the particle
* @param v - the velocity of the particle
*/
Particle::Particle(std::array<double, 30> p, std::array<double, 30> v) {
bestFitness = fitness = rastriginEvaluation(p);
bestPosition = position = p;
velocity = v;
}
// setter methods
void Particle::setFitness(double f) { fitness = f; }
void Particle::setBestFitness(double f) { bestFitness = f; }
void Particle::setPosition(std::array<double, 30> p) { position = p; }
void Particle::setBestPosition(std::array<double, 30> p) { bestPosition = p; }
void Particle::setVelocity(std::array<double, 30> v) { velocity = v; }
Notice the constructor directly accesses member attributes yet I have setter methods. Should I be using the setter methods to initialize attributes? Either is fine, I wonder what is more proper.
For example, instead of:
bestFitness = fitness = rastriginEvaluation(p);
bestPosition = position = p;
velocity = v;
I could do:
setFitness(rastriginEvaluation(p));
setBestFitness(rastriginEvaluation(p));
setPosition(p);
setBestPosition(p);
setVelocity(v);
For this example, rastriginEvaluation()
is called twice, when the original code only calls it once. It is therefore slower but what is better practice?
I could also wonder about getter methods in the mix:
setFitness(rastriginEvaluation(p));
setBestFitness(getFitness());
setPosition(p);
setBestPosition(getPosition();
setVelocity(v);
If it makes a difference, all attributes are private.