help about best way

is it only okay for setter function definition to be more than 1 line?

1
2
3
4
5
void Class::setter(c obj)
{
    if ( obj.A > 1 && obj.A < 10 )
       myData = obj;
}
Last edited on
Of course. Your setter can be as simple or as complex as you wish.


i see, i was thinking about which one is the best way

first one:

1
2
3
4
5
6
7
8
9
10
11
int main()
{ 
    Class myObj;
    c obj;
    if ( obj.A > 1 && obj.A < 10 )
         myObj.setter(obj);
}
void Class::setter(c obj)
{
       myData = obj;
}


or this

1
2
3
4
5
6
7
8
9
10
11
int main()
{ 
    Class myObj;
    c obj;
    myObj.setter(obj);
}
void Class::setter(c obj)
{
    if ( obj.A > 1 && obj.A < 10 )
       myData = obj;
}
Last edited on
I'm not fond of either one. Both require that members of class c are public.

I would do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{   Class myObj;
    c obj;
    myObj.setter(obj);
}

//  Visibility of A should be limited to class c
bool c::is_valid () const
{   return A > 1 && A < 10;
}

//  Class should not access members of c
//  It only needs to now if obj is valid or not.
void Class::setter(c obj)
{   if (obj.is_valid())
       myData = obj;
}


Last edited on
i was thinking about which one is the best way

First what happens, in either snippet, if the if() statement isn't triggered?

Both snippets are basically doing the same thing. The difference is who is responsible for data validation. If you go with the first snippet, the user of the class will be responsible and will always need to insure a valid value is being used. In the second snippet the class is responsible of checking that a valid value is being used, the user of the class doesn't need to worry about validation.

Which is best? That really depends on how the class is being used. If the limits will always be the same then perhaps it would be better to let the class deal with the validation, but if the values can change based on something outside the control to the class then perhaps it would be better to use external validation. The decision should be based on the specifications of the class and on the specifications of the program.

Topic archived. No new replies allowed.