Question

What's so special about "optional typing"?

People are very enthusiastic about Dart supporting "optional typing", but once a language supports duck typing - can't I take optional typing for granted? Isn't it an obvious feature?

Was it helpful?

Solution

When you specify types annotations you're passing information to both fellow developers and tools.

Consider this (fairly long) example of two functions - the first with no type info, the second with type info:

createConnection(details) {
  var foo = details.host; // assume details has a host property
  // do stuff
  return connection;
}

versus

Connection createConnection(ConnectionParams details) {
  var foo = details.host; // tools can validate that details has a host property
  // do stuff
  return connection;
}

When you call the first function, you need to know (from either reading API docs, or the sourcecode) that the function takes something which has a host field. You also need to know that the function returns a Connection object, not a string or something else.

When you call the second function, you know that you can pass in any object that meets the interface defined by ConnectionParams, and you know that a Connection object is returned.

Let's say you have two classes:

class MySqlConn {
  String host;
}

class PostgreSqlConn {
  String host;
}


// elsewhere
var conn = new MySqlConn()..host = '127.0.0.1';
createConnection(conn);

Although though it's valid duck typing, there is no connection in code between the first function and these classes, other than they both have a field with the same name: host.

Looking at these two classes, I can't tell that one use of them is to pass an instance of them into the createConnection() function (and it's very hard for tools to understand that, too). I can't create API docs for the createConnection function that link back to these two classes.

When you add a little more type information, communicating intent, suddenly everything comes together.

// define an interface
abstract class ConnectionParams { 
  String host;
}

// inform tools and humans that MySqlConn implements the interface
class MySqlConn implements ConnectionParams {
  String host;
}

class PostgreSqlConn implements ConnectionParams {
  String host;
}

Now both tools and humans can form links in static code from the second createConnection function back to the classes and ultimately the interface. With the first example, the link is only made at runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top