Skip to main content
Plus not minus
Source Link
Caridorc
  • 27.6k
  • 7
  • 54
  • 135

Self-documenting code

char h1 = { (e.hour / 10) + '0' }; // Extract the first digit and convert to char (if any, else 0)

As you considered the division by ten and the 0 too enigmatic you added a comment, this is much better than leaving the reader wondering so good job.

The even better option though is stating your intention in code:

char h1 = convert_to_char(first_digit(e.hour))

Where you can easily define:

char convert_to_char(int x) {
    return x -+ '0';
}

and

int first_digit(int x) {
    return x / 10;
}

Having to maintain / read code and comments is double the effort than only code.

Self-documenting code

char h1 = { (e.hour / 10) + '0' }; // Extract the first digit and convert to char (if any, else 0)

As you considered the division by ten and the 0 too enigmatic you added a comment, this is much better than leaving the reader wondering so good job.

The even better option though is stating your intention in code:

char h1 = convert_to_char(first_digit(e.hour))

Where you can easily define:

char convert_to_char(int x) {
    return x - '0';
}

and

int first_digit(int x) {
    return x / 10;
}

Having to maintain / read code and comments is double the effort than only code.

Self-documenting code

char h1 = { (e.hour / 10) + '0' }; // Extract the first digit and convert to char (if any, else 0)

As you considered the division by ten and the 0 too enigmatic you added a comment, this is much better than leaving the reader wondering so good job.

The even better option though is stating your intention in code:

char h1 = convert_to_char(first_digit(e.hour))

Where you can easily define:

char convert_to_char(int x) {
    return x + '0';
}

and

int first_digit(int x) {
    return x / 10;
}

Having to maintain / read code and comments is double the effort than only code.

Source Link
Caridorc
  • 27.6k
  • 7
  • 54
  • 135

Self-documenting code

char h1 = { (e.hour / 10) + '0' }; // Extract the first digit and convert to char (if any, else 0)

As you considered the division by ten and the 0 too enigmatic you added a comment, this is much better than leaving the reader wondering so good job.

The even better option though is stating your intention in code:

char h1 = convert_to_char(first_digit(e.hour))

Where you can easily define:

char convert_to_char(int x) {
    return x - '0';
}

and

int first_digit(int x) {
    return x / 10;
}

Having to maintain / read code and comments is double the effort than only code.