Insight 12.4.1.
Good code is self-documenting. It should be clear what the code is doing without needing extensive comments. The abstractions produced by well designed functions help make code more understandable.
calculateTriangleArea
provides an opportunity to write a new function that addresses both principles. The start of main has this ugly chunk of code:
double side1, side2, side3;
cout << "Enter the length of the first side of the triangle: ";
cin >> side1;
cout << side1 << endl; // echo the input
cout << "Enter the length of the second side of the triangle: ";
cin >> side2;
cout << side2 << endl; // echo the input
cout << "Enter the length of the third side of the triangle: ";
cin >> side3;
cout << side3 << endl; // echo the input
if (side1 <=0) ...
.
double getDoubleInput
that will perform the three steps and return the side length.
prompt
a parameter. That way, we can customize the message for each side of the triangle. We now have a function double getDoubleInput(const string& prompt)
:
#include <iostream>
#include <cmath>
#include <format>
#include <string>
using namespace std;
double getDoubleInput(const string& prompt) {
cout << prompt;
double value;
cin >> value;
cout << value << endl; // echo the input
return value;
}
double calculateTriangleArea(double side1, double side2, double side3) {
double s = (side1 + side2 + side3) / 2; // Semi-perimeter
double area = sqrt(s * (s - side1) * (s - side2) * (s - side3)); // Heron's formula
return area;
}
int main() {
double side1 = getDoubleInput("Enter the length of the first side of the triangle: ");
double side2 = getDoubleInput("Enter the length of the second side of the triangle: ");
double side3 = getDoubleInput("Enter the length of the third side of the triangle: ");
double area = calculateTriangleArea(side1, side2, side3);
cout << format("The area of the triangle to one decimal is: {:.1f}", area) << endl;
}
getDoubleInput
function and all three inputs will then take advantage of the new code.
main
function is doing. After scanning it, a programmer hopefully thinks something like “oh, that whole block just gets the three sides” and then doesn’t worry about the details of how that happens (unless that is the part of the code they are trying to work on!).
main
function. We can see that it is getting the three sides of the triangle without having to worry about the details of how that is done. It might be worth writing the getDoubleInput
function even if we only use it once (and thus get no code reuse benefit) because it still makes the code clearer.
double shippingCost1 = 0;
if (order1Cost < 100) {
shippingCost1 = order1Weight * 3.50;
}
if (order1IsExpressHandling) {
shippingCost1 += 20;
}
double shippingCost2 = 0;
if (order2Cost < 100) {
shippingCost2 = order2Weight * 3.50;
}
if (order2IsExpressHandling) {
shippingCost2 += 20;
}
shippingCost1
.