How to reduce repetition in VSM? (DRY principle) #47
-
👋 Hello! I'm forwarding another question that I've fielded directly from an inquirer. Here's the question:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You'll want to avoid using classes for your state models due to the ephemeral nature of states, and the memory storage implications. There are two common approaches to reducing repetition in VSM state models:
Forwarding ActionsTo reuse other models' actions without deferring to Object-Oriented Programming (OOP) techniques, you can forward one model's action to another like so: struct LoaderModel {
func load() -> some Publisher<MyViewState, Never> {
load(page: 1)
}
fileprivate func load(page: Int) -> some Publisher<MyViewState, Never> {
...
}
}
struct LoadedModel {
let currentPage: Int
func loadNextPage() -> some Publisher<MyViewState, Never> {
LoaderModel().load(page: currentPage + 1)
}
} This generally works very well if the models are simple enough to stand up without too much work and have reasonable dependencies requirements. Protocol-Oriented ProgrammingTo reduce repetition without needing to stand up other models or use OOP, you can add functionality to more than one type by using a protocol extension. POP is unique to the Swift language but has many limitations. However, POP is useful in this context. protocol PageLoading { }
private extension PageLoading {
func load(page: Int) -> some Publisher<MyViewState, Never> {
...
}
}
struct LoaderModel: PageLoading {
func load() -> some Publisher<MyViewState, Never> {
load(page: 1)
}
}
struct LoadedModel: PageLoading {
let currentPage: Int
func loadNextPage() -> some Publisher<MyViewState, Never> {
load(page: currentPage + 1)
}
} The above examples demonstrate not only how to reuse actions, but also how to maintain state values (in this case |
Beta Was this translation helpful? Give feedback.
You'll want to avoid using classes for your state models due to the ephemeral nature of states, and the memory storage implications.
There are two common approaches to reducing repetition in VSM state models:
Forwarding Actions
To reuse other models' actions without deferring to Object-Oriented Programming (OOP) techniques, you can forward one model's action to another like so: