Is this an acceptable style?

From feedback I have received in the past, I have been trying to move away from having 'magic' values in my code. I tried doing this too with expressions as well. Below is an example function where I replaced return values by const variables, and expressions by const variables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int isContained( uint aval )const
{
	const int NOT_CONTAINED = 0; 
	int lreturn = NOT_CONTAINED;

	assert( this->isValid() );

	const int NORMAL_CONTAINED = 1;
	const int LEFT_EDGE = 2;
	const int RIGHT_EDGE = 3;
	const int ENTIRELY_CONTAINED = 4;
	const bool TOUCHES_LEFT = (aval == this->x);
	const bool TOUCHES_RIGHT = (aval == this->y);
	const bool BETWEEN = this->x < aval && aval < this->y;

	if( BETWEEN ){
		lreturn = NORMAL_CONTAINED;			
	}else if( TOUCHES_LEFT && !TOUCHES_RIGHT ){					//intersect head
		lreturn = LEFT_EDGE;
	}else if( TOUCHES_RIGHT && !TOUCHES_LEFT ){					//intersect tail
		lreturn = RIGHT_EDGE;
	}else if( TOUCHES_LEFT && TOUCHES_RIGHT ){					//identity
		lreturn = ENTIRELY_CONTAINED;
	}

	assert( lreturn >= 0 );
	return lreturn;
}


Is this acceptable or am I going too far with this? I find that this particular trial example came out to be much easier to read than before. (Typically I define global or namespace constants with the same capitalization scheme shown for these const variables, so I may change naming conventions to avoid collisions with the namespace.)
Lines 16~27 are "easier to read", but all the above seems a bit messy to me. But I'm guessing those declarations generally won't be inside the function?
Consider using an enum to specify the type of containment.
It makes the code more typesafe, and also passes on the benefits to the users of the class.

Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct the_class
{
    // ...
    
    enum contain_type { NOT_CONTAINED = 0, NORMAL_CONTAINED = 1, LEFT_EDGE = 2,
                        RIGHT_EDGE = 3, ENTIRELY_CONTAINED = 4 } ;

    contain_type contains( int v ) const 
    {
        // ...
    }
    
    // ...                      
};

And then:
1
2
3
4
if( an_object.contains(value) == the_class::ENTIRELY_CONTAINED ) 
{ 
    // ... 
}


Last edited on
Topic archived. No new replies allowed.