Last active
May 10, 2022 09:08
-
-
Save developerjamiu/bb71ded4452a691ce80a9e0ff26d7b5e to your computer and use it in GitHub Desktop.
A snippet of code violating the Don't Repeat Yourself (DRY) principle and then, fixing it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:intl/intl.dart'; | |
void main() { | |
/// This assessment is done using the Dart Programming Language | |
/// The next lines of code describes a snippet of code violating the DRY Principle | |
/// DRY basically means "Don't Repeat Yourself" and it is aimed at reducing repititions in Software Engineering | |
/// A snippet of code violating the DRY principle | |
/// In the code below I need to format two dates [startDate] and [endDate] using a dart | |
/// package [intl] | |
final startDate = DateTime.now(); | |
final endDate = DateTime.now().add(Duration(days: 3)); | |
// Formating | |
String startDateString = DateFormat('EEEE, MMMM dd').format(startDate); | |
String endDateString = DateFormat('EEEE, MMMM dd').format(endDate); | |
print(startDateString); | |
print(endDateString); | |
/// This code violates the DRY principle since I'm duplicating [DateFormat('EEEE, MMMM d')], | |
/// It'll be worse if I need to format the date more times, I can easily make a mistake | |
/// like typing DateFormat('EERR, MMMM d').format(endDate) instead of DateFormat('EEEE, MMMM d') | |
/// Fixing it | |
/// The next lines of code will use a method created below [fullDateFormat] to hold the date formatting | |
/// Note that in a proper application, this will be added as a method to a claas ... | |
/// and in this case usually named by appending Util (i.e DateUtil) with Util meaning Utility | |
String startDateFixed = fullDateFormat(startDate); | |
String endDateFixed = fullDateFormat(endDate); | |
print(startDateFixed); | |
print(endDateFixed); | |
} | |
/// We have written this method once and can now use it in multiple places | |
String fullDateFormat(DateTime date) => DateFormat('EEEE, MMMM dd').format(date); | |
/// You can test on DartPad @ https://dartpad.dev/? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment