C语言DRY原则应用疑问:从重复魔法数字示例切入
Great question! Let's start with the basics first: DRY (Don't Repeat Yourself) is absolutely a universal design principle across all programming languages. Its core idea is simple: every piece of knowledge, value, or logic should live in exactly one place. This makes your code easier to maintain, more readable, and less prone to bugs (like forgetting to update one instance of a magic number when you need to change it).
Now, let's fix your example code. The problem here is the repeated "magic number" 10—you've hardcoded it twice, which violates DRY because if you ever need to change that value (say, to 15), you'd have to find and update every occurrence manually.
Here are two clean, idiomatic ways to fix this in C:
1. Use a #define Macro (Traditional C Approach)
Macros are a common way to define reusable constants in C. They're processed by the precompiler, so they don't take up runtime memory:
#define DEFAULT_INPUT 10 int main(void) { int input_1 = DEFAULT_INPUT; int input_2 = DEFAULT_INPUT; /* some stuff */ return 0; }
The name DEFAULT_INPUT also adds clarity—anyone reading your code immediately knows what that value represents, unlike a random 10.
2. Use a const Constant (Type-Safe Alternative)
If you prefer type safety (the compiler will catch mismatched type errors), use a const variable instead:
const int DEFAULT_INPUT = 10; int main(void) { int input_1 = DEFAULT_INPUT; int input_2 = DEFAULT_INPUT; /* some stuff */ return 0; }
This is a more modern approach in C, as it leverages the language's type system to prevent mistakes (like accidentally assigning this constant to a float without casting, which the compiler would flag).
Why This Follows DRY
Both approaches centralize the value 10 in a single location. If you need to update it later, you only change one line of code instead of hunting down every instance of 10 in your program. This scales even better as your codebase grows—imagine if that value was used 10 times instead of 2!
And to circle back to your original question: yes, this logic applies everywhere. In Python you'd use a variable or enum, in Java a final variable, in JavaScript a const—the core idea of centralizing repeated values/logic never changes.
内容的提问来源于stack exchange,提问作者Achal

