Sunday 27 March 2011

Multiple Inheritances in java and the controversy


In my early bachelor's degree when I was starting to begin familiar with languages like C and C++, Our teachers use to point us to this unique problem of multiple inheritance and how it causes ambiguity in the inherited class, the solution was to use virtual functions/inheritance, it seem to be a fix that was added to C++ as it was not thought earlier while designing the C++ language.

Later during my master's degree, this new language called "java" starting to pick up waves and I was kind of impressed with it earlier being a new language and always wanted to explore it. I remembered how C++ solved the problem of multiple inheritances, and was curious of how java would play with it.

Most of them believe that multiple inheritances are possible in java through java interface. However I have a difference in opinion here.

According to me inheritance is

  • Inheriting the implementation
  • Inheriting the declarations

Inheritance of implementation is inheriting the actual code that does the work when the method is called which is done in case of C++ multiple inheritance and which is not possible to do in case of java

Inheriting only the method declaration and variables for one or many such classes for which the implementation will be written in its subclass is called inheritance of interfaces which is a bit different from the concept of multiple inheritances and it’s only possible in java. An interface defines all of those methods that an object exposes to either its subclasses or other classes.

When you inherit from a class in Java you get both inheritance of interface and implementation. All methods in the super class become part of the subclass's interface. However, when you implement an interface you only inherit interface and must provide implementations for each method.

When a Java class implements multiple interfaces you do run the risk of naming clashes. A class can implement two interfaces that share the same method name and return type. Say for example you have the following interfaces:

public interface MyFirstInterface{
                public void myFirstMethod();
}
public interface MySecoundInterface{
                public void myFirstMethod();
}

A class called MyFirstInheritance can come and implement these two interfaces at the same time without difficulty. However there may be a problem. Chances are if this happens the resulting class with not be able to provide an implementation that satisfies the expected behavior of both the interfaces at the same time. Even if you go ahead and provide and implementation for myFirstMethod() this may not make sense if you simply view the object as an MyFirstInterface or MySecoundInterface.

So what's the solution? If you have access to the source code the best course of action is to rename the methods in either of the above cases. If you don't have access, you are stuck.

Thursday 17 March 2011

HTML5 Web Storage API

Introduction

This specification allows web application to store the data in structured and persistence manner. This storage mechanism is similar to HTTP session cookies. But the web storage resolves the problems that are with cookies implementation like
  • Storage limit: Cookies can store 4KB data only
  • Performance issues: With every request cookies are transmitted to server
  • Accessibility issues: Per domain there are numbers of cookies created by different browsers
The web storage can be categorized into session storage (per browser session) and local storage (persistent across multiple sessions).

Session storage: Web application can store data into session store which can be accessible by same application within any window opened in same/another browser session/instance. The data stored into this storage is cleared off when a browser window is closed.

Local storage: This storage type allows application to store data that can be persisted across multiple browser session or reboots. It can act as a permanent repository to store data that is required to be remembered by your computer unless user tries to clear the data using browser’s data clean up wizard.

While we think of power to store in better way the good questions to ask are what about security of data and what about storage limit/constraint. Though the data is stored per domain and will be restricted by browser to have access to that domain only there are going to be potential risks from cross-directory and DNS spoofing attacks. On the space limit, W3C specifies the ideal space limit to be 5MB but it can be up to the browser vendor to decide. In order to not navigate away from the theme to describe the API let’s move on to the user cases.

Use case

There could be many scenarios where one can think of using web storage to achieve some purpose, like storing data for sticky notes, remembering how many times user visited a page, bookmarking page number in a flip book application where user has left last time, language preference user selected during signing into an application and many more.

If we use cookies to remember how many items user has added it to a shopping cart for an eCommerce transaction then we might have cross-window transaction issues. If a user is buying movie ticket in two different windows, using the same site then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same movie without really handling the scenario. Session storage for this situation would solve this problem.

Another good example to use local storage is to cache the metadata information for a diagram creation tool. The tool can allow user to draw a diagram and add multiple components which user might just leave in the middle without actually pushing draft to server. When this happens tool might store information about components, their position, colors, settings, etc into a local storage so when user resumes the tool can re-apply design panel with same state of diagram that user had created earlier.

Example

Tuesday 15 March 2011

Java design Techniques – Using Interfaces Part – 2


This article will talk more about role of interfaces and its usage while choosing between multiple inheritance and composition in your design I personally believe multiple inheritance implementations is basically inflexible. And this inflexibility maps directly to the inflexibility of inheritance as compared to composition.

By composition, I simply mean using instance variables that are references to other objects. For example, in the following code, class Apple is related to class Fruit by composition, because Apple has an instance variable that holds a reference to a Fruit object:

class Fruit {

    //...
}

class Apple {

    private Fruit fruit = new Fruit();
    //...
}

In this example, Apple is the front-end class and Fruit is the back-end class. In a composition relationship as a thumb rule, the front-end class always holds a reference in one of its instance variables to its back-end class.
Composition usually yields more flexible code. I identified the following flexibility advantages for composition:
  • It's easier to change classes involved in a composition relationship than it is to change classes involved in an inheritance relationship.
  • Composition allows you to delay the creation of back-end objects unless they're needed. It also allows you to change the back-end objects dynamically throughout the lifetime of the front-end object. However with inheritance this is not true, you get the image of the super class in your subclass object image as soon as the subclass is created, and it remains part of the subclass object throughout the lifetime of the subclass.
The one flexibility advantage I identified for inheritance was:
  • It's easier to add new subclasses (inheritance) than it is to add new front-end classes (composition), because inheritance comes with polymorphism. If you have a bit of code that relies only on a super class interface, that code can work with a new subclass without change. This isn't true for composition, unless you use composition with interfaces.
In this above flexibility comparison, however, inheritance is not as secure as it might seem given its polymorphism advantage. That last clause above, "unless you use composition with interfaces," is very important. Basically, thanks to interfaces. Here's an example:

interface Peelable {

    int peel();
}

class Fruit {

    // Return int number of pieces of peel that
    // resulted from the peeling activity.
    public int peel() {

        System.out.println("Peeling is appealing.");
        return 1;
    }
}

class Apple implements Peelable {

    private Fruit fruit = new Fruit();

    public int peel() {
        return fruit.peel();
    }
}

class FoodProcessor {

    static void peelAnItem(Peelable item) {
        item.peel();
    }
}

class Example {

    public static void main(String[] args) {

        Apple apple = new Apple();
        FoodProcessor.peelAnItem(apple);
    }
}
Given the above set of classes, you could later define a class Banana like this:

class Banana implements Peelable {

    private Fruit fruit = new Fruit();

    public int peel() {
        return fruit.peel();
    }
}

Like Apple, class Banana has a composition relationship with Fruit. It reuses Fruit's implementation of peel() by explicit delegation: it invokes peel() on its own Fruitobject. But a Banana object can still be passed to the peelAnItem() method of class FoodProcessor, because Banana implements the Peelable interface.

As this example illustrates, interfaces allow you to get the best of both worlds. You get the flexibility of composition and the flexibility of polymorphism in one design.


Monday 14 March 2011

HTML5 Web notification API

Introduction

Web notifications are the ability for an application to notify user even if they are not at the web page in the form of small notification popup box. This creates a great deal for the web applications where even if the interaction between the web application and user is not in synch they can have notifications reached to the end user.

Let me first introduce you to the various types of the notifications so it will be easy to explain different use cases for.

  • Ambient notification: A notification which appears and disappears automatically without user action.
  • Interactive notification: A notification which can receive events from user actions and deliver them to the application which created the notification.
  • Persistent notification: A notification which is displayed until the user explicitly dismisses it.
  • Notification platform: A notification platform is a system outside the browser which provides desktop notifications. Examples include Growl on MacOS, NotifyOSD on Linux, and the Windows notification API.
  • Simple notification: A notification which consists only of an icon and one or two lines of text.
  • Web notification: A notification which consists of Web platform content, such as HTML or SVG.

This specification provides an API to generate simple notifications to alert users outside of the web page. When this specification refers to displaying notifications on the "desktop", it generally refers to some static display area outside the web page, but may take several forms, including:

  • a corner of the user's display,
  • an area within the chrome of the browser,
  • the "home" screen of a mobile device

User case

When an application need to display email related notifications to user about ‘new email arrived’ it can display ambient notification with new email subject, from, etc. fields or it can display an interactive notification with an ability to return to inbox.

An application where it needs to display a upcoming meeting notification that the user might have set in his calendar or interactive notification that will allow user to snooze the meeting reminder for specific time interval.

Sometimes it can also span over wide range of notifications where say some one has posted on user’s comment, status on Facebook and user has opened multiple tabs in browser where Facebook needs to notify user about this activity.

Some application like Flicker or Picasa might want to notify user about his image upload completion progress by the time he has navigated away from the current tab.

One of the security aspects that need to be considered by an author is to make sure that the user has granted permission for a notification to appear on his platform.

Examples

Notification objects dispatch events during their lifecycle, which authors can use to generate desired behaviors. The show event occurs when the notification is shown to the user -- this may be at some time after the show() method is called in the case of limited display space and a queue. In the following example, this event is used to guarantee that regardless of when the notification is shown, it is displayed for only 15 seconds.

var notification = new Notification("mail.png", "New Email Received");

notification.onshow = function() { setTimeout(notification.cancel(), 15000); }

notification.show();

When a meeting reminder notification is acknowledged, the application suppresses other forms of reminders.

var notification = new Notification("calendar.png", "Meeting about to begin", "Room 101");

notification.onclose = function() { cancelReminders(event); }

notification.show();

Saturday 12 March 2011

HTML5 Server-Sent API

Introduction

This specification defines an API for opening an HTTP connection for receiving push notifications from a server in the form of DOM events. The API is designed such that it can be extended to work with other push notification schemes such as Push SMS. It can also be used to implement connectionless Push notification as described in below use case.

When we would like to push data to web pages over HTTP or using some dedicate server-push protocol this API can be used. It offers the use of EventSource interface to implement this functionality. Using this API we will need to create an EventSource object and registering an event listener to show various readyState as CONNECTING (numeric value 0), OPEN (numeric value 1) and CLOSED (numeric value 2).

While the connection is alive with the server the user agent will be required to parse and interpret the event stream of MIME type text/event-stream

Use case

In case of Stock application when we would like to minimize the load on client especially if it is on the portable device like mobile to save battery power and reduce network load the push notifications can certainly help. This will require server side implementation to support pushing of data to client. This can be a good alternative rather than using XMLHttpRequest or an iframe.

The browsers on mobile handsets tied to specific carriers, may offload the management of the connection to a proxy on the network. In such a situation, the user agent will be implementing the connectionless push notification with the help of some ‘push proxy’.

For example, a browser on a mobile device, after having established a connection, might detect that it is on a supporting network and request that a proxy server on the network take over the management of the connection. In between two messages, the browser detects that it is idle except for the network activity involved in keeping the TCP connection alive, and decides to switch to sleep mode to save power. Here the browser will disconnect from the server and the "push proxy" service will contact the remote HTTP server and requests the resource and if available then it will convey the event to the mobile device, which wakes only enough to process the event and then returns to sleep.

This can reduce the total data usage, and can therefore result in considerable power savings.

The only challenge is if user is opening multiple pages from the same server that is using this API. In such cases isolated domain per page might be required to solve the problem or implementing push objects with the help of Webworker API.

Examples

The user agent will create the EventSource object as described below and have a listener for incoming data.

var source = new EventSource('stockupdates.cgi');

source.onmessage = function (event) {

alert(event.data);

};

On the server-side, the script ("stockupdates.cgi" in this case) will send messages in the following form, with the text/event-stream MIME type:

data: This is the X stock value for AAA stock option.


data: This is Y stock value for BBB stock option

data: with deviation from previous value as 4.

Friday 11 March 2011

HTML5 Webworker API

Introduction

This specification defines an API for running scripts in the background independently of any user interface scripts. This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image.

Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.

User case

As the web worker API allows us to implement multi threading behavior to a web application imagine a Stock application requires doing multiple things at the same time, getting stock updates on timed interval and finding quotes for specific stock option based on user search criteria. This can be a very good example to think about web workers to be used.

Another use case could be where the application is required to display different views for the map say regular map view, satellite view, hybrid view and 3D map view displaying same region at the same time. User can switch between maps to move map directions in any of the views where all the maps should get updated to show the respective region in their view.

Examples

http://www.whatwg.org/demos/workers/stocks/page.html

HTML5 JS API specification and use cases


We all know that the HTML5 is new hot thing in the industry which everyone is trying to write about it, know more concepts, downside and curious about future of the web going ahead with this innovative standard – technology.Some might embrace it or some might criticize it whichever side of the debate you are on it will surely change the web development platform giving the power to do more – which we as geeks weren’t suppose to even think about it. Being W3C standards the browser vendors are now getting leaned towards supporting different features of it that included Microsoft Internet Explorer 9 too.
Things like jQuery, YAML, formatting techniques, and design trends change very quickly throughout the web community. And for the most part we’ve all accepted that some of the things we learn today can be obsolete tomorrow, but that’s the nature of our industry. But keeping aside that fear of not learning new thing we are going to know more about HTML5. If you Google it you will find tons of articles and blogs about HTML5 features and demos, mainly tags and new additions to HTML5 than older versions.
This blog is an attempt to gather HTML5 JS API information in one place instead of going through the traditional concepts only. As the HTML5 is in draft mode and it will change quickly, it is likely that some information outline below might get outdated. If that is the case, please get in touch so that I can update accordingly.

Below is the list of APIs in draft version by the time I wrote this blog. I am going to link them to specific posts in the blog that I will be writing the introduction and explaining the use case of each.

Web Workers
This specification defines an API for web developers to implement multi-threading running scripts in the background independently of any user interface scripts.

Server-Sent Events
This specification defines an API for opening an HTTP connection for receiving push notifications from a server in the form of DOM events. The API is designed such that it can be extended to work with other push notification schemes such as Push SMS.

Web Notifications
Web notifications are the ability for an application to notify user even if they are not at the web page in the form of small notification popup box. This creates a great deal for the web applications where even if the interaction between the web application and user is not in synch they can have notifications reached to the end user.

Web Storage
This specification allows web application to store the data in structured and persistence manner using key-value format. The web storage can be categorized into session storage (per browser session) and local storage (persistent across multiple sessions).

The Messaging API
 This specification defines an API that provides access to messaging functionality in the device, including SMS, MMS and email. It includes APIs to create and send messages. These APIs complement what sms:, mms:, and mailto: URI schemes provide with:
  • the possibility to attach files to messages,
  • A callback on success / error when a message is sent

Navigation Timing

This specification defines an interface for web applications to access timing information related to navigation and elements.

For more information http://geeksinaction.blogspot.com/2011/06/navigation-timing-api.html





Contacts API
HTML5 Web Messaging
File API: Writer
File API: Directories and System
File API
Web IDL
Permissions for Device API Access
The Media Capture API
HTML Media Capture
RDFa API
The Widget Interface
Geolocation API Specification
XMLHttpRequest Level 2
Indexed Database API
XMLHttpRequest
Cross-Origin Resource Sharing
API for Media Resource 1.0
The System Information API
Uniform Messaging Policy, Level One
Selectors API Level 2
Programmable HTTP Caching and Serving
The Web Sockets API
Selectors API Level 1
Web Forms 2.0

Wednesday 9 March 2011

Java Design Techniques – Using Interfaces Part - 1

Interfaces give you more polymorphism and design freedom than singly inherited families of classes, let us prove this statement. 

Consider an example of singly inherited families of classes.

abstract class Animal {
    abstract void talk();
}
class Dog extends Animal {
    void talk() {
        System.out.println("Woof!");
    }
}
class Cat extends Animal {
    void talk() {
        System.out.println("Meow.");
    }
}
class Interrogator {
    static void makeItTalk(Animal subject) {
        subject.talk();
    }
}
 
Given these set of classes and inheritance, it becomes mandatory for you to pass only objects of the family Animal to the makeItTalk() function. 

Remember a very good design never mandates you on any obvious scenario that might occur in future. As in case of the above example it does and hence it’s not a very good design to follow. This is where interfaces come and save you.

Using Interfaces make your design more flexible. Interfaces give you more polymorphism and design freedom than singly inherited families of classes, because with interfaces you don't have to make everything fit into one family of classes. 

For example:

interface Talkative {

    void talk();
}

abstract class Animal implements Talkative {

    abstract public void talk();
}

class Dog extends Animal {

    public void talk() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {

     public void talk() {
        System.out.println("Meow.");
    }
}

class Interrogator {

    static void makeItTalk(Talkative subject) {
        subject.talk();
    }
}

Given this set of classes and interfaces, later you can add a new class to a completely different family of classes and still pass instances of the new class to makeItTalk(). For example, imagine you add a new CuckooClock class to an already existing Clock family:

class Clock {
}

class CuckooClock implements Talkative {

    public void talk() {
        System.out.println("Cuckoo, cuckoo!");
    }
}

Because CuckooClock implements the Talkative interface, you can pass a CuckooClock object to the makeItTalk() method:

class Example {

    public static void main(String[] args) {
        CuckooClock cc = new CuckooClock();
        Interrogator.makeItTalk(cc);
    }
}

With single inheritance only, you'd either have to some how fit CuckooClock into the Animal family, or not use polymorphism. With interfaces, any class in any family can implement Talkative and be passed to makeItTalk(). This is why interfaces give you more polymorphism and design freedom than you can get with singly inherited families of classes.

Tuesday 8 March 2011

New age Mobile application development using MVC

In recent days, the technologies have started to emerge quickly with the latest innovations and older computing methods are getting back stage in the software development. I believe that one of the software development methods Model-View-Controller (MVC) can become one of most successful architectural pattern for the mobile application development permitting independent development, testing and maintenance at ease as always. Popular in Web application development, MVC is now finding a new age in mobile app development. Despite being decades old, MVC is being applied to the latest trends in software development: Web and mobile applications.

MVC is especially appropriate for Mobile applications. It can typically have a substantially larger number of specifically purposed user interface modules. So the more rigorous attention to mobile development that is implied by good MVC design makes keeping the design more tightly focused on single-purpose units that are consistent in their abstractions and play well together. At the same time, this pattern helps partition functionality into modules that can more cleanly defined with solid coherence while being more precise about limited cohesion where it properly belongs.

There are few mobile application development frameworks based on MVC pattern available in market. Sencha Touch is a powerful way to build mobile apps, and, because it relies entirely on web technologies, we can easily host those apps on the web server and have users find and access them directly from their mobile browsers. Another one is the M-project that contains all UI and Core files to build jQuery Mobile based mobile HTML5 Apps.

To write mobile application we can think of either of the below cited options to achieve a business need.

  1. Purely native application using mobile specific development platform and libraries.
  2. Web based application to address the mobile version of web. In this case HTML5 can play vital role to provide greater capabilities like storage methods, offline cache, etc.
  3. Hybrid application – developed using Webkit control of mobile platform to render the view using HTML and platform specific APIs to implement the business logic.

Model

The model can be a collection of Java script objects or platform specific classes that form a software application intended to store, and optionally separate, data. A front end object that can communicate with any user interface (for example: a mobile specific custom control that represents graphical user interface or a web component like HTML).

View

The view can represented either by the HTML/HTML5 components or platform tailored UI controls, with ability to view data being transported to the page in various ways.

Controller

The Controller communicates with the front end of the model and loads view with appropriate data.

We can depict the MVC architecture for above mentioned development methods as show in diagram below.