The Importantance of Setting Boundaries on Variable Values


Every variable in a programming language belongs to a data type and has a size and range.

The endpoints of these ranges are known as the “boundaries” of the variables.

When a value is being assigned to a variable it is important that the value falls within the defined range.
Else the variable can behave erratically by causing the program to crash, taking of a random value, or continuing to use a predefined value – all of which causes a failure in execution logic and end up making the software “buggy” and unsafe.

The following are bounds for common data types in Visual C++ :

Bounds can be enforced in code in the following ways

  • Input validation
    Input needs to be validated strictly and only when found within the range, be assigned to variables.
  • Index checking
    The index value of an array variable is checked against the bounds of the array at all times, before being invoked.
    An array A(16) ranges from A[0] to A[15], and before invoking A[i], checks must be done that i >= 0 and i <=15 
  • Unit testing
    Every snippet of code should through rigorous unit test cases which tests for boundary values, random range values, and values from other character sets.
    This will ensure robust code.
  • Code Review
    Having a fresh set of eyes reviewing the code can often unearth oversights.
  • Anticipating and handling exceptions and failing safely
    All code should be enclosed within exception handlers.
    If a variable at run-time is pushed with a value beyond its acceptable range, it should exit gracefully without causing erratic errors or worse, crashing completely.
  • Using a high-level language suite with in-built bound checks
    Raw bones C doesn’t have bound-checks and relies on the skills of the programmers to get it right.
    Higher-level language suites like C# .NET come with “intellisense” and bound-check enabled compilers.