3 ms·
Please excuse me, I have actually serious questions: Are Generics a solution to a problem caused by programming in OOP? Can someone explain what people did to
by MrYellowP 4y ago
Please excuse me, I have actually serious questions:
Are Generics a solution to a problem caused by programming in OOP?
Can someone explain what people did to solve these problems before someone came up with generics?
Thank you!
- kaba0 4y agoNo, functional languages also have generics. It is a type system feature, not related to OOP. Maybe the best example of a language without generics is C. In short there are 3 solutions to counter the lack of generics: copy-paste the same code multiple times with minor changes, make this copy-paste automatic with macros, or circumvent the problem by further abstraction. Let’s say you want to create a vector data structure that can grow. It is not a hard thing if you know the size of each element, so you can trivially write it for, say, ints. Now you want to reuse your logic for your custom structs that have a different size - the only change you would have to do is replace the element_size constant and repeat the whole thing with a different name (first solution). You might try to write some ugly hack with C’s pre-processor macro to generate this thing for you by an easier to use wrapper, or you could just implement a wrapper that has a next, prev pointer and use a linked list structure (with very bad performance compared to storing the elements next to each other in an array). C code often uses the third option due to the inconvenience of the first 2, which would be solved by generics.
- MrYellowP 4y agoAahhh, now I get it! So you basically write code for "one size fits all" for the programmers convinience, at the cost of performance/general efficiency? Thank you for the response!
- wvenable 4y ago> Can someone explain what people did to solve these problems before someone came up with generics? Like many things in programming, when your language didn't have a feature you just did it yourself. You didn't have one sort() method you had a different one for integers, floats, strings, etc. Or you used other language features that could accomplish the same thing only a little messier.
- SAI_Peregrinus 4y agoIf you don't have generics, you either check the data type at runtime (e.g. dynamic types, or dynamic dispatch in a statically-typed language) or you write different functions for every data type you want your function to handle.
- Jtsummers 4y agoGenerics are orthogonal to OO, they're about parameterizing your code with types (and sometimes values) rather than having to make many copies and tweaks for each possible specialization. Ada had generics in 1983, and only got OO in 1995.