HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Keeping integer addition within bounds

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
keepingadditionwithinboundsinteger

Problem

I have to read a int8_t from a buffer, read a uint8_t from the camera's current settings, add them together, keep new value within the bounds 0 to 100 and write the new value to the camera's current settings. This seems quite easy to me, and yet here I have a rather large bit of code.

The brace style is company-mandated.

Is there a way to remove some of the complexity from this code?

Ranges:

plusZoomPercentage: full range of int8_t.

currentZoomPercentage and getZoomPercentage(): 0 to 100, 0 and 100 included.

newZoomPercentage: To be between 0 and 100, 0 and 100 included.

Header file:

/*Zooms to the provided percentage of maximum zoom level.*/
void zoomToPercentage(uint8_t percentage);

/*Retrieves the current targeted percentage of maximum zoom level (if the camera is currently at 50% zoom, but is zooming towards 60%, return 60.)*/
uint8_t getZoomPercentage();


Calling implementation:

int8_t plusZoomPercentage;
if (!unabto_query_read_int8(readBuffer, &plusZoomPercentage))
{
    return AER_REQ_TOO_SMALL;
}
if (plusZoomPercentage == 0) 
{ 
    return AER_REQ_RESPONSE_READY;
}
uint8_t currentZoomPercentage = getZoomPercentage();
uint8_t newZoomPercentage = currentZoomPercentage + plusZoomPercentage;
if (plusZoomPercentage > 0)
{
    /*Check for overflow or otherwise going out of bounds*/
    if (newZoomPercentage > 100 || newZoomPercentage  currentZoomPercentage)
    {
        zoomToPercentage(0);
    }
    else
    {
        zoomToPercentage(newZoomPercentage);
    }
}
return AER_REQ_RESPONSE_READY;

Solution

It will be a bit shorter and simpler without the duplicated else blocks:

if (plusZoomPercentage > 0)
{
    /*Check for overflow or otherwise going out of bounds*/
    if (newZoomPercentage > 100 || newZoomPercentage  currentZoomPercentage)
{
    newZoomPercentage = 0;
}
zoomToPercentage(newZoomPercentage);
return AER_REQ_RESPONSE_READY;

Code Snippets

if (plusZoomPercentage > 0)
{
    /*Check for overflow or otherwise going out of bounds*/
    if (newZoomPercentage > 100 || newZoomPercentage < currentZoomPercentage)
    {
        newZoomPercentage = 100;
    }
}
else if (newZoomPercentage > currentZoomPercentage)
{
    newZoomPercentage = 0;
}
zoomToPercentage(newZoomPercentage);
return AER_REQ_RESPONSE_READY;

Context

StackExchange Code Review Q#83377, answer score: 6

Revisions (0)

No revisions yet.