"Gaijinco" <> wrote in message
news: oups.com...
> I found one of that problems all of us have solve when they begin
> programming: given 3 numbers print the greater and the lesser one of
> the set.
>
> I was trying to remember the if-then-else structure when something hit
> me and I wrote:
>
> // Function returns the greater or lesser numbers of two given numbers,
>
> // specified by a flag: 1 for greater (default), 0 for lesser
>
> int greater_lesser(int a, int b, bool flag=1){
>
> int toBeReturned;
>
> if(flag)
> a > b ? toBeReturned = a : toBeReturned = b;
> else
> a > b ? toBeReturned = b : toBeReturned = a;
>
> return toBeReturned;
> }
>
> int main(){
>
> int x, y, z;
> cin >> x >> y >> z;
> cout << "Greater : " << greater_lesser(greater_lesser(x,y),z) << endl
> << "Lesser : " << greater_lesser(greater_lesser(x,y,0),z,0) << endl;
>
> return 0;
> }
>
> The code works all right, but it seems odd, as if it can be improved...
>
> Any thoughts? Thanks!
>
No, this is horrible!
Flags which control the behavior of a function in such a radical way are
often
confusing and make code difficult to understand, especially something as
simple
as this. Perhaps in a more complex example where a basic algorithm can be
adapted
to perform different variations, flags might be more appropriate, but I
would generally
make that function private and provide simple wrappers of the basic function
to be more
meaningful to a user.
Flags have a habit of multiplying, so we often see two or three flag
parameters in code which
affect the behavior of the function making code harder to understand.
Surely the following is easier to understand ?
#include <iostream>
int lesser( int a, int b)
{
return a < b ? a : b;
}
int greater( int a, int b)
{
return a > b ? a : b;
}
int main()
{
int x, y, z;
std::cin >> x >> y >> z;
std::cout << "Greater : " << greater ( greater (x,y),z) << "\n"
<< "Lesser : " << lesser( lesser(x,y),z) << "\n";
return 0;
}
|