Function Refactoring
Here is a short program that calculates the average score of students. Refactor the code to be more appropriate for a larger program. You might consider improving variable namings, grouping student scores into an array or vector, and creating functions for operations that would be useful for a larger program to leverage.
#include <iostream>
int main() {
int s1 = 85, s2 = 90, s3 = 78;
int total = s1 + s2 + s3;
double avg = total / 3.0;
std::cout << "Total score: " << total << std::endl;
std::cout << "Average score: " << avg << std::endl;
return 0;
}
Answer
Here is an example of how the code could be refactored:
#include <iostream>
#include <vector>
// Function to calculate total score
int calculateTotal(const std::vector<int>& scores) {
int total = 0;
for(int score : scores) {
total += score;
}
return total;
}
// Function to calculate average score
double calculateAverage(int total, int numberOfScores) {
return static_cast<double>(total) / numberOfScores;
}
int main() {
// Scores of students
std::vector<int> scores = {85, 90, 78};
// Calculate total score
int totalScore = calculateTotal(scores);
std::cout << "Total score: " << totalScore << std::endl;
// Calculate average score
double averageScore = calculateAverage(totalScore, scores.size());
std::cout << "Average score: " << averageScore << std::endl;
return 0;
}
Key Improvements:
Encapsulation in Functions: Created separate functions for calculating the total score (calculateTotal) and the average score (calculateAverage).
Use of Vectors: Utilized a vector to store scores, making it easier to handle a variable number of scores.
Improved Variable Names: Used descriptive variable names (scores, totalScore, averageScore).
Static Cast: Used static_cast<double> for type conversion to ensure accurate division.
This version is more modular, making it easier to maintain and extend. Each function has a single responsibility, adhering to the single responsibility principle.