3 ms·
Explicit types are important wherever you have an interface contract, because otherwise you may be basing your assumptions on a wrong understanding of what the
by layer8 4y ago
Explicit types are important wherever you have an interface contract, because otherwise you may be basing your assumptions on a wrong understanding of what the actual contract is. Furthermore, explicit types serve to decouple interface from implementation. With (only) inferred types, you only have implementation, and client code is thus much more prone to relying on implementation details.
Arguably, every function or method can be regarded as having an interface contract, which is why it is useful to have explicit types there.
Personally, I also find it useful for local variables, because in a significant portion of code, the type of a variable is at least as important as its name, and guessing their type based on their name is worse than having the types be explicitly stated and visible at first sight. In particular in higher-level/domain logic code, variables are often the only ones with their specific type in the local scope. In many cases you therefore could in principle do without the name, the type would be enough.
I sometimes wonder if it could be practical to have a language allowing “anonymous” local variables, only identified by their type, as long as they’re (necessarily) the only one in their local scope with that specific type. That is, instead of writing `Foo foo = …` or `var foo = …`, have the ability to just write `Foo = …` in contexts where you only have one Foo. It would have the advantage that you know it’s a Foo (instead of guessing from the name as in `var foo`), and that the name can’t get out of sync with the type.
- kaba0 4y agoScala’s implicits are something like that (though not for local variables). You can create a method signature like `listEntities(implicit connection: DBConnection)` and at call site if you have a DBConnection typed object in scope (and exactly one so it is obvious) it will be inserted automatically.