函数 vs 方法/Functions vs Methods

Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability.

不附属于类或类型的全局函数应该被谨慎使用。可能的话,首选方法而不是全局函数。这有助于提升可读性,也更容易被检索到。

Free functions are most appropriate when they aren't associated with any particular type or instance.

全局函数最适用于它们与任何特定类或实例无关的情况。

推荐(Preferred):

let sorted = items.mergeSorted()  // easily discoverable
rocket.launch()  // acts on the model

不推荐(Not Preferred):

let sorted = mergeSort(items)  // hard to discover
launch(&rocket)

适合全局函数的场景/Free Function Exceptions

let tuples = zip(a, b)  // feels natural as a free function (symmetry)
let value = max(x, y, z)  // another free function that feels natural

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1