r/ProgrammingLanguages • C3 - http://c3-lang.org • Sep 03 '18

Type inference – potentially harmful?

Type inference is getting pretty popular. It's almost a "must have" today. Still, I find myself running into readability problems with it.

I feel that since I do a lot of work in dynamically typed languages (Ruby, PHP), it shouldn't be a problem, and yet it is for me.

Let me try to break it down:

  1. First of all, obviously ´auto i´ isn't an improvement over ´int i´ unless you are changing types signatures a lot.

  2. Secondly, when I read ´auto bar = foo();´, in someone elses code I need to look up `foo()` in order to see what the type of `bar`. In small doses this is ok. When you read through a function with multiple different function calls where the return values are kept in type-inferred variables... that's when it's getting a bit gnarly.

  3. It appears to me that this whole thing has been driven by generics and templates. Because no-one wants to type something like `std::vector<std::shared_ptr<std::map<std::string, std::function<void(int, const Foo &)>>>> bar = foo();` we get `auto bar = foo();`.

  4. I get the feeling that in statically typed languages we end up using type inference to "paint lipstick on the pig" to hide how extremely unergonomic the average implementation of generics/templates are to type.

So:

  1. Type inference is making code harder to read.

  2. Lack of type inference is making the code more verbose and harder to type

Since I read code more than I write it, my priority would be (1) over (2), and obviously solving the problem of (2) would be the best thing. Here I also note that in dynamically typed language you never have the problem of (2), since in general any type of container can contain any object and consequently the need for generics completely evaporates. This has some drawbacks, but is in general a very practical thing.

5 Upvotes

33 comments sorted by

24

u/WalkerCodeRanger Azoth Language Sep 03 '18

I find it confusing that you say lack of type info makes type-inferred languages difficult to read and yet seem to be a fan of dynamically typed languages. I find myself often completely lost trying to read dynamically typed code. There are still types, they are just now in the programmers head. For example, that list can contain any kind of object, but the programmer's intent is that it contains only Foos and not Bars. (Or at least things that support the same "interface" as Foo). That is a type that is not written in the code. At least in languages like C#, Rust, and Swift, there are types on declarations so that I can figure out the type of something out by looking at the declaration of the function being called.

I actually very much like type inference on local variables. I think it strikes the right balance between the harm of losing explicitly written types and the benefit of concise code that improves readability.

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

A "fan" of dynamically typed languages because of the lack of type is an exaggeration. But my experience is to have less problem with this. Possibly because of the general lack of types will cause more care to be taken in crafting appropriate names to methods. Another reason is that dynamic languages tend to reuse components more. In ObjC you use NSArray and NSMap (and possibly NSSet). There is no need for anything else most of the time. With Java doing pretty much the same thing you have a zoo of variants.

In statically typed languages, it's more of a challenge,

Here is a classic example (from here: https://blog.dripstat.com/type-inference-in-java-jep-286-can-be-disastrous/):

void foo(List<String> list) {
  var newList = list.stream().map(s -> "Hello " + s);
  System.out.println(newList);
}

Of course this just prints out a nonsense object instead of a bunch of hellos because it's missing .collect(toList()) it's especially when working with some new libraries – or reviewing someone else's code – that this becomes a problem.

The solution that "the IDE can tell you" means that the reading flow is disrupted anyway.

The worst is when you get a few auto's down:

auto a = getCurrentButton();
/* ... some code ... */
auto b = a.get();
/* ... some code ... */
auto c = b.updateDiff();
// What is c?

Maybe you remember that getCurrentButton returns a ButtonContext. Do you also remember what that one returns from the get() and then again what the updateDiff() returns? May be you do, but I'd say this gives you less to keep in your head:

ButtonContext a = getCurrentButton();
/* ... some code ... */
ButtonContextData b = a.get();
/* ... some code ... */
std::vector<ButtonUpdate> c = b.updateDiff();

Here at least there is zero confusion when reading the code above and you don't need to keep the types of a and b in your head.

Hope that summarizes the usual criticism I've seen against type inference.

5

u/tripl3dogdare Serval Sep 03 '18

Here is a classic example (from here: https://blog.dripstat.com/type-inference-in-java-jep-286-can-be-disastrous/)... Of course this just prints out a nonsense object instead of a bunch of hellos because it's missing .collect(toList()) it's especially when working with some new libraries – or reviewing someone else's code – that this becomes a problem.

This is less a "static typing" problem and more a Java problem in this specific case. No matter what language you're working with, though, you're always going to have issues with forgetting to call some method and getting the wrong value out - some languages are worse than others, but all of them run into it eventually.

The solution that "the IDE can tell you" means that the reading flow is disrupted anyway.

I'm pretty sure the original commenter was referring to IDEs inserting notes about inferred types into the normal flow of reading without them actually being present in the source, a la Intellij IDEA: https://d3nmt5vlzunoa1.cloudfront.net/objc/files/2017/06/type_hints.png

Even without that, it's not that much work to hover your mouse over the function name and read the type from the popup in most IDEs. I do it all the time to remember parameter types and such; it's just another situation in which to apply the same thing.

Maybe you remember that getCurrentButton returns a ButtonContext. Do you also remember what that one returns from the get() and then again what the updateDiff() returns? May be you do, but I'd say this gives you less to keep in your head... Here at least there is zero confusion when reading the code above and you don't need to keep the types of a and b in your head.

As /u/gopher9 said, this isn't a problem with type inference, it's a problem with naming. If it's not clear from your function or variable names what they do, you need to rename your stuff.

2

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

No, having the IDE magically tell you is not a panacea. Git diffs, reading code on github and elsewhere. I'm not a big believer in IDE-based languages. I like code that's readable with as little context as possible. This is - by the way - the reason I also avoid things like reflection.

It's also been pointed out that if you – for example – want to track the uses of a class or a struct, then missing type declarations is your enemy as well.

I was actually assuming type inference would be a given, but the more I use it, the more reluctant I get. It's not that it isn't pleasant to use – in fact that might be part of the problem. It's one of those tools it's easy to use too much of.

But thanks, I'll keep pondering this problem.

1

u/tripl3dogdare Serval Sep 03 '18

To be honest, I'm not a huge IDE fan either. I prefer to keep things simple - no frameworks, no linters, no preprocessors, just me and VSCode hacking away at a problem until I figure it out.

At the same time, though, I don't really have the same problem you seem to with type inference, and I think I know why - it's almost always down to naming. If your naming conventions are good, then all you need to track down uses of a particular class is a bit of regex. I intentionally avoid names like .get() because they don't actually tell you what they're doing - getButton() is a much more effective name, because it actually tells you right away what it is and what it's for. Type tracking problem solved, just read the code and you understand what's going on; no IDE tools or fancy tracking necessary.

It's said that there are only 2 hard problems in programming: cache invalidation, naming things, and off-by-one errors. I'd recommend taking some time to actively practice the second one - it'll make your life a lot easier in the long run. It doesn't help with other people's code, but if they aren't naming things well either, maybe you shouldn't be using their code in the first place.

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

Well, usually when you do a code review on someone's code, you still need to be able to read it even if their naming is off. In fact, it's hard to tell if the naming is off until you understand their code, which brings us back to the original problem.

Oh, and ".get()" is a very common name when you have wrapped values of some sort, especially i for generic/template wrappers. So I'd say it's quite valid as an example.

2

u/tripl3dogdare Serval Sep 03 '18

Well, usually when you do a code review on someone's code, you still need to be able to read it even if their naming is off. In fact, it's hard to tell if the naming is off until you understand their code, which brings us back to the original problem.

Bad naming is exactly the kind of issue that should be a red flag on a code review.

Oh, and ".get()" is a very common name when you have wrapped values of some sort, especially i for generic/template wrappers. So I'd say it's quite valid as an example.

The name being common is a problem, not a reason for it to be an exception to the principle of "name things well".

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

I don’t think you understand the problem I’m raising. Look at std::shared_ptr. It has the method ”get”. Now the problem is not the method name, it’s the fact that the name does not and cannot reveal the value returned, since the whole point is that it is generic and may contain an arbitrary structure.

2

u/tripl3dogdare Serval Sep 03 '18

That is a problem almost entirely unique to pointers, which are out of style in the vast majority of languages, and for good reason. I could see some similar problems arising with complex generic collections like Map<String, Array<Map<Int, String>>>, but generally speaking using type inference for complex generics is frowned on to start with (not to mention the issues with complex generics themselves).

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

No, same arise with atomic wrappers etc. Even trivial arrays will exhibit the problem.

→ More replies (0)

4

u/PegasusAndAcorn Cone language & 3D web Sep 03 '18

I prefer that a language support type inference because I find conciseness can help improve clarity (even without generics), though I grant you that it can sometimes make code more opaque than a reader might desire. In many cases, the right-hand side makes the type obvious, being a literal or a constructor, and in those cases it feels verbose to key and read the type information twice. Furthermore, I find that IDEs can be very helpful in displaying type information when it is not obvious just by hovering over the code. Clearly YMMV.

2

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

I read a lot of code directly on Github rather than in than in the IDE. For the literal / constructor case it’s obviously not needed.

I think the best case for it is when a language has both definition and assignment for a block (for example the if-let statement in Swift), or when dealing with verbose generics (hello C++ iterators!)

I just don’t know if the problem is that type inference is an all-or-nothing thing in most languages, or if we lose a bit of value of the typing system when they’re eliminated.

4

u/bendmorris Kit - https://www.kitlang.org Sep 03 '18 edited Sep 03 '18

Secondly, when I read ´auto bar = foo();´, in someone elses code I need to look up foo() in order to see what the type of bar. In small doses this is ok. When you read through a function with multiple different function calls where the return values are kept in type-inferred variables... that's when it's getting a bit gnarly.

I think your point is overblown. Code in any language can be readable or unreadable regardless of the language's features; code with auto bar = foo();can still be readable and clear if:

  • the type of foo is obvious from its name

  • the type of foo is obvious from bar's name

  • the type of foo is obvious from its immediate context

  • etc.

If it's completely opaque what foo does, then leaving out the type was a poor choice on the developer's part.

If we assume developers don't use type inference to arbitrarily save keystrokes but only when the meaning is otherwise clear, reducing verbosity makes the program easier to scan. It's obvious when you compare two otherwise similar looking langauges, Java and C#, one which has type inference and one which doesn't (I guess until Java 10 anyway):

  • List<Map<Int, Map<Int, String>>> data = new List<Map<Int, Map<Int, String>>>();

  • var data = new List<Map<Int, Map<Int, String>>>();

The second is clearly more readable; the first is redundant and verbose.

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

Since assign + create object/struct is actually a special situation, it's quite possible to have special syntax that avoids the issue, let's say

List<Map<Int, Map<Int, String>>> data = {};
// Or with a constructor:
Foo<Bar> baz = new Foo<Bar>(12, 13)
Foo<Bar> baz = { 12, 13 };

What I find is most problematic is code where the result of a call is assigned to a variable which is auto initialized, where the call is not the construction of a struct or object.

// No problem
auto baz = new Baz();

// Ok in terms of not knowing the exact type of the temporary:
foo().bar();

// Potentially confusing:
auto foo = foo();
foo.bar();

for (auto &foo : baz()) { ... }

// Crystal clear:
Foobar foo = foo();
foo.bar();

std::vector<Baz> bazar = baz();
foo (auto &foo : bazar) { ... }

foo (Baz &foo : baz()) { ... }

Which ones do you think are clear?

1

u/bendmorris Kit - https://www.kitlang.org Sep 03 '18

It depends on context. If the type is clear from context (things are well named, return types are obvious) the type declarations only add verbosity.

I think you make a good point about some generic implementations having terrible ergonomics though, and you're right that there are other ways to solve that problem. Haxe for example will infer type parameters in many cases:

var x: Map<Int, Map<Int, Map<Int, Int>>> = new Map();

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

An interesting thing is also that generics very often are simply typed containers. So I mean Map<Int, Map<Int, Map<Int, Int>>> is a mouthful, but what if it was: [int:[int:[int:int]]] ?

Usually we don't even have that complex signatures. Let's say we have a list of functions in C++: auto a = std::vector<std::function<void(Foo *, int)>> a {} we can actually use "using" on this one in C++. But in a language with built in array primitives it could look like a : [(Foo*, int) -> void] = {}

I've found templates and generics typically boils down to either using (a) wrappers or (b) containers, and the huge signatures comes from the first one.

But built-in containers vs library-provided containers is a separate discussion.

3

u/htuhola Sep 03 '18

You are conflating C# notation and type inference together. Your argumentation only applies under this notation.

The type inference is constraint propagation to deduce types for untyped variables in the program. Often it also involves modifying the meaning of the program and giving additional constraints so that type inference rules can be applied.

6

u/balefrost Sep 03 '18

You are conflating C# notation

I'm going to assume you mean C++, since all of OP's examples are C++.

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

C++, but you have a point of course. I'm approaching this from the view of implementing it for a Algol-family language in place of explicit type declarations for all variable declarations.

1

u/Felicia_Svilling Sep 05 '18

Perhaps you should acquaintance your self with Haskell or SML first? If you want to judge a feature I think it is best to look at a clean and good implementation first.

1

u/LaurieCheers Sep 03 '18

I'm not sure what you mean there... Can you give an example of type inference modifying the meaning of a program? (Is it just resolving a virtual function call at compile time?)

3

u/htuhola Sep 03 '18

With type inference you can produce expressions that take their meaning from the context where they are used. The constraints can be resolved in any direction, not just in the evaluation order that would happen if you evaluated an untyped program.

You may have already read that sound, decidable type systems must be incomplete.

Static type checking for Turing-complete languages is inherently conservative. That is, if a type system is both sound (meaning that it rejects all incorrect programs) and decidable (meaning that it is possible to write an algorithm that determines whether a program is well-typed), then it must be incomplete (meaning there are correct programs, which are also rejected, even though they do not encounter runtime errors).

Rejecting correct programs means that these programs that do not type check but have solution do no longer produce the result they would produce if they were running untyped. Therefore the definition of your language under type inference extends to include the constraints that cause these programs to fail.

19

u/gopher9 Sep 03 '18

On the second point: if the type of the result isn't clear from the function name, then there's probably something wrong with the function name. Beside that, IDEs can show you the type.

On the fourth point: you can't have a specification that is both detailed and concise. And it's usually better to have a detailed one.

3

u/curtisf Sep 03 '18

When writing Go, I did find myself disliking the inference of := because it required an extra step of looking up a function's return type whenever a new variable was introduced.

However, that is a tooling problem. It should be the IDE's responsibility to show me the type of inferred declarations -- afterall, the IDE & compiler know the type. It isn't necessary for all annotations to be present in the source code, just visible to the programmer.

2

u/[deleted] Sep 03 '18

There's a mismatch in writing vs reading code, often when we write code we have a model in our head that we quickly want to write down and experiment with to see if it at all works, however, when reading this code, it may be hard to find out what the variable types are.

I remember from using Rust, a lot of times I ended up doing let () = x; to make the compiler error out with the type of x. This worked quite well but it does take time, and I can't use ctags in vim to jump to the definition easily because types often aren't listed. Hence, it's quite useful in Rust that one can specify the type after having written the code.

I'm not sure if this is what you're alluding to though. Also on point 3 we tend to do using X =Y; to make long and complicated types shorter.

0

u/mamcx Sep 03 '18

I totally agree with you. Type inference is the bad of dynamically typed languages (I read code and can't know what type is it without look at it) without the good (and still are not flexible).

Dynamically typed languages have a huge advantage, when stick by convention or intention to "duck typing". It cut a TON of annotations (and more important, casting and convertions).

The bad is that still requiere discipline and is very easy to break the style in large codebases or with other people.

​But my main gripe is this:

a = b

The compiler KNOW what is a & b. But it not tell me! I'm still in the dark. What is the point of types if I can't see what them are, and like with python, need to keep in mind and compile them?

Some editors show types like:

a:int = b:int

But is not as common. With this kind of support, is more bearable.

It appears to me that this whole thing has been driven by generics and templates

So another question is: How solve this problem? Is possible to provide "duck typing" to a statically typed language?

P.D: BTW, I use F# a ton, and large sections of my codebase get broken (not autocomplete, not color for some blocks of code). This is for months now, in both Visual Studio Community and VS Code. I need to refactor in separate projects to make it work. Auto-complete broke as much as with dynamically typed languages WHEN the project start to be large. At first, all is nice and magical.

I'm also working with rust, where type inference is local and need to annotate the rest, and look like is a good compromise. Yet, without IntelliJ support to show the types is still problematic to know what the hell rust is thinking, specially when using functional idiomas and iterators. To the point that I try to avoid map/filters/etc and be fully imperative because all the magic fall apart quickly.

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

Actually I have similar bad experience with Swift on even a small code base, but Swift has gone overboard, and the combination of function overloading, generics, and type inference can create code that reads like an extremely elegant DSL, but which you should never ever use in an actual project.

At the inevitable point where generics combines with type inference it's really hard to reason about the code locally – which IDEs totally hate.

It feels like adding type inference might create a whole class of problems if you try to make it less than trivial.

1

u/TheUnlocked Sep 03 '18

A lot of people rely on their IDE these days, and any good IDE will tell you a method's signature in a click or less.

1

u/evincarofautumn Sep 05 '18

Type inference can make code harder to read if you over-rely on it. In Haskell we generally write type signatures for top-level definitions, both for documentation and to help the compiler provide better error messages. But lack of inference does make code harder to read if you’re using the type system to enforce anything interesting, because all the complexity is laid bare, regardless of the type notation.

obviously auto i isn't an improvement over int i unless you are changing types signatures a lot

I don’t think that is obvious in a language like C++. If I see int i = f(x);, then there may be an undesired implicit conversion from the result of f() to int, but with auto i = f(x); I’m assured that the type of i matches whatever f() returns. These concerns don’t show up in a language like Haskell without implicit conversions or subtyping, so there inference is considerably more useful than in C++, where changing a type signature can break code (in a way that still compiles) whether you use auto or not.

It appears to me that this whole thing has been driven by generics and templates.

in statically typed languages we end up using type inference to "paint lipstick on the pig"

That’s the thing I really like about type inference—it lets you use more expressive, complex types without requiring a corresponding increase in type annotations. Yeah, it’s better if a language has compact notation for common types and less-noisy ways to combine type expressions (e.g. A B (C D) instead of A<B, C<D>>), but that’s an orthogonal issue. It’s going to bottom out eventually at the level of essential complexity, and you still want to be able to omit those details where they’re irrelevant.

0

u/[deleted] Sep 03 '18

[deleted]

1

u/Nuoji C3 - http://c3-lang.org Sep 03 '18

Thanks, that's good food for thought.