Tuesday, May 8, 2012

Why singleton is bad

- Against the OO spirit and increase coupling which usually becomes hidden

- Classic Singleton approach is hard to unit test

- Classic Singleton Class is hard to be inherited

http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

http://stackoverflow.com/questions/1020312/are-singletons-really-that-bad

http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/

http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/

http://sites.google.com/site/steveyegge2/singleton-considered-stupid

J2SE v.s. J2EE

http://www.velocityreviews.com/forums/t141428-j2ee-vs-j2se-vs-jdk.html

J2SE - Java 2 Standard Edition. This is what most people need for a
Servlet/Beans/JSP/XML/JDBC web application or Swing desktop application.

J2EE - Java 2 Enterprise Edition. This is J2SE plus RMI tools, EJB, an
EJB server, and other distributed computing tools. There's a high
development overhead to using J2EE features so don't bother unless you
need them.

http://stackoverflow.com/questions/402056/should-i-do-more-javase-before-jumping-to-javaee

Why stateless utility class with static methods is bad?

- Violation of the OO design principle:
---- Theoretically, if such a static method takes in arg1, arg2, ... and change their 'state', then either:
--------1. arg1, arg2, should be members of a separate class Class1 and assigned through constructor 
--------2. the operation carried out by this static method should be part of classes of arg1, arg2 ....

- Hard to mock and Unit Test

Practically, however, most people don't ban it in entirety.

+ Could potentially save memory in multithread operation (the Utility object itself is read-only by the thread as it contains no state, hence no race or deadlock) - e.g. Stateless session bean pool in J2EE?

+ Examples of existing implementation:
JAVA 
java.lang.Math
java.util.Collection

C#
System.Collections.Specialized.CollectionsUtil 
System.Net.WebUtility
 
 
http://stackoverflow.com/questions/3339929/if-a-utilities-class-is-evil-where-do-i-put-my-generic-code
http://stackoverflow.com/questions/3340032/utility-classes-are-evil
http://stackoverflow.com/questions/1942903/java-class-with-only-static-fields-and-methods-bad-or-good-practice 
 

How To Design A Good API and Why it Matters

http://www.youtube.com/watch?v=aAb7hSCtvGw 
 

Thursday, April 19, 2012

"Cannot reduce the visibility of the inherited method from ..." - inteface are implicitly public

http://stackoverflow.com/questions/8584802/reducing-visibility-of-the-java-interface-when-implementing-it-in-an-abstract-cl

interface CFL extends PowerSaver, LightingDevice{
    void showLifeTime();
    void getBrand();
}

interface PowerSaver {
    void showEcoRate();
}

interface LightingDevice {
    void doLight();
}
 
 
public abstract class Philips implements CFL{
    void showLifeTime(){}; // ! => Cannot reduce the visibility of the inherited method from CFL.
    void showEcoRate(){};  // ! => Cannot reduce the visibility of the inherited method from CFL.
}
 
 
Interface implementations must be public.
To understand the error, see the spec:
Every method declaration in the body of an interface is implicitly public.
Therefore, you're actually overriding (or, in this case, implementing) public methods.
 

Monday, April 9, 2012

JDK v. JRE v. JVM

http://www.javabeat.net/qna/67-wat-is-the-difference-between-jrejvm-and-jdk/

JDK (Java Development Kit)

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…
Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.
JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system
The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.
If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.

JVM (Java Virtual Machine)

As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file. '.class' file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.
The JVM is called "virtual" because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.
There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

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);
  }
}