swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.3k stars 10.34k forks source link

[SR-12375] Refactoring: Extract Method to Extension #54811

Open swift-ci opened 4 years ago

swift-ci commented 4 years ago
Previous ID SR-12375
Radar rdar://problem/60832823
Original Reporter mariusLAN (JIRA User)
Type Bug
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Source Tooling | |Labels | Bug, Refactoring | |Assignee | None | |Priority | Medium | md5: a2f9fdaa45b849292dacbd0493741cee

Issue Description:

When writig complex Code FP-Style you may want to give the other Developers a better naming style to see what exactly is going on there without heading in every implementation.

The Input may have an complex reduce, map, compactMap, flatMap, sort, etc.

let foo = [
    "bar": ["baz", "buz"],
    "faz": ["baz", "buz"]
]

foo
    .sorted{ $0.key > $1.key }
    .reduce("") { (result, keyValue) -> String in
        keyValue.key + keyValue.value.joined()
    }

The goal would be to extract the reduce Method to a extension on sorted and name it properly:

let foo = [
    "bar": ["baz", "buz"],
    "faz": ["baz", "buz"]
]

foo
    .sorted{ $0.key > $1.key }
    .glueAllTogether()

extension Sequence where Element == (key: String, value: [String]) {
    func glueAllTogether() -> String {
        reduce("") { (result, keyValue) -> String in
            keyValue.key + keyValue.value.joined()
        }
    }
}

The Code is extracted properly, easy to test and better to read for all devs.

beccadax commented 4 years ago

@swift-ci create