Conflict Resolution
This piece of code contain conflicting variable and function names. Refactor the code to avoid naming conflicts without renaming variables or functions. Ensure that the code runs correctly after resolving the conflicts.
#include <iostream>
// Variable declarations
double area = 0;
double perimeter = 0;
// Function declarations
double calculateArea(double length, double width) {
return length * width;
}
double calculatePerimeter(double length, double width) {
return 2 * (length + width);
}
double calculateArea(double radius) { // Conflicting function name
return 3.14159 * radius * radius;
}
double calculatePerimeter(double radius) { // Conflicting function name
return 2 * 3.14159 * radius;
}
int main() {
// Rectangle calculations
double length = 5.0, width = 3.0;
area = calculateArea(length, width);
perimeter = calculatePerimeter(length, width);
std::cout << "Rectangle Area: " << area << std::endl;
std::cout << "Rectangle Perimeter: " << perimeter << std::endl;
// Circle calculations
double radius = 4.0;
area = calculateArea(radius);
perimeter = calculatePerimeter(radius);
std::cout << "Circle Area: " << area << std::endl;
std::cout << "Circle Perimeter: " << perimeter << std::endl;
return 0;
}
Hint
Use namespaces to resolve the naming conflicts.
Answer
Here is an example of how the code could be refactored using namespaces to resolve the naming conflicts:
- Seperated the functions for rectangle and circle calculations into separate namespaces.
- Added the PI constant to the Circle namespace.
#include <iostream>
// Namespace for rectangle calculations
namespace Rectangle {
double calculateArea(double length, double width) {
return length * width;
}
double calculatePerimeter(double length, double width) {
return 2 * (length + width);
}
}
// Namespace for circle calculations
namespace Circle {
const double PI = 3.14159;
double calculateArea(double radius) {
return PI * radius * radius;
}
double calculatePerimeter(double radius) {
return 2 * PI * radius;
}
}
int main() {
// Rectangle calculations
double length = 5.0, width = 3.0;
double rectangleArea = Rectangle::calculateArea(length, width);
double rectanglePerimeter = Rectangle::calculatePerimeter(length, width);
std::cout << "Rectangle Area: " << rectangleArea << std::endl;
std::cout << "Rectangle Perimeter: " << rectanglePerimeter << std::endl;
// Circle calculations
double radius = 4.0;
double circleArea = Circle::calculateArea(radius);
double circlePerimeter = Circle::calculatePerimeter(radius);
std::cout << "Circle Area: " << circleArea << std::endl;
std::cout << "Circle Perimeter: " << circlePerimeter << std::endl;
return 0;
}