[swift-users] Parameter Validation

Brent Royal-Gordon brent at architechies.com
Mon Dec 7 02:20:34 CST 2015


> I’m looking at the special case of library code. If I surface an API in a library, it’s the library user who will call this function. Would you regard this as an assert or throws scenario?

“Library” is not a special case here—the same basic considerations apply. If you expect API users to pass you raw data from an untrustworthy source, throw. If you expect them to always give you valid data, use precondition().

For example, let’s say you’ve been hired by a company called PayMe to write PayMeKit.

* PayMeServer.setDeveloperToken(_:) takes a token issued by PayMe to each developer, which should be hardcoded into the app. This API should use precondition() to check if the token is valid.
* PayMeCard.init(name:cardNumber:expirationMonth:year:) creates an object from data which is probably provided by the user. This API should throw if the data is invalid.
* PayMeServer.buyProductWithID(_:usingCard:) is an interesting case. The product ID is probably developer-controlled, and presumably should always be valid, so we’ll precondition() that. But suppose the product ID is valid but the product is out of stock. We don’t want to crash the app, right? So we’ll throw for that one.

(Of course, buyProductWithID would in practice probably be an async call with a completion handler, and instead of throwing, you’d pass an ErrorType to the completion handler. But you get the idea.)

In short: Even when you’re writing a library, you can’t escape the requirement that you think about how your product will be used. Sorry that there’s no single answer I can give.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list