Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: If types are good why shouldn't every var be a custom type?
2 points by jjallen 54 days ago | hide | past | favorite | 3 comments
We use types to find bugs at compile time to prevent runtime errors. When we use an i32 where an f64 should be, our linter can immediately raise an error and we can fix it immediately.

And there are a limited number of types: perhaps a few dozen at most but in reality we often use the same generic types over and over. Sometimes we have named structs which is a great example of using additional types (but this is usually to keep relevant data in a single place, not to have a unique type _usually_).

So if types are good, why don't more people use custom type for primitive types as well? I don't recall ever seeing this in a library that I have used.

This increases the number of possible types which should help us catch even more bugs. It can also have the benefit of helping the developer know what each var is, what it should be doing and where it came from.

For my example, I am thinking of a financial program, where we are tracking prices or account values. So we may have dozens of different "types" of floats, floating around our program (pun not intended but I'll take it).

We may have a stock price and lots of options prices or a person could have a bank account with lots of historical values or transactions.

So why don't more programs do this and do you do this or some companies do this?




I previously worked for a company developing custom software some of Germany’s leading banks. Even (back in the nineties) when we had to use languages such as Natural and COBOL, we developed a macro language (that compiled to COBOL) to let us use more specific types.

Particularly in finance, yo need to distinguish between dates and durations, between interest rates and volatility and a host of other business concepts. Using strong user-defined types helps catch errors at compile time. I would have no problem, on a large project, with having every variable (with the possible exception of counters, etc.) being a user-defined type. On small projects, where one developer can comfortably oversee all of the code, the overhead of correctly defining types and their operations might not outweigh the benefits. In user-facing code, for example, UI frameworks don’t use business types. Writing conversion routines to translate user input to a business type can be a disproportionate amount of work for a small project.


I've heard this referred to as "primitive obsession." You can find a lot of writing that covers the pros and cons.


there are a limited number of types

Objects are types...at least if you squint.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: