Created
February 2, 2024 16:58
-
-
Save serhiybutz/e568dc1b7b53fa94a691c64bbc3ad9fe to your computer and use it in GitHub Desktop.
Injecting dependencies by value, scenario 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// MARK: - (1) Original app blob scenario: | |
/// We have the app blob with original code: | |
/// _Note: We use enums just for namespaces._ | |
enum AppBlob { | |
/// Some sigleton (global state): | |
static var someSingleton: String? | |
/// Some view: | |
struct UIView { | |
init() { | |
/// We depend on the singleton to create an instance: | |
precondition(AppBlob.someSingleton != nil) | |
} | |
func load() {} | |
} | |
/// The builder: | |
struct Builder { | |
func build() { | |
/// In the original code, the singleton initialization comes first: | |
AppBlob.someSingleton = "bla-bla-bla" | |
/// Next, we handle the view: | |
let view = UIView() | |
view.load() | |
} | |
} | |
} | |
/// Run: | |
do { | |
/// Create a builder and run it: | |
let builder = AppBlob.Builder() | |
builder.build() | |
} | |
// MARK: - (2) After modularization scenario: | |
/// Here we have modularized the constructor into some module. The only change is that we now use the configuration object to inject dependencies: | |
enum SomeModule { | |
/// The configuration object to host injected dependencies: | |
struct Configuration { | |
let view: AppBlob.UIView | |
} | |
/// The builder moved to `SomeModule`: | |
struct Builder { | |
let cfg: Configuration | |
func build() { | |
/// In the original code, the singleton initialization comes first: | |
AppBlob.someSingleton = "bla-bla-bla" | |
/// Next, we handle the view (this time the readymade view-dependency is provided by the configuration object): | |
cfg.view.load() | |
} | |
} | |
} | |
/// Run: | |
do { | |
/// Make sure the singleton is originally non-initialized: | |
AppBlob.someSingleton = nil | |
/// Create a configuration object to pass dependincies to the builder: | |
let cfg = SomeModule.Configuration(view: AppBlob.UIView()) | |
/// Create the builder and run it: | |
let builder = SomeModule.Builder(cfg: cfg) | |
builder.build() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment