如何将类中带条件分支的可变参数printf合并为单个调用?是否需优化?
Merging Conditional printf Calls into One
Absolutely, you can clean this up into a single formatted output call while keeping it maintainable. The key is to build your format string and arguments dynamically based on the $add_info flag, which eliminates the duplicate code in your original branches.
Here's a streamlined implementation:
// Precompute common values to avoid repetition $field_attr = esc_attr($field); $checked = isset($this->options[$field]) && (1 == $this->options[$field]) ? 'checked="checked" ' : ''; $descr = __($this->settings_list[$field]['descr'], 'extra-settings-for-woocommerce'); $info = __($this->settings_list[$field]['info'], 'extra-settings-for-woocommerce'); // Build the base format string $format = '<fieldset> <label><input id="%1$s" type="checkbox" name="eswc_settingz[%1$s]" value="1" %2$s />%3$s</label> </fieldset>'; // Append the optional description section if needed if ($add_info) { $format .= ' <p class="description">%4$s</p>'; } // Assemble the arguments array $args = [$field_attr, $checked, $descr]; if ($add_info) { $args[] = $info; } // Use vprintf to handle variable argument count vprintf($format, $args);
Why this works:
- DRY Code: We eliminate the duplicate long format string and repeated calculations (like the
checkedternary) from your original if/else branches. - Dynamic Construction: The format string and arguments array are built only once, with the optional parts added conditionally.
vprintfinstead ofprintf: This function accepts an array of arguments, which lets us easily add or remove the extra%4$sargument when needed.
Is the original code "good enough"?
Your original code functions correctly, but it has redundant code that makes it harder to maintain. If you ever need to update the fieldset/label structure, you'd have to change it in two places instead of one. The optimized version fixes that without adding unnecessary complexity.
内容的提问来源于stack exchange,提问作者Ryszard Jędraszyk
相关产品推荐
相关产品推荐

