Hacker News new | ask | show | jobs
by Amelorate 3029 days ago
Counter-argument to changing the return type of a function with var: You can change the return type of the function to another type that might break some assumptions later in the code.

For example, if the code assumes it has a type Foo with a length field, and you change the return type of tha function to a Bar without that length field, the compiler will complain that Bar doesn't have a length field, rather than complaining about trying to assign a Bar to a variable of type Foo.

Even worse is if the Bar type changes the symantics of that length field (perhaps going from the number of elements to the max index of elements, causing an off-by-one error), the code could break silently.

That's mostly a strawman argument, however it is worth noting.

2 comments

I mentioned the first case in my post - using var is better because there’s minimal code change when refactoring and the compiler will tell you any incompatibilities to look into.

For the second case, var or not, it doesn’t matter. If you’re changing the meaning of a property it’s common sense to ‘find all refernces’ and review where that property is used.

In your example, after you manually change the return type at the caller to Bar from Foo, the usage of Foo.length and Bar.length remains and nothing will help you if they changed semantics with neither inferred nor explicit types. The access of the length field is still valid in either case.