Sobes.tech
Junior — Middle

Can you explain the principle that involves reusing code without duplicating it?

sobes.tech AI

Answer from AI

The principle of reusing code without duplication is called DRY (Don't Repeat Yourself). It implies that each piece of knowledge or logic should be represented in the system only once.

In iOS development, this is achieved through:

  • Using functions and methods for repetitive operations.
  • Creating reusable UI components (e.g., custom UIView or UITableViewCell).
  • Using protocols and extensions to add functionality without duplication.
  • Applying inheritance and composition for code reuse.

An example of using an extension in Swift for code reuse:

extension UIView {
    func addShadow() {
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: 0, height: 2)
        self.layer.shadowRadius = 4
    }
}

// Now any UIView or its subclass can call addShadow(), avoiding code duplication.
let button = UIButton()
button.addShadow()

Thus, DRY helps keep the code clean, reduces errors, and simplifies maintenance.