I have a question related to how to design a class using object-orienting languages such as c++. In many circumstances variables can either be assigned to class members or function arguments. I give the following examples to make my point clear:
class MyClass
{
public:
int variable1;
int variable2:
MyClass (int vr1, int vr2)
{
variable1 = vr1;
variable2 = vr2;
}
bool perform_one_task()
{
// do something
return true;
}
}
When we want to use this class, we can use the following codes:
int a,b;
MyClass mine(a,b);
mine.perform_one_task();
It is also possible to design a class without variable1 and variable2.
class MyClass
{
public:
bool perform_one_task(int variabl1, int variable2)
{
// do something
return true;
}
}
In this class variable1 and variable2 are not members of the class but become the arguments of the function. My question is in which condition the first design strategy is preferable and in which condition the second design pattern is better. The given example only assume the structure ofvariable1 and variable2 are small, but what if they are big, for example, variable1 may be an large array of data.
Class members are class members. These are properties of an instance of class object or static values used by whole class - so values closely related to the class.
You don't store in your class values that don't model your class, unless you need them (and then they do model your class actually). This is unnecessary and waste of resources. Always avoid unnecessary variables. So basically:
class MyClass{
public:
bool perform_one_task(int onlyMethodArg1, int onlyMethodArg2){
// do something
return true;
// onlyMethodArgs are gone since nobody really needs them, we are interested
// only in result of calculation
}
void saveProperties(int prop1, prop2){
property1=prop1;
property2=prop2;
}
private:
int property1;
int property2;
};
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