Don't let test code reach production
Summary: Avoid adding flags like isTesting or similar in your code.
Problems ??
- Poor abstraction
- Contamination with non-business related code
- Fragile code
- Inconsistent behavior
- Hidden dependencies
- Difficulty in debugging
- Use of boolean flags
- Unreliable tests
- Code dependent on the production environment
Solutions ??
- Eliminate unnecessary conditionals
- Use dependency injection
- Model external services without using mocks
- Separate configurations
- Isolate test logic
- Maintain well-defined behavior boundaries
Refactoring ??
Using appropriate patterns allows eliminating unnecessary flags in the code logic.
Context ??
When you add flags like isTesting, you mix test and production code, creating hidden paths that only activate during tests. This prevents properly covering production code and increases the risk of errors.
Code Example ??
Incorrect ?
struct PaymentService {
is_testing: bool,
}
impl PaymentService {
fn process_payment(&self, amount: f64) {
if self.is_testing {
println!('Test mode: Skipping real payment');
return;
}
println!('Processing payment of ${}', amount);
}
}
Correct ??
trait PaymentProcessor {
fn process(&self, amount: f64);
}
struct RealPaymentProcessor;
impl PaymentProcessor for RealPaymentProcessor {
fn process(&self, amount: f64) {
println!('Processing payment of ${}', amount);
}
}
struct TestingPaymentProcessor;
impl PaymentProcessor for TestingPaymentProcessor {
fn process(&self, _: f64) {
println!('Payment not executed: Skipping real transaction');
}
}
struct PaymentService {
processor: T,
}
impl PaymentService {
fn process_payment(&self, amount: f64) {
self.processor.process(amount);
}
}
Detection ??
- [x] Semi-Automatic
This bad practice can be detected by looking for conditional flags like isTesting, environment == 'test' or DEBUG_MODE, signs that test logic is leaking into production.
Tags ???
- Testing
Level ??
- [x] Intermediate
Importance of environment separation ???
It is essential to maintain a clear separation between test and production code. If they are mixed, the correspondence between actual behavior and program operation is broken.
AI code generation ??
AI tools often introduce this problem by prioritizing quick solutions over good design.
AI detection ??
If configured correctly, detection tools can identify this problem by analyzing conditional logic based on test states.
Conclusion ??
Avoid using flags like isTesting in your code. Instead, apply dependency injection and model environments to ensure a clear separation between test and production logic.
At Q2BSTUDIO, a company specialized in development and technological services, we promote the best development practices to ensure clean and maintainable code. Our team of experts ensures the application of solid software architecture principles, avoiding problems such as test code leaking into production.




