wnagrodzki / iOSProgrammingGuidelines

2 stars 0 forks source link

Use structured data #1

Closed wnagrodzki closed 5 years ago

wnagrodzki commented 6 years ago

It is common to misuse primitive type like in the function below. Any string can be passed as the argument. It is too general provided that application expects email to have certain format.

func showUser(withEmail: String) { }

Define a new type to make the API more strict, provide validation and convenience methods/properties if needed.

struct Email: RawRepresentable {

    let username: String
    let host: String

    var rawValue: String {
        return username + "@" + host
    }

    init?(rawValue: String) {
        // parsing and validation code
    }
}

func showUser(with: Email) { }

This is to increase source code reliability by building it on data you can trust.

wnagrodzki commented 6 years ago

Source of inspiration Related: Data you can trust. WWDC 2018 Check is it is possible to use RawRepresentable protocol here.

wnagrodzki commented 5 years ago

@pwetrifork @moskacz What do you think?

pwetrifork commented 5 years ago

I'm ok with this as long as there is an actual purpose, e.g. in the example above I would only introduce a new type if the app actually validated the emails. Another related idea would be to start with a typealias and refactor later, for example when validation is first introduced. Typealiasing would make refactoring much easier in such scenario.

Moskacz commented 5 years ago

I'm ok with new type if there is some benefit gained (as @pwetrifork mentioned - need for validation is a good reason for introducing new type). At the same time I'm not a big fan of typealiases. Every time I see a method that takes typealias as a parameter I need to think what it really is.

wnagrodzki commented 5 years ago

@pwetrifork @Moskacz Thanks, very good point. I edited the text to reflect that

It is too general provided that application expects email to have certain format.

If you have an idea how to rephrase the section better, let me know. Otherwise I will include like it is into the guidelines soon.