CSC/ECE 517 Fall 2011/ch6 6c sj: Difference between revisions
No edit summary |
|||
Line 133: | Line 133: | ||
<li>Information hiding is not achieved as the code is all exposed in the header.</li> | <li>Information hiding is not achieved as the code is all exposed in the header.</li> | ||
</ol> | </ol> | ||
==Evolution of Generics== | |||
Here we take Java programming language as an example to explain evolution of generics. Generics were introduced with Java 1.5. However, before that, the codes were bulky and messy but the results were same. Rather than simply using a List<Integer> or Comparable<String>, developers had to deal with a significant amount of inheritance, casting, and instanceof testing. For example, an ArrayList to store only Integers pre-generics might look like the below snippet: | |||
<pre> | |||
public class IntegerList extends ArrayList{ | |||
public boolean add(Object o){ | |||
if(o instanceof Integer) | |||
return super.add(o); | |||
return false; | |||
} | |||
public Integer get(int index){ | |||
return (Integer)super.get(index); | |||
} | |||
} | |||
</pre> | |||
Generics allows to write more modular and reusable code that is adaptable to various datatypes, yet logically restrictive as well. Currently, generics are implemented using erasure, which means that the generic type information is not available at runtime, which makes some kind of code hard to write. Generics were implemented this way to support backwards compatibility with older non-generic code. Reified generics would make the generic type information available at runtime, which would break legacy non-generic code. Generics are implemented using erasure, in which generic type parameters are simply removed at runtime. That doesn't render generics useless, because you get typechecking at compile-time based on the generic type parameters, and also because the compiler inserts casts in the code based on the type parameters. | |||
==Erasure v/s Reification== | |||
Consider the below example, it won't work because of erasure. | |||
<pre> | |||
public class Test<Key, Val> { | |||
public void test(Key key) { | |||
} | |||
public void test(Val value) { | |||
} | |||
} | |||
</pre> | |||
This would give a name clash error for having same erasure and one way to avoid the error is by renaming the method name but this will not the serve the purpose of overloading. Similarly, the below example would give errors because the JVM is not aware of the type T instead views it just as an Object. | |||
<pre> | |||
public class Test { | |||
public <T> void f() { | |||
T t = new T(); | |||
} | |||
} | |||
</pre> | |||
So reified generics have support in the compiler for preserving type information whereas type erased generics don't have and that "remember" the class they were created with during runtime. Below are some of the reasons why Java should have reified generics: | |||
<ol> | |||
<li>Type argument erasure cripples frameworks that works with generic types and this results in horrid workarounds</li> | |||
<li>Reified generics allows Typesafe narrowing. Currently in Java, we first test the type of the object using the instanceof operator, and then attempt to downcast it using a C-style typecast</li> | |||
<li>Interoperability between statically-typed is difficult since few support reified generics.</li> | |||
</ol> | |||
But at the same time reified generics have issues and one of the main concern is incompatible with the current collections. So a test on instanceof List<String> would now test that the object is an instance of List but also that its elements are of type String. This requires a lot of work around since we need to distinguish between collections making used of reified types from their older types. | |||
==Reference== | ==Reference== | ||
Line 151: | Line 198: | ||
<li>http://jnb.ociweb.com/jnb/jnbJul2003.html</li> | <li>http://jnb.ociweb.com/jnb/jnbJul2003.html</li> | ||
<li>http://tech.puredanger.com/java7/#reified</li> | |||
<li>http://gafter.blogspot.com/2006/11/reified-generics-for-java.html</li> | |||
<li>http://relation.to/21406.lace</li> | |||
<li>http://beust.com/weblog/2011/07/29/erasure-vs-reification/</li> | |||
</ol> | </ol> |
Revision as of 17:24, 17 November 2011
Generic Programming
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This enables writing common set of functions which differ only in the types on which they operate. This reduces duplication. Software entities created using generic programming are known as generics in Ada, Eiffel, Java, C#, F#, and Visual Basic .NET; parametric polymorphism in ML, Scala and Haskell, templates in C++.
For example, given various data structures and several algorithms, the brute force way would be implement them for each data structure which would mean that various combinations of implementations will be necessary. Generic programming reduces this effort.
Generics in Java
What are Generics?
Generics were added to Java programming language as a part of J2SE 5.0 release in 2004. They allow programmers to develop generic and compile safe applications which enables a type or method to operate on objects of various type. This feature is well utilized while implementing Java Collections. The reason why people went into generic programming can be well explained using the below example:
List list = new ArrayList(); list.add("name"); Integer num = (Integer)list.get(0);
In this example, we insert a String
into an ArrayList
and retrieve element by typecasting with Integer wrapper class. This throws a runtime exception because of Illegal class cast. But if we use generics, runtime exceptions can be avoided and the compiler will be able to catch such issues which in turn help a programmer to build a bug free code. So if we convert the above code to use generic then it would look like this:
List<String> list = new ArrayList<String>(); list.add("name"); Integer num = list.get(0); //line 1
Here at line 1 the compiler throws an error because the compiler on seeing the declaration of ArrayList will be expecting the list to have just String
and thereby the return type of get
to be String
.
Implementing Generics:
Java provides a feature which helps one to implement your own generic types and this will help to build more sophisticated and runtime error free applications. Consider the below example:
interface List<N> {
void add(N i);
Iterator<N> iterator();
}
interface Iterator<N> {
N next();
boolean hasNext();
}
class LinkedList<N> implements List<N> {
//Business Logic
}
So here,
N
can be replaced with any primitive data types or wrapper classes in the business logic. But we need to make sure that placeholders to be replaced with valid subtypes of Object. Generics implementation is not restricted for classes or interfaces, we can have for static/non static methods and constructors.
Example for generic methods:
<T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); // Correct } }
Pros and Cons
Pros:
- Reduces the number of casts in the program, which in turn reduces the number of potential bugs in the program.
- Improves code clarity and maintenance.
Cons:
- Parameter type information is not available at run time.
- The automatically generated casts may fail when interoperating with ill-behaved legacy code.
Templates in C++
What are templates?
Templates are functions that can operate with generic types which means that the functionality can be adapted for more than one type of data without repeating the entire code for each type.
Overview
Templates can be either function templates or class templates.
Function Templates
These are just like regular functions except that they can have arguments of different types. A single function definition works with different kinds of data types. During compile time, the actual functions are generated once the compiler knows the data type being used. This kind of template does not save any memory.
Example
template <typename Type> Type max(Type a, Type b) { return a > b ? a : b; } #include <iostream> int main() { // This will call max <int> (by argument deduction) std::cout << max(3, 7) << std::endl; // This will call max<double> (by argument deduction) std::cout << max(3.0, 7.0) << std::endl; // This type is ambiguous, so explicitly instantiate max<double> std::cout << max<double>(3, 7.0) << std::endl; return 0; }
Class Templates
A class template provides a specification for generating classes based on parameters. A class template is instantiated by passing a given set of types to it as template arguments.
Example
template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };
Features of C++ Templates
Some of the features of C++ templates are:
-
Implemented in the compiler.
- No runtime overhead
- Requires template source to be in headers
- Latent typing means template instantiator does no type checking
- Glorified macro facility
- “Macros done right”/“Macros that look like classes”
- Can use template arguments for both classes and straight function
- Template specialization
- Specific implementation of a templated type or method
- Pattern matching and text replacement
- Declarative model (like Prolog)
Pros and Cons
Usage of templates have both advantages and disadvantages.
Pros
- Reduction in code size.
- They are type-safe, that is, type-checking is done at compile time.
Cons
- Since all compilers are not good at their support for templates, they may not be very portable.
- Compilers generate additional code for each template type, this could lead to huge code if usage of templates is not checked.
- Information hiding is not achieved as the code is all exposed in the header.
Evolution of Generics
Here we take Java programming language as an example to explain evolution of generics. Generics were introduced with Java 1.5. However, before that, the codes were bulky and messy but the results were same. Rather than simply using a List<Integer> or Comparable<String>, developers had to deal with a significant amount of inheritance, casting, and instanceof testing. For example, an ArrayList to store only Integers pre-generics might look like the below snippet:
public class IntegerList extends ArrayList{ public boolean add(Object o){ if(o instanceof Integer) return super.add(o); return false; } public Integer get(int index){ return (Integer)super.get(index); } }
Generics allows to write more modular and reusable code that is adaptable to various datatypes, yet logically restrictive as well. Currently, generics are implemented using erasure, which means that the generic type information is not available at runtime, which makes some kind of code hard to write. Generics were implemented this way to support backwards compatibility with older non-generic code. Reified generics would make the generic type information available at runtime, which would break legacy non-generic code. Generics are implemented using erasure, in which generic type parameters are simply removed at runtime. That doesn't render generics useless, because you get typechecking at compile-time based on the generic type parameters, and also because the compiler inserts casts in the code based on the type parameters.
Erasure v/s Reification
Consider the below example, it won't work because of erasure.
public class Test<Key, Val> { public void test(Key key) { } public void test(Val value) { } }
This would give a name clash error for having same erasure and one way to avoid the error is by renaming the method name but this will not the serve the purpose of overloading. Similarly, the below example would give errors because the JVM is not aware of the type T instead views it just as an Object.
public class Test { public <T> void f() { T t = new T(); } }
So reified generics have support in the compiler for preserving type information whereas type erased generics don't have and that "remember" the class they were created with during runtime. Below are some of the reasons why Java should have reified generics:
- Type argument erasure cripples frameworks that works with generic types and this results in horrid workarounds
- Reified generics allows Typesafe narrowing. Currently in Java, we first test the type of the object using the instanceof operator, and then attempt to downcast it using a C-style typecast
- Interoperability between statically-typed is difficult since few support reified generics.
But at the same time reified generics have issues and one of the main concern is incompatible with the current collections. So a test on instanceof List<String> would now test that the object is an instance of List but also that its elements are of type String. This requires a lot of work around since we need to distinguish between collections making used of reified types from their older types.
Reference
- http://en.wikipedia.org/wiki/Generic_programming
- http://en.wikipedia.org/wiki/Generics_in_Java
- http://www.oracle.com/technetwork/articles/javase/generics-136597.html
- http://download.oracle.com/javase/tutorial/extra/generics/methods.html
- http://www.cplusplus.com/doc/tutorial/templates/
- http://en.wikipedia.org/wiki/Template_(programming)
- http://www.cs.binghamton.edu/~mike/presentations/java-generics-cs580c-fall-2007.pdf
- http://jnb.ociweb.com/jnb/jnbJul2003.html
- http://tech.puredanger.com/java7/#reified
- http://gafter.blogspot.com/2006/11/reified-generics-for-java.html
- http://relation.to/21406.lace
- http://beust.com/weblog/2011/07/29/erasure-vs-reification/