C语言代码重构咨询:能否合并重复分支优化代码结构?
Absolutely right to flag those repeated pidLine(speed) calls—your gut feeling that this can be cleaner is totally correct. Let's walk through how to streamline this code, cut down on duplication, and make it easier to maintain going forward.
First, Let's Identify the Duplication
Your original code has two nearly identical branches for rx_color and lx_color: both set the sensor mode, fetch the value, print it, check for color 3, and either exit or call pidLine. Plus, pidLine(speed) is called three times total across different branches—this is a perfect candidate for applying the DRY (Don't Repeat Yourself) principle.
Step 1: Extract Repeated Sensor Logic into a Helper Function
We can wrap the common sensor-checking behavior into a reusable function. This way, we don't have to copy-paste the same code for each sensor. Here's how that might look:
// Helper function to handle color sensor checks and exit logic bool check_and_handle_color_sensor(int sensor_num, int *color_value, const char *sensor_name, const char *turn_message) { // Repeated sensor setup/reading code set_sensor_mode(sensor_num, "COL-COLOR"); get_sensor_value(0, sensor_num, color_value); printf("%s is %d\n", sensor_name, *color_value); // Exit condition check if (*color_value == 3) { printf("%s\n", turn_message); killMotors(0); return true; // Signal that we need to exit the loop/function } return false; // No exit needed }
Step 2: Simplify the Main Logic
Now we can rewrite your original loop code to use this helper function, and call pidLine(speed) only once at the end (since it's the default behavior unless we hit an exit condition):
bool should_exit = false; if (rx_color <= 60) { should_exit = check_and_handle_color_sensor(sn_rx_color, &rx_color, "rx_color", "turn right"); } else if (lx_color <= 60) { should_exit = check_and_handle_color_sensor(sn_lx_color, &lx_color, "lx_color", "turn left"); } // If we triggered an exit condition, return early if (should_exit) { return; } // Only call pidLine once, as the default action pidLine(speed);
Why This Works Better
- Less repetition: All the sensor setup/printing/exit logic lives in one place. If you need to adjust how sensors are read or what happens when color 3 is detected, you only modify the helper function once.
- Clearer logic: The main code now reads like a plain-English sequence: check sensors, exit if needed, otherwise run the line-following PID.
- Fewer bugs: No risk of forgetting to add
pidLine(speed)to a new branch, or mistyping it in one of the duplicated spots.
Is Your Original "Unreasonable"?
Not necessarily—it works, but it's not as maintainable. As your code grows (if you add more sensors or adjust behavior), the duplicated code will become a bigger headache. The optimized version keeps your code clean, scalable, and easier to debug.
内容的提问来源于stack exchange,提问作者G. Ramistella

