But static typing has a few key benefits:
* No searching through comments for type constraints.
* Better autocompletion.
* Better compilation.
* Better serialization/deserialization.
I do think static typing pays for itself in the long term. Sometimes, we shouldn't care about that. Engineering means managing tradeoffs: short-term velocity vs long-term performance and maintainability?
This sounds terribly controversial, but I would love to know /when/ the static-typing pays off compared to a looser approach like sound-gradual typing (where you basically export types at a boundary and make sure that you don't violate those).
I do wonder whether a better approach is to prove your code in some other language (say Z3, Agda, Coq) - then implement it in something else, making sure you can prove isomorphism. This has quite a few benefits; you're not tied to a constructive proof on the type-level ala Haskell, Rust, Go etc... and you can automate a large part of trivial proofs.
I haven’t quite seen another language handle it this elegantly as Python does.
Then, inside the function, you can check the parameter’s data type, and handle it appropriately. And error out immediately if the wrong type is passed in.
This allows you to operate on the data at a more logical level (what it implies), as opposed to just at the technical level (what data type it is).
For example, you can pass in a single string, or a list of strings. And your function can check the type and handle it appropriately.
In C++ and Java, because of the rigidity of the function declaration, in order to do something like this, then you would need to create multiple functions to handle each of the different types that you want to allow. Then you’d need to create a wrapper function to dispatch it to its appropriate sub function. That becomes a complete mess after a while.
When you are in a codebase where you don't know which modules have been soundly typed, and which ones are still in the 'gradual' phase.
40+ years of programming experience here + a language geek. I have for years programmed in both dynamic and static languages to find out what works best for me. My conclusion is that problems are easier to solve with statically typed languages. So clearly different languages works for different personalities.
So, some examples? Also examples where "easier" is not just "you don't need to write types". That goes without saying...
But it can still be done, like you mention, by using reflection. Now, you claim that it is unsafe. This is untrue, it depends how the reflection works. Even if it were unsafe, it would be no worse than in Python, where you get a TypeError or in JavaScript where you get undefined, which probably leads to a crash later.
For an example of reflection which is safer than just a string-dictionary like JavaScript or Python, see GHC.Generics. It works by compile-time generating a type safe structure which is not just a dictionary. The function you want would have a signature involving this constraint, "Generic x => x -> x", which means it works for any "object" implementing the Generic interface.
Now you may say "but I asked for a function that handles all objects", but I don't see the point. In statically typed languages you get an additional option of using generics when you want. It doesn't make sense to me to require all types to implement reflection when you don't actually need it everywhere.
By using reflection you only lose type-safety for this particular function. With a dynamic language, you lose it everywhere.
And it's still an one-liner or close in a language without much ceremony (e.g. not Java 1.5).
Example implementation (pseudo-code):
fun capitalize (o: object) -> [f.toUpper() for f in
reflection.fields(o) if reflection.type(f) == "string"]That's why you find it hard to do in a compiled statically typed language - because it's not something that really makes any sense.
That's fair, but can you explain the context here? I.e. why are we trying to capitalize all the field names of a record object? This may be an 'XY' problem--you may be trying to accomplish some final goal and 'capitalize all the field names of a map' seems like an obvious intermediate step to you, while to a statically typed language programmer they may take a very different approach.
type T = { [k: string]: number };
const t: T = {
one: 1,
two: 2,
three: 3,
};
const makeUpperCaseKeys = (v: T): T => {
const keys = Object.keys(v);
return keys.reduce((p, c) => {
const key = c.charAt(0).toUpperCase() + c.slice(1);
return { ...p, [key]: v[c] };
}, {});
};
console.log(makeUpperCaseKeys(t));
// {
// One: 1,
// Two: 2,
// Three: 3
// }By the way, my example was meant to be more like User -> User where there are some string values and some other types of value. You want to do the transformation in a generic way, but still have the type-safe object come out the other end with all the expected keys.
interface User { name: string; age: number; }
type CapitalizeProperties<T> = { [Property in keyof T as Capitalize<string & Property>]: T[Property]; };
type CUser = CapitalizeProperties<User>;
var c : CUser = { Age: 17, Name: "john" }
You can check that the autocompletion works on the c variable.
https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=15&pc=2#...
In reality, you probably wouldn't because of how contrived and completely removed from any conceivably realistic practical goal this example is. In what situation would I actually need to solve this problem for every type in my program?
One good example is where you might treat records or "product types" as maps
Let's say you want to write a function that can capitalize all the string fields in the object passed in. In a dynamic language, you could map over the values and apply capitalization trivially. It would be a one-liner.
In a static language, you'd have a few options, but none are great:
1. You could use "reflection" or some dynamic feature to do this, but lose type-safety
2. You could make the function take in the union of all possible data types in your system, and then write a mapping function for each one. Then you're duplicating the logic N times, or at the least writing a lot of conversion boilerplate.
3. You could write two functions for each data type in your system to convert to a Map<String, Object> or some such and back, which lets you operate on the maps. Again, lots of boilerplate. Maybe you use code-generation for this? That would add complexity.
In reality, you probably wouldn't even try to write such a function in a typed language because of how awkward it is. Maybe you'd just write specific translation functions for the records you know you happen to need. But I think that's what people mean when they say you're restricted by the type-system - because it can't verify those types of operations, you find workarounds when maybe that would have been the easiest way to implement something.