- Mastering macOS Programming
- Stuart Grimshaw
- 296字
- 2021-07-02 22:54:28
Separation of concerns
Separation of concerns is important enough to be awarded its own abbreviation, SoC. It is a principle that applies to all levels of granularity. It means not only that objects administer their own internal state (and so on), but that entire functional layers of a program are themselves encapsulated and communicate with other layers via strict, well-defined interfaces.
And yet, how often it is that we forget to apply those principles. Take another look at the ViewController.swift file of our SalesTaxCalc project. Did it jar with you that a view-controller object was being required to perform tax calculations? I hope that, if it didn't, it will by the end of this book. A View Controller's responsibilities are many, but certainly don't include tax calculations. Such code belongs not only in a different class, but to an altogether different area of the program. The View Controller needs to send user input to that layer, and convey to the view the result of the calculation, but the calculation belongs somewhere else.
Not only do we reduce the complexity of the ViewController class itself, we also gain the option of changing how the calculation is performed without altering the ViewController class's code. Furthermore, if we have some TaxCalculator class, we can use it in other parts of the program, or even in a different program.
"But it's only a tiny program!" I hear you think. It would be foolish to suggest that such a small amount of code really needs that separation, but the fact is, all programs start off small, and where do you draw the line? It is hard to say where such a line is drawn, but safe to say that many, if not most, developers draw that line too late, too often.