[swift-evolution] [Review] SE-0023 API Design Guidelines (when to use properties)

Dave Abrahams dabrahams at apple.com
Thu Jan 28 01:22:14 CST 2016


on Wed Jan 27 2016, David Waite <swift-evolution at swift.org> wrote:

>> On Jan 27, 2016, at 4:45 PM, Dave Abrahams
>> <dabrahams at apple.com> wrote:
>> on Wed Jan 27 2016, David Waite <david-AT-alkaline-solutions.com
>> <http://david-at-alkaline-solutions.com/>> wrote:
>> 
>>> Whether I get a collection’s count once at the start of my loop or for
>>> each iteration of my loop, both will give me safe behavior.
>> 
>> I'm not sure whether you're conflating two ideas here.  When we say
>> "safe" in Swift, we don't mean "doesn't have side-effects;" we mean
>> either type safety (not accessing initialized memory as a type it
>> doesn't have) or memory safety (not accessing uninitialized memory).
>> Could you clarify what you mean?
>
> Apologies, I omitted the definition of safe I was using when paring
> down the email and didn’t notice (FYI, the original definition of safe
> and idempotent came from HTTP).
>
> I mean without *impacting* side effects. For value types this means
> non-mutable, but not necessarily forbidding mutation of classes
> (including ones referenced internally by the struct). This means that
> any side effects are not visible from the API perspective.
>
> On a separate reply of what I mean by this, I gave the example of
> using a logging interface, or having a collection backed by a splay
> tree (a data structure whose topology is modified on read).
>
>> 
>>> Once you have the safety aspect underway, usability and consistency
>>> determine what stays as properties or gets promoted to methods.
>>> 
>>> Example: from a safety perspective, “reverse” and many other methods
>>> could be getter property on CollectionType. However, they could not be
>>> properties on the super type SequenceType, because SequenceType is
>>> allowed to consume the underlying data. To have “reverse’ be
>>> consistent across both SequenceType and its subtype CollectionType, it
>>> needs to be a method.
>>> 
>>> underestimateCount() looks like it could be a property for safety, but
>>> some other design/consistency aspects made it a method.
>> 
>> This is useful, thanks!
>
> Yeah, once you qualify what can be a property by the basic level of
> user expectation, there are other aspects (including complexity and
> usage) that come into play when deciding between properties and
> methods.
>
> Count is a great example; with C-style for loops in the picture, it
> was probable someone would call count in their comparison on each
> loop, not realizing it backs a possibly O(n) operation. With C-style
> loops gone, having count be a property is more easily justified.

Meh. I don't think 

    while i < x.count {
      ...
      ++i
    }

is any less likely than a C-style for loop was.

-- 
-Dave



More information about the swift-evolution mailing list