Skip to content

Instantly share code, notes, and snippets.

@omundy
Created October 22, 2024 12:07
Show Gist options
  • Save omundy/599d461c6456098692df436b6e692559 to your computer and use it in GitHub Desktop.
Save omundy/599d461c6456098692df436b6e692559 to your computer and use it in GitHub Desktop.

Self-documenting code

Example from https://stackoverflow.com/a/209089/441878

Typical code

double a, b, c; a=9.81; b=5; c= .5*a*(b^2);

Self-documenting code shows what is being done

double gravity = 9.81;
double seconds = 5;
double displacement = (1 / 2) * gravity * (seconds ^ 2);

Documented code, which better explains why it is being done

// compute displacement with Newton's equation x = vₒt + ½at²
double gravity = 9.81;
double seconds = 5;
double displacement = (1 / 2) * gravity * (seconds ^ 2);

The final version using self-documented function with zero comments needed

double computeDisplacement(float timeInSeconds) {
    double gravity = 9.81;
    double displacement = (1 / 2) * gravity * (seconds ^ 2);
    return displacement;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment