Sunday, December 4, 2011

Motivation for java Generics + C++ template

 
 
http://en.wikipedia.org/wiki/Generics_in_Java 

Motivation for generics

The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.

List v = new ArrayList();
  v.add("test");
  Integer i = (Integer)v.get(0);        // Run time error

Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
Using generics, the above code fragment can be rewritten as follows:
 
List<String> v = new ArrayList<String>();
  v.add("test");
  Integer i = v.get(0); // (type error)  Compile time error
 
 
 http://stackoverflow.com/questions/36347/what-are-the-differences-between-generic-types-in-c-and-java
 
1.  
There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing.

<typename T> T sum(T a, T b) { return a + b; }

The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.

In Java you have to specify a type if you want to call methods on the objects passed, something like:

<T extends Something> T sum(T a, T b) { return a.add ( b ); }

In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...

Something sum(Something a, Something b) { return a.add ( b ); }
 
... 
 
2.  
Basically in C++ templates are basically a glorified preprocessor/macro set (Note:
 since some people seem unable to comprehend an analogy, I'm not saying 
template processing is a macro).  In Java they are basically syntactic 
sugar to minimize boilerplate casting of Objects. 
 
... 
 
3. 
C++ templates have a number of features that Java Generics don't:
  • Use of primitive type arguments.
For example:
template<class T, int i>
class Matrix {
 
int T[i][i];
 
...
}
  • Use of default type arguments, which is one feature I miss in Java but there are backwards compatibility reasons for this;
  • C++ allows the use of primitive type arguments, Java doesn't; and
  • Java allows bounding of arguments.
For example:
public class ObservableList<T extends List> {
 
...
}


4. 


There is a great explanation of this topic in Java Generics and Collections By Maurice Naftalin, Philip Wadler. I highly recommend this book. To quote:
Generics in Java resemble templates in C++. ... The syntax is deliberately similar and the semantics are deliberately different. ... Semantically, Java generics are defined by erasure, where as C++ templates are defined by expansion.
 http://books.google.com.au/books?id=3keGb40PWJsC&dq=java+generics+and+collections&printsec=frontcover&source=bn&hl=en&sa=X&oi=book_result&ct=result&redir_esc=y#v=onepage&q&f=false


Thursday, December 1, 2011

Design by Contract + Precondition Weakened Example

Design by Contract

(Fowler UML Distilled, 3rd Ed)

Design by Contract uses three particular kinds of assertions: post-conditions, pre-conditions, and invariants. Pre-conditions and post-conditions apply to operations.

A post-condition is a statement of what the world should look like after execution of an operation.
For instance, if we define the operation "square root" on a number, the post-condition would take the form input = result * result, where result is the output and input is the input value.

A pre-condition is a statement of how we expect the world to be before we execute an operation. We might define a pre-condition for the "square root" operation of input > = 0. Such a pre-condition says that it is an error to invoke "square root" on a negative number and that the consequences of doing so are undefined.

An invariant is an assertion about a class.
In essence, this means that the invariant is added to pre-conditions and post-conditions associated with all public operations of the given class.
The invariant may become false during execution of a method, but it should be restored to true by the time any other object can do anything to the receiver.

The invariants and post-conditions of a class must apply to all subclasses. The subclasses can choose to strengthen these assertions but cannot weaken them. The pre-condition, on the other hand, cannot be strengthened but may be weakened.

http://www.stanford.edu/~pgbovine/programming-with-rep-invariants.htm

class Child {

  ...

  private void checkRep() {
    assert (0 <= age < 18);
    assert (birthdate + age == todays_date);
    assert (isLegalSSN(social_security_number));
  }
}

    ... and call checkRep() at the beginning and end of every public method
        The principle here is that clients should only be able to access your object via public methods, so ...
            at the beginning of a method, check to make sure the representation is intact before it starts operating on its internal state (fields)
            at the end of a method, check to make sure the representation is intact before it hands over control back to the client (caller)
        For example, look at the changeSSN() method:

class Child {
  ...

  public void changeSSN(int newSSN) {
    checkRep();
    ... method body ...
    checkRep();
  }


http://earthli.com/news/view_article.php?id=2183

An example for "The pre-condition of the parent class cannot be strengthened but may be weakened by the subclasses."

In general, the sub class may say that 'I don't mind if some requirment by the method from my parent class is not met, I will handle it (differently) in my method'.

- Example: a failback machansim

class Transmitter
{
  public Server Server { get; }

  [Pure]
  public virtual bool ServerIsReachable
  {
    get { return Server.IsReachable; }
  }

  public virtual void SendData(Data data)
  {
     Contracts.Requires(data != null);
     Contracts.Requires(ServerIsReachable);
     Contracts.Ensures(data.State == DataState.Sent);

     Server.Send(data);
  }

  [ContractInvariantMethod]
  protected void ObjectInvariant
  {
    Contract.Invariant(Server != null);
  }
}

class TransmitterWithFallback : Transmitter
{
  public Server FallbackServer { get; }

  [Pure]
  public override bool ServerIsReachable
  {
    get { return Server.IsReachable || FallbackServer.IsReachable; }
  }

  public override void SendData(Data data)
  {
    if (Server.IsReachable)
    {
      base.SendData(data);
    }
    else
    {
      FallbackServer.Send(data);
    }
  }

  [ContractInvariantMethod]
  protected void ObjectInvariant
  {
    Contract.Invariant(FallbackServer != null);
  }
}