There are many articles on the topic of DRY, I recommend reading the original “The Pragmatic Programmer” by Andy Hunt and Dave Thomas. However, I still see many developers having questions about this principle in software development.
The DRY principle states that we must not repeat ourselves, this applies to both code and the processes we perform as programmers. An example of code that violates DRY:
class Client {
public let name: String
private var messages: [String] = []
init(name: String) {
self.name = name
}
func receive(_ message: String) {
messages.append(message)
}
}
class ClientController {
func greet(client: Client?) {
guard let client else {
debugPrint("No client!")
return
}
client.receive("Hello \(client.name)!")
}
func goodbye(client: Client?) {
guard let client else {
debugPrint("No client!!")
return
}
client.receive("Bye \(client.name)!")
}
}
As you can see, in the greet and goodbye methods, an optional instance of the Client class is passed, which then needs to be checked for nil, and then work with it can begin. To comply with the DRY method, you need to remove the repeated check for nil for the class instance. This can be implemented in many ways, one option is to pass the instance to the class constructor, after which the need for checks will disappear.
We maintain DRY by specializing ClientController on a single Client instance:
class Client {
public let name: String
private var messages: [String] = []
init(name: String) {
self.name = name
}
func receive(_ message: String) {
messages.append(message)
}
}
class ClientController {
private let client: Client
init(client: Client) {
self.client = client
}
func greet() {
client.receive("Hello \(client.name)!")
}
func goodbye() {
client.receive("Bye \(client.name)!")
}
}
DRY also concerns the processes that occur during software development. Let’s imagine a situation in which a team of developers has to release a release to the market themselves, distracting them from software development, this is also a violation of DRY. This situation is resolved by connecting a CI/CD pipeline, in which the release is released automatically, subject to certain conditions by the developers.
In general, DRY is about the absence of repetitions both in processes and in code, this is also important due to the presence of the human factor: code that contains less repetitive, noisy code is easier to check for errors; Automated processes do not allow people to make mistakes when performing them, because there is no human involved.
Steve Jobs had a saying, “A line of code you never have to write is a line of code you never have to debug.”
Sources
https://pragprog.com/titles/tpp20/the-pragmatic-programmer-20th-anniversary-edition/
https://youtu.be/-msIEOGvTYM