| Generic Programming |
Article Index for Generic |
Website Links For Generic |
Information AboutGeneric Programming |
| CATEGORIES ABOUT GENERIC PROGRAMMING | |
| programming paradigms | |
| generic programmingprogramming paradigms | |
| generic programming | |
| programming paradigms | |
|
For example, if one wanted to create a list using generics, a possible declaration would be to say List Generic facilities first appeared in the 1970s in such languages as CLU and Ada , and were subsequently adopted by many Object-based and Object-oriented languages, including BETA , C++ , D and Eiffel . The ''template'' construct of C++ is widely cited as the generic programming construct that popularized the notion among programmers and language designers. Java has provided generic programming facilities since the introduction of J2SE 5.0. C# 2.0 and Visual Basic .NET 2005 have constructs that take advantage of the support for generics present in the Microsoft .NET Framework since version 2.0. The ML family of programming languages encourage generic programming through Parametric Polymorphism and generic Module s called ''functors.'' The Type Class mechanism of Haskell supports generic programming. Dynamic Typing , such as is featured in Objective-C , and, if necessary, judicious use of Protocols circumvent the need for use of generic programming techniques, since there exists a general type to contain any object. Whilst Java does so also, the casting that needs to be done breaks the discipline of Static Typing , and generics are one way of achieving some of the benefits of dynamic typing with the advantages of having static typing. TEMPLATES IN C++ Templates are of great utility to programmers in C++, especially when combined with multiple Inheritance and Operator Overloading . The C++ Standard Template Library (STL) provides many useful functions within a framework of connected templates. As the templates in C++ are very expressive they may be used for things other than generic programming. One such use is called Template Metaprogramming , which is a way of pre-evaluating some of the code at compile-time rather than run-time. Further discussion here only relates to templates as a method of generic programming. Technical overview There are two kinds of templates. A ''function template'' behaves like an ordinary function, but that can accept arguments of many different possibly unrelated types. For example, the C++ Standard Template Library contains the function template max(x, y) which returns either ''x'' or ''y'', whichever is larger. max() could be defined like this:template T max(T x, T y) { if (x < y) return y; else return x; } This template can be called just like a function: cout << max(3, 7); // outputs 7 The compiler determines by examining the arguments that this is a call to max(int, int) and ''instantiates'' a version of the function where the type T is int.This works whether the arguments x and y are integers, strings, or any other type for which it makes sense to say "x < y". There does not need to be any common inheritance for the set of types that can be used, and so it is actually a form of static Duck Typing . If a program defines a custom data type, all it needs to do is to use operator overloading to define the meaning of < for that type, thus allowing it to be used by the max() function. While this may seem a minor benefit in this isolated example, in the context of a comprehensive library like the STL it allows the programmer to get extensive functionality for a new data type, just by defining a few operators for it. Merely defining < allows a type to be used with the standard sort(), stable_sort(), and binary_search() algorithms; or put inside data structures such as sets, heaps, and associative arrays; and more.C++ templates are completely type safe at compile time. As a demonstration, the standard type complex does not define the < operator, because there is no strict order on Complex Number s. Therefore max(x, y) will fail with a compile error if ''x'' and ''y'' are complex values. Likewise, other templates that rely on < cannot be applied to complex data. Unfortunately, compilers historically generate somewhat esoteric and unhelpful error messages for this sort of error. Ensuring that a certain object adheres to a Method Protocol can alleviate this issue.The second type of template, a ''class template'' extends the same concept to classes. Class templates are often used to make generic containers. For example, the STL has a Linked List container. To make a linked list of integers, one writes list<int>. A list of strings is denoted list<string>. A list has a set of standard functions associated with it, which work no matter what you put between the brackets.Advantages and disadvantages Some uses of templates, such as the max() function, were previously filled by function-like Preprocessor Macro s. For example, here is a max() macro:#define max(a,b) ((a) < (b) ? (b) : (a)) Both macros and templates are expanded at compile time. Macros are always expanded inline; templates can also be expanded as inline functions when the compiler deems it appropriate. Thus both function-like macros and function templates have no run-time overhead. However, templates are generally considered an improvement over macros for these purposes. Templates are type-safe. Templates avoid some of the common errors found in code that makes heavy use of function-like macros. Perhaps most importantly, templates were designed to be applicable to much larger problems than macros. There are three primary drawbacks to the use of templates. First, many compilers historically have very poor support for templates, so the use of templates can make code somewhat less portable. Second, almost all compilers produce confusing, unhelpful error messages when errors are detected in template code. This can make templates difficult to develop. Third, each use of a template may cause the compiler to generate extra code (an ''instantiation'' of the template), so the indiscriminate use of templates can lead to Code Bloat , resulting in excessively large executables. The extra instantiations generated by templates can also cause debuggers to have difficulty working gracefully with templates. For example, setting a debug breakpoint within a template from a source file may either miss setting the breakpoint in the actual instantiation desired or may set a breakpoint in every place the template is instantiated. GENERICS IN JAVA Generics were added to the Java Programming Language in J2SE 5.0. Unlike templates, generic Java code generates only one compiled version of a generic class. Generic Java classes can only use object types as type parameters— Primitive Type s aren't allowed. Thus a List<Integer> is legal, while a List<int> is not.In Java, generics are checked at compile time for type correctness. The generic type information is then removed via a process called type erasure, leaving a non-generic version of the code. For example, List<Integer> will be converted into a non-generic (''raw'') List, which can contain arbitrary objects. However, due to the compile-time check, the resulting code is guaranteed to be type correct, as long the code generated no unchecked complier warnings.One side-effect of this process is that the generic type information is not known at runtime. Thus, at runtime, a List<Integer> and a List<String> refer to the same class, List.Wildcards Generic type parameters in Java aren't limited to specific classes. Java allows the use of ''wildcards'' to specify bounds on what type of parameters a given generic object may have. For example, List<?> indicates a list which has an unknown object type. Method s which take such a list as an argument could take any type of list. Reading from the list will return objects of type Object, and writing non- Null elements to the list isn't allowed, since the parameter type isn't known.To specify the upper bound of a generic element, the extends keyword is used, which indicates that the generic type is a subclass (either extends the class, or implements the interface) of the bounding class. So List<? extends Number> means that the given list contains objects which extend the Number class; for example, the list could be List<Float> or List<Number>. Thus, reading an element from the list will return a Number, while writing non-null elements is once again not allowed, since it is not known what type of element the list holds.To specify the lower bound of a generic element, the super keyword is used, which indicates that the generic type is a superclass of the bounding class. So List<? super Number> could be List<Number> or List<Object>. Reading from the list returns objects of type Object, while any element of type Number can be added to the list, since it is guaranteed to be a valid type to store in the list.Limitations A limitation of the Java implementation of generics impossible to create an Array of a generic type, since there is no way to determine what the array type should be. Thus if a method had a type parameter T, the programmer cannot create a new array of that type, such as via new T {Link without Title} ;. Another limitation of the Java implementation of generics is that it is impossible to create an array of a generic class with a type parameter type other than <?>. This is due to the way arrays are handled in the language, and is necessary to assure that all code that doesn't cause compile warnings without using explicit casts is guaranteed to be type safe.GENERIC PROGRAMMING FEATURES IN OTHER LANGUAGES Templates were left out of C# , largely due to the problems with templates in C++. However, C# is currently adopting generic programming features comparable to those of Java. One major difference is that generic information in C# is kept at runtime, rather than being erased at compile time. {Link without Title} D supports template programming as advanced as C++'s, and in some ways even more powerful. Ada 's generics predate templates. Many Functional Programming Languages support small-scale generic programming in the form of parameterized types and Parametric Polymorphism . In addition, Standard ML and OCaml provide functors, which are similar to class templates and to Ada's generic packages. GENERIC PROGRAMMING IN HASKELL In Haskell in particular, some language extensions have been developed for generic programming, and the language itself includes some generic aspects. In the language itself For instance, in a declaration of a user-defined data type (a binary tree with values of some given type a in the nodes and leaves): |
|
|