Skip to content

Commit 3182d8c

Browse files
authored
Merge pull request #10 from jVirus/bulking-and-value-binding
Balking and value binding
2 parents e2dc97c + fcd65c9 commit 3182d8c

File tree

3 files changed

+105
-3
lines changed

3 files changed

+105
-3
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Balking Pattern
2+
3+
## Introduction
4+
Concurrency is a crucial aspect of software design, as it allows for the efficient execution of multiple tasks simultaneously. When dealing with concurrent programming, it is essential to handle situations where an object's method is called when it's not ready to perform the requested action. The Balking design pattern provides an elegant solution for such cases by refusing to execute the method when the object is in an undesirable state.
5+
6+
In this article, we will discuss the Balking design pattern in Swift, its benefits, and how to implement it in your applications.
7+
8+
## The Balking Pattern
9+
10+
The Balking pattern is a concurrency design pattern used to handle situations where an object's method is called when the object is not ready to perform the requested action. In such cases, the method "balks" or refuses to execute, often returning immediately without doing anything. This pattern is commonly used to avoid blocking when an object is in an undesirable state for a certain operation.
11+
12+
Here's an example of the Balking pattern implemented in Swift:
13+
```swift
14+
import Foundation
15+
16+
class WashingMachine {
17+
enum State {
18+
case idle
19+
case washing
20+
}
21+
22+
private(set) var state: State = .idle
23+
private let lock = NSRecursiveLock()
24+
25+
func wash() {
26+
lock.lock()
27+
defer { lock.unlock() }
28+
29+
if state == .washing {
30+
print("Already washing. Balking.")
31+
return
32+
}
33+
34+
state = .washing
35+
print("Start washing")
36+
DispatchQueue.global().async {
37+
self.doWashing()
38+
}
39+
}
40+
41+
private func doWashing() {
42+
Thread.sleep(forTimeInterval: 2) // Simulate washing
43+
lock.lock()
44+
defer { lock.unlock() }
45+
state = .idle
46+
print("Washing completed")
47+
}
48+
}
49+
```
50+
51+
In this example, we have a `WashingMachine` class with an internal State enum to represent its state, either idle or washing. The `wash()` method is called to initiate the washing process. We use a lock to ensure that only one thread can modify the state at a time.
52+
53+
When the `wash()` method is called while the washing machine is already in the washing state, it "balks" and returns immediately, printing "Already washing. Balking." to indicate that the operation was not performed.
54+
55+
## Benefits
56+
The Balking pattern can be useful in situations where it's undesirable to block the calling thread when an object is not ready to perform a requested action. By implementing the Balking pattern, you can improve your application's concurrency behavior and avoid potential issues caused by blocking on unavailable resources.
57+
58+
# Conclusion
59+
The Balking design pattern is a valuable tool for handling concurrency in your Swift applications. It helps you manage situations where an object's method is called when the object is not prepared to execute the requested action. By implementing the Balking pattern, you can ensure that your application responds gracefully to such situations, improving its overall concurrency behavior.

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
![GitHub last commit](https://img.shields.io/github/last-commit/jvirus/swift-design-patterns?label=Last%20Commit)
44
[![Language](https://img.shields.io/badge/language-Swift-orange.svg)]()
5-
[![Progress Patterns](https://img.shields.io/badge/patters-33/79-green.svg)]()
5+
[![Progress Patterns](https://img.shields.io/badge/patters-35/79-green.svg)]()
66
[![Progress Principles](https://img.shields.io/badge/principles-0/50-red.svg)]()
77
[![NLOC](https://img.shields.io/tokei/lines/github/jvirus/swift-design-patterns)]()
88
[![License](https://img.shields.io/badge/license-MIT-blue.svg)]()
@@ -124,7 +124,7 @@ rise of new classes
124124
> **Source:** [wikipedia.org](https://en.wikipedia.org/wiki/Concurrency_pattern)
125125
126126
- **Active Object:** decouples method execution from method invocation for objects that each reside in their own thread of control
127-
- **Balking Pattern:** executes an action on an object when the object is in a particular state
127+
- [**Balking Pattern:**](/Concurrency%20Design%20Patterns/BalkingPattern/BalkingPattern.md) executes an action on an object when the object is in a particular state
128128
- [**Barrier:**](/Concurrency%20Design%20Patterns/Barrier/Barrier.md) is a type of synchronization method. A barrier for a group of threads or processes in the source code means any thread/process must stop at this point and cannot proceed until all other threads/processes reach this barrier
129129
- **Binding Pattern:** combines multiple observers to force properties in different objects to be synchronized or coordinated in some way
130130
- **Double-Checked Locking:** used to reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed
@@ -161,7 +161,7 @@ The following patterns are not part of the `design patterns` topic. However, the
161161

162162
- [**Wildcard:**](/Swift%20Design%20Patterns/Wildcard/Wildcard.md) a wildcard pattern matches and ignores any value and consists of an underscore (_). Use a wildcard pattern when you don’t care about the values being matched against [[code]](/Swift%20Design%20Patterns/Wildcard/Wildcard.playground/Contents.swift)
163163
- [**Identifier:**](/Swift%20Design%20Patterns/Identifier/Identifier.md) an identifier pattern matches any value and binds the matched value to a variable or constant name [[code](/Swift%20Design%20Patterns/Identifier/Identifier.playground/Contents.swift)]
164-
- **Value-Binding:** a value-binding pattern binds matched values to variable or constant names. Value-binding patterns that bind a matched value to the name of a constant begin with the let keyword; those that bind to the name of variable begin with the var keyword
164+
- [**Value-Binding:**](/Swift%20Design%20Patterns/ValueBinding/ValueBinding.md) a value-binding pattern binds matched values to variable or constant names. Value-binding patterns that bind a matched value to the name of a constant begin with the let keyword; those that bind to the name of variable begin with the var keyword
165165
- **Tuple Pattern:** a tuple pattern is a comma-separated list of zero or more patterns, enclosed in parentheses. Tuple patterns match values of corresponding tuple types
166166
- **Enumeration Case:** an enumeration case pattern matches a case of an existing enumeration type. Enumeration case patterns appear in switch statement case labels and in the case conditions of `if`, `while`, `guard`, and `for-in` statements
167167
- **Optional:** an optional pattern matches values wrapped in a `some(Wrapped)` case of an `Optional<Wrapped>` enumeration. Optional patterns consist of an identifier pattern followed immediately by a question mark and appear in the same places as enumeration case patterns
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Value-Binding Pattern
2+
3+
## Introduction
4+
The value-binding pattern in Swift is a powerful feature that allows you to extract values from complex structures like enums, tuples, or custom types and assign them to new constants or variables. It is most commonly used with switch statements when working with enums that have associated values. In this article, we will discuss the value-binding pattern in detail and provide examples to demonstrate its benefits.
5+
6+
## What is the Value-Binding Pattern?
7+
Value-binding in Swift is a way to destructure complex structures and access their individual values. By using the value-binding pattern, you can create new constants or variables and assign the extracted values to them, making your code more readable and maintainable.
8+
9+
## Value-Binding with `Enums`
10+
Enums in Swift can have associated values, which are additional pieces of information stored alongside each case. The value-binding pattern is particularly useful when working with enums that have associated values, as it simplifies the process of accessing these values.
11+
12+
## Example
13+
Consider the following example demonstrating the value-binding pattern in Swift:
14+
15+
```swift
16+
enum ApiResponse {
17+
case success(Int, String)
18+
case failure(Int, String)
19+
}
20+
21+
let response = ApiResponse.success(200, "OK")
22+
23+
switch response {
24+
case .success(let statusCode, let message):
25+
print("Success: \(statusCode) - \(message)")
26+
case .failure(let statusCode, let message):
27+
print("Failure: \(statusCode) - \(message)")
28+
}
29+
```
30+
31+
In this example, we define an `ApiResponse` enum that has two cases: success and failure. Each case has associated values: a status code (`Int`) and a message (`String`).
32+
33+
When we create a response with `ApiResponse.success(200, "OK")`, the switch statement checks which case of the enum it is. The value-binding pattern is used within the switch statement to extract the associated values (status code and message) and assign them to new constants: `statusCode` and `message`. Then we can use these constants to print the response details.
34+
35+
## Benefits of the Value-Binding Pattern
36+
The value-binding pattern offers several benefits:
37+
38+
- Readability: By using value-binding, you can make your code more readable and easier to understand. Instead of accessing associated values through cumbersome methods, you can directly bind them to new constants or variables.
39+
- Maintainability: The value-binding pattern promotes cleaner code, making it easier to maintain and modify when necessary.
40+
- Flexibility: Value-binding allows you to work with complex structures, like enums with associated values, tuples, or custom types, in a more efficient and concise manner.
41+
42+
## Conclusion
43+
The value-binding pattern in Swift is an essential tool for working with complex structures, such as enums with associated values, tuples, or custom types. By using the value-binding pattern, you can simplify your code, making it more readable, maintainable, and flexible. Incorporate this pattern into your Swift development practices to improve the quality and efficiency of your code.

0 commit comments

Comments
 (0)