DEV Community

Discussion on: What language features/concepts do insiders of the language love and outsiders hate?

Collapse
 
restoreddev profile image
Andrew Davis • Edited

I'm becoming more of a fan of static types after using Swift. I used to hate static types because of the complexity and extra code. Once you get used to types though, it's hard to go back. They add an extra level of documentation to your code and peace of mind that a function/class will only be used a certain way. Here's a non-typed function in PHP:

<?php

function upper($value) {
    if (empty($value)) {
        return false;
    }
    return strtoupper($value);
}

The problem is that anyone using this function can pass anything into the function. It does not have to be a string, it could be a number or a boolean. Plus, we don't know if the function will return a string or boolean.

We could write the same thing in Swift:

func upper(value: String) -> String? {
    if value.isEmpty {
        return nil
    }
    return value.uppercased()
}

Looking at the signature of this function, we know that it can only be used by passing in a string for the value and that it will always return either a string or nil (the question mark says the return value can be nil). The types make the function safer to use and easier to understand.

Collapse
 
einenlum profile image
Yann Rabiller

You can achieve the same now in PHP since PHP 7.1 :)