Coding standards and type inference

With type inference you avoid “finger-typing” on both sides of an assignment:

Foo myFoo = new Foo()
var myFoo = new Foo() //Type-inference (no "win" here, but with parameterized types...)

Type inference also works with functions, allowing you to write:

def bar() : Foo = { ...etc... }
def bat(foo : Foo) = { ...etc... }

var myFoo = bar(); //Type-inference works fine

But I’m wondering if a coding standard that specified a type on the LHS of such assignments would be clearer:

Foo myFoo = bar();

Pro arguments:

  1. If you think type signatures are important for reasoning (which you presumably do if you’re using a type-inferred language), it follows that the explicitness is helpful; and
  2. If you change bar()s signature, the compiler’s going to complain about the call to bat (“Foo expected, found SomeNewType”) and that’s a little misleading.

Con arguments:

  1. Complaining about what’s passed to bat() is only “misleading” in the sense that people aren’t used to it; and
  2. Putting types on the LHS is an insult to referential transparency, since it is making explicit a difference in assignment use-cases

I am tending towards the “Con” arguments, but I think there’s merit to the “Pro” arguments. Anyone care to make the case that the “Pro” coding standard is superior?

2 thoughts on “Coding standards and type inference

  1. I say, always use var. If you need to know the type to reason about it then the code probably isn’t clear enough anyway. Meaning variable names and member names should be clear enough to read what is going on without knowing “how” it’s happening. Adding type information is adding a lot more “how” rather than “what”, which decreases ones ability to reason about it in my opinion.

Comments are closed.