Question #103EasyGeneral

What is DRY in coding ?

Answer

Overview

DRY stands for "Don't Repeat Yourself" — a fundamental software engineering principle that states every piece of knowledge or logic should exist in exactly one place.


The Problem — Repeated Code

dart
// ❌ DRY violation — same validation logic duplicated
class LoginScreen extends StatelessWidget {
  void validate(String email) {
    if (email.isEmpty) throw 'Email is required';
    if (!email.contains('@')) throw 'Invalid email';
  }
}

class RegisterScreen extends StatelessWidget {
  void validate(String email) {
    if (email.isEmpty) throw 'Email is required';   // Copy-pasted!
    if (!email.contains('@')) throw 'Invalid email'; // Copy-pasted!
  }
}

The Fix — Centralize Logic

dart
// ✅ DRY — one place for email validation
class Validators {
  static String? email(String? value) {
    if (value == null || value.isEmpty) return 'Email is required';
    if (!value.contains('@')) return 'Invalid email format';
    return null;
  }

  static String? password(String? value) {
    if (value == null || value.length < 8) return 'Min 8 characters';
    return null;
  }
}

// Used anywhere
TextFormField(validator: Validators.email);

DRY in Flutter — Reusable Widgets

dart
// ❌ Repeated widget code
Column(children: [
  Padding(padding: EdgeInsets.all(8), child: Text('Title 1', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold))),
  Padding(padding: EdgeInsets.all(8), child: Text('Title 2', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold))),
]);

// ✅ DRY — extract to reusable widget
Widget sectionTitle(String text) => Padding(
  padding: EdgeInsets.all(8),
  child: Text(text, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
);

Column(children: [sectionTitle('Title 1'), sectionTitle('Title 2')]);

DRY in Constants and Themes

dart
// ✅ Centralized constants
class AppColors {
  static const primary = Color(0xFF6200EE);
  static const secondary = Color(0xFF03DAC6);
  static const error = Color(0xFFB00020);
}

// ✅ Centralized strings
class AppStrings {
  static const appName = 'My App';
  static const loginTitle = 'Welcome Back';
}

DRY vs WET

DRYWET (Write Everything Twice)
Code duplication❌ None✅ Common
Bug fixesFix in one placeMust fix everywhere
MaintenanceEasyHard
ReadabilityBetterBloated

Key Insight: Violation of DRY is the root cause of many bugs — you fix one copy but forget another. Apply DRY to logic and config; be pragmatic with UI (sometimes a tiny copy is clearer than an over-abstracted shared component).