2 – The Separation of Concerns Principle: Creating modular SwiftUI views that are easily previewable

If you are not careful, technical debt will crush your project

When you find a piece of code that has potential issues, you might decide to leave it as it is, even if it is not optimal, because the investment of fixing it would not justify the return you get.

For example, it is dangerous to touch a perfectly working piece of code just because it looks off. You risk introducing bugs when you refactor code you would not have touched otherwise.

That is different when writing new code. When we talk about time investment, we expect a return. Clearly, the faster we can release an app or a feature, the sooner we can reap its benefits. That’s why we often pick the fastest way to implement it.

However, while a shortcut can accelerate development in the short term, the resulting low-quality code will increase future maintenance costs.

Expanding the financial metaphor, we can say that borrowing time now by choosing an expedient short-term solution will incur technical debt later.

And when debt becomes unmanageable, your project goes bankrupt under the weight of spaghetti code, i.e., code so entangled that it is impossible to disentangle.

A client wasted thousands of euros because of technical debt

Years ago, I was hired as a freelancer to fix a few bugs for a project that had to be delivered to its final client.

The task was supposed to last only a couple of weeks. However, it turned out the app’s problems were not mere bugs but structural issues.

A proper fix would have required weeks of work, so, at my client’s request, I created workarounds rather than fix the underlying problem to get the app released quickly.

Unfortunately, that approach didn’t bring them very far. In the end, the codebase was unsalvageable, and they had to hire another company to rewrite it from scratch.

They spent their entire budget on the rewrite, so they practically worked for free.

Software design principles help you prevent technical debt

It is usually better to recognize shortcuts early on and consciously avoid them rather than fix the problems they create later. The longer you wait, the more your code becomes coupled, i.e., entangled.

That is why we need universal design principles to avoid such shortcuts in the first place, or help us refactor existing code with structural problems.

In the previous lesson, we discussed line length and nesting as two code smells.

Methods tend to become too long and complex because, in the short term, it is easier to write new code close to existing code, leveraging the surrounding context.

This leads to code that knows or does too much.

When a piece of code has too many concerns, developers must keep too many concepts in mind while reading it, making it harder to understand and more error-prone.

Code with too many concerns is prone to frequent changes, and because it is hard to read and modify, it is easy to introduce bugs.

So, our first design principle is the Separation of Concerns principle:

The Separation of Concerns Principle

A software module should be concerned only about a specific feature.

The word feature here refers to a specific aspect of your code, not an entire app feature, which usually requires integrating several modules.

A software module can then be a grouping of code at any level of granularity. Thus, the Separation of Concerns principle applies to long methods, massive types, and even to an entire codebase that can be split into smaller components.

Do this: Refactor your SwiftUI views with long bodies into modular components

Our first principle guides us in refactoring the long, deeply nested methods we identified in the previous lesson.

The place where you can get the most immediate return by applying the Separation of Concerns principle is in SwiftUI views with a long body.

The declarative nature of SwiftUI leads developers to deeply nest views when creating a user interface. Even the most straightforward user interface can quickly grow to hundreds of lines of code.

Let’s take, as an example, the main screen of our budgeting app.

struct CategoriesView: View {
	// ...

	var body: some View {
		List {
			Section {
				VStack(alignment: .leading, spacing: 8) {
					Text("Available Balance")
						.font(.subheadline.weight(.semibold))
					Text(amount, format: .currency(code: "USD"))
						.font(.largeTitle.weight(.bold))
				}
				.foregroundStyle(.white)
				.padding(.vertical, 8)
			}
			.listRowBackground(
				RadialGradient(
					colors: [.blue, .indigo],
					center: .topLeading,
					startRadius: 0,
					endRadius: 270
				)
			)
			Section {
				VStack(alignment: .leading, spacing: 16) {
					Text("Expenses")
						.font(.subheadline)
						.foregroundStyle(.secondary)
					LabeledContent {
						Picker("", selection: $range) {
							ForEach(SummaryRange.allCases, id: \.self) { value in
								Text(value.rawValue)
									.tag(value)
							}
						}
					} label: {
						Text(total, format: .currency(code: "USD"))
							.font(.title.weight(.bold))
					}
					Chart(data) { summary in
						BarMark(
							x: .value("Month", summary.monthName),
							y: .value("Amount", summary.amount)
						)
						.foregroundStyle(by: .value("Category", summary.category))
					}
					.chartForegroundStyleScale { colors[$0] ?? .accentColor }
					.chartXAxis {
						AxisMarks(values: .automatic) { _ in
							AxisGridLine(stroke: StrokeStyle(lineWidth: 0))
							AxisValueLabel()
						}
					}
					.frame(height: 160)
					.padding(.vertical)
					.padding(.horizontal, 8)
				}
			}
		}
		Section {
			ForEach(categories) { category in
				NavigationLink {
					TransactionsView(category: category)
				} label: {
					LabeledContent {
						Group {
							if let amount {
								Text(amount, format: .currency(code: "USD"))
									.font(.headline)
									.foregroundStyle(.primary)
							}
							if let date {
								Text(date, format: Date.FormatStyle(date: .abbreviated))
									.font(.subheadline)
							}
						}
						.frame(maxWidth: .infinity, alignment: .trailing)
					} label: {
						Label {
							Group {
								Text(header)
									.bold()
									.fixedSize()
								Text(caption)
							}
							.padding(.leading, 8)
						} icon: {
							Image(systemName: systemImage)
								.imageScale(.medium)
								.symbolVariant(.fill)
								.background {
									Circle()
										.foregroundStyle(.gray.quinary)
										.frame(width: 40, height: 40)
								}
						}
					}
					.padding(.horizontal, 12)
				}
			}
		}
		.toolbar {
			ToolbarItem { Button("", systemImage: "plus", action: {}) }
			ToolbarItem(placement: .topBarLeading) {
				Button("", systemImage: "person.fill", action: {})
			}
		}
	}
}

It is pretty hard to read this view, understand its structure, or find the lines responsible for a specific part of the UI and change their appearance.

The reason is that the body of this view has too many concerns. In the coming lessons, we will see what these are in detail, but we can already see that some relate to different parts of the user interface.

To improve the code, we can extract those into separate views. For example, the Available Balance section at the top is a clear candidate for a modular view.

private struct Balance: View {
	let amount: Decimal

	var body: some View {
		Section {
			VStack(alignment: .leading, spacing: 8) {
				Text("Available Balance")
					.font(.subheadline.weight(.semibold))
				Text(amount, format: .currency(code: "USD"))
					.font(.largeTitle.weight(.bold))
			}
			.foregroundStyle(.white)
			.padding(.vertical, 8)
		}
		.listRowBackground(
			RadialGradient(
				colors: [.blue, .indigo],
				center: .topLeading,
				startRadius: 0,
				endRadius: 270
			)
		)
	}
}

Breaking the interface into modular views makes the CategoriesView much easier to read because, with fewer concerns, it’s clearer what its body does.

struct CategoriesView: View {
	// ...

	var body: some View {
		List {
			Balance(amount: balance)
			Expenses(
				total: totalExpenses,
				summaries: summaries,
				range: $range
			)
			Categories(categories: categories)
		}
		.toolbar {
			ToolbarItem { Button("", systemImage: "plus", action: {}) }
			ToolbarItem(placement: .topBarLeading) {
				Button("", systemImage: "person.fill", action: {})
			}
		}
	}
}

Modular views are also easier to preview. The CategoriesView requires several data sources, which can be hard or impossible to set up in complex apps. The Balance view, instead, only needs a number.

#Preview("Balance") {
	List {
		Balance(amount: 12345.67)
	}
}

Back to: The SwiftUI Architecture Audit > Lessons

Leave a Comment