3 ms·
Ok, so this is OT but can someone explain generics and their purpose LI5?
by Kiro 13y ago
Ok, so this is OT but can someone explain generics and their purpose LI5?
- bstamour 13y agoIt allows you write code that works for multiple types. For example, consider the following function in C++: template <typename T> T min(T a, T b) { if (a < b) return a; else return b; } This code works for any type T (ints, strings, floating point numbers) that can be compared with less-than. In a language like Go that does not support generics, you would have to write a min function for ints, a different min function for strings, etc.
- Roboprog 13y agoKeeping in mind that in C++, "<" would need to be an overloaded operator defined by any type used for T. That is, to those of us non-C++ programmers, there is a function call (callback) dependency hidden in that templated function. Not saying it's a bad thing, just that most other languages would show something like "a.compare( b) < 0" to do something like this.
- adrianmsmith 13y agoTrue, it's hidden, but the compiler will only compile code which uses that function for types which meet that condition. So yes it's hidden, but at least you'll find out about it at compile-time, not run-time, so it could be worse.
- adrianmsmith 13y agoIf you want to model a user's transactions you can create a List<Transaction> rather than just a List, and then - The compiler will fail to compile your code if you put anything in the list apart from a Transaction - The compiler will fail to compile your code if you try to do anything with an object from that list which a Transaction can't do - It also makes the code more readable as if my function takes a List<Transaction> you know what you can pass to it. Does it take a List<Transaction> or a List<TransactionId>? It's obvious. - If you try to pass a List<TransactionId> then the compiler won't compile your code. (Otherwise you'll only find out about it at runtime.) This means a lot fewer fails at run-time. Which in turn means a lot less time writing (and maintaining) unit tests.