7 - Function Returns & Generic Subroutines

download 7 - Function Returns & Generic Subroutines

of 18

description

hhjh

Transcript of 7 - Function Returns & Generic Subroutines

Generic Subroutines

Function Returns &Generic SubroutinesManmath Narayan SahooFunction RetrunsEarly languages viz. Algol 60, Fortran, and Pascalfun_name = value;Control will not immediately come back to the callerOverridden latter by explicit return statementsIssue in function return(Ada code fragment)

rtn will be allocated memory in callees AR, the value of which is copied to return location allocated by the callerIssue in function return(SR code fragment)rtn will be allocated memory in callers AREiffel: Result := valResult is a default object allocated in caller

Generic subroutines - MotivationsWith large programs containing many methods it is possible that subroutines will be needed to perform similar operations on many different types.Consider some code from any language:public String add (String a, String b)return a + b;public int add ( int a, int b )return a + b;public double add ( double a, double b)return a + b;What is wrong with this code?Nothing!Generic subroutines - MotivationsThe code is correct but repetitively definedEfficient way the subroutine should only be written once and be capable of accepting any arguments.This idea is known as generic programming.In Java version 5, generic programming has been added.In C++, generics are known as templates.Other languages that feature generics are Ada, Modula-3 and C#.GenericsGenerics are especially helpful for creating container classes.Container classes are data abstractions that hold a collection of objects.The operation of the container class is independent of the type of object stored.Some examples of container classes include.StackQueueSetListGeneric SubroutinesGeneric subroutines are needed in generic classes.They allow a method to be parameterised by a single type.Hence our earlier example becomes vastly simplified:public T add ( T a, T b){return a + b;}This code is now identical to the first slide except we now have a generic type T passed as a parameter to the add method.Hence we can now call the code:int c = add( 5 , 7 );double d = add ( 4.5, 6.9 );String concat = add( gen , erics );

Implementing GenericsThe compiler creates a separate copy of the code for every instance.In Java, all instances of the generic code will share that same code at run-time.Generics in C++A generic add method in C++:template T add (T a, T b) {return a+b;}To call the methodadd(5,6);add(5.6 , 7.8);Generics in C++A generic Max method in C++:template T Max (T a, T b) {return a>b ? a : b;}To call the methodMax(5,6);Max(5.6 , 7.8);Cant we get same effect using macro???#define Max(a, b) ((a) > (b)) ? (a) : (b)Max(5,6)Will not work in case the arguments are expression that has side effectsGenerics in C++Max(x++, y)which produces((x++) > (y) ? (x++) : (y))

If x>y then x will be incremented twiceGenerics in JavaOld Java:A Vector of ints:/* Adding to a Vector */Vector v = new Vector();for ( int i = 0; i < 10; i++ )v.add(new Integer(i));

With generics:/* Adding to a Vector */Vector v = new Vector ();for (int i = 0; i < 10 ; i++)v.add(i);Java Generics : ErasureGenerics in Java are defined in terms of type erasure.This means that every generic type parameter is replaced by java.lang.Object and casts back to concrete types are automatically inserted into the code by the compiler.E.g.class choice {public boolean best ( T a , T b ) {} }

Is replaced by:

class choice{public boolean best ( Object a, Object b ) {} }

Java GenericsRecall the C++ example:template T add (T a, T b) {return a+b;}This allows any number ( int, float, short, double etc ) to be added together.How can we achieve this is Java?public T add ( T a, T b ){return a+b;}Is this correct?

Java GenericsLets perform the type erasure:public Object add ( Object a, Object b ){return a+b;}Does this compile?No!, because the + operator is not applicable to Object.We must modify the code to make it typesafe so it can compile:Java Genericspublic T add ( T a, T b ){return a+b;}

We have to impose a higher bound on the type passed to the generic method. In this case we are saying that the type passed in will be a subclass of java.lang.NumberWill the code compile now?Nope!We still have to make sure that it is typesafe.Java Genericspublic T add ( T a, T b ){if ( T instanceof Integer )return a.intValue() + b.intValue();if ( T instanceof Double )return a.doubleValue() + b.doubleValue();return null;}

public static void main( String args [] ){int a = add (5 , 6);double b = add ( 7.9, 11.3 );}We are passing ints and doubles to add but the add method takes Integers and Doubles, how is this?