Monday, 31 January 2011

HTML5: Animation Example Step By Step

HTML5: Animation Example Step by Step

Define canvas tag inside HTML (preferrably inside body tag):
<canvas id="moving_img_id" width="600" height="600"></canvas>

Define moving image inside javascript:
 var moving_image = new Image();  
 moving_image.src = 'imageToDraw.jpg'; 

Call getContext on canvas to get the context for drawing:

    var 2d_content = canvas.getContext('2d');
    2d_content.save();   //Save Context
    2d_content.translate(350,350); //Move to this location 350,350 in this case.
    2d_content.rotate(angle);//Rotate at various angles
    2d_content.translate(0,1);//Move to a new position   
    2d_content.drawImage(moving_image, 5, 5);//Draw the image   
    2d_content.restore();// Restore context

For Animation effect call the setInterval function which will internally call drawMovingImages (same function which will execute the steps mentioned above) function every 100 milliseconds.
setInterval(drawMovingImages, 100);

Try this and have fun :)

Friday, 28 January 2011

Weekly Report (23-28 Jan 2011)

10 Billion downloads from Apple’s App Store reached this week!(Now I'm giving a re-thought whether I should step into this 'i' development area ;) Facebook has been valued 50 Billion USD.


We've got numerous acquisitions declared.
Facebook has acquired hyperlocal mobile advertising service Rel8tion.
Silicon Valley startup CardMunch, which offers a great business card reading app for the iPhone, has been acquired by LinkedIn. The service is available for free, with no limit on the number of cards that can be scanned.


Zferral- mainly about creating, tracking and managing custom referral programs, has acquired Cloudomatic which has various tools covering areas commonly required by any company- development, collaboration, storage and productivity.
PostUp Acquires UberTwitter- a popular Twitter client for Blackberry and iPhone, and is now UberMedia. It also acquires Mixx-curates social content which then becomes searchable on the info channels as per interest.
Area/Code which takes advantage of today’s environment of pervasive technologies and overlapping media to create new kinds of gameplay is now Zynga New York.
Freelancer.com acquires Freelancer.de.
Verizon Acquires Cloud Services Company Terremark. Terremark provides industry leading managed services, cloud computing, colocation & web hosting solutions for enterprise IT infrastructures.

Mumbai based Komli Media raises third round of funding of $15 million for upgrading current products and technology. Komli Media owns an online ad network - Komli and an audience measurement tool - Vizisense.com.


New product releases:
LinkedIn Launches Tool to Visualize Your Business Network.
Amazon to Roll Out Grocery Delivery Service.
Qwiki Launches Public Alpha To Change the Way You Consume Information.
Google Project Hosting adds file editing.
There is new YouTube homepage now.
Twitter now shows 'Connections' - 'Also followed by': amongst whom we follow & 'You both follow': common in following list.


Android market:
Very soon we'll be seeing Viber for Android and Blackberry as well. As of now Viber allows totally free calls anywhere in world but only to those iphones which have Viber installed.

Google to acquire fflick.
HP will be launching enterprise cloud service.
Qwiki will soon allow users to submit content.
yumm.com - A social recipe bookmarking service. Currently in beta and on invitation basis only. Bookmarklet will allow you to save recipe from any of the sites and visible under 'My Recipes' in yumm.com tab, you can share as well.

Thursday, 27 January 2011

Get DOM Elements by Class Name

Do you remember how badly we had to fight for finding elements by class name prior to HTML5? Just to use this API we had to depend on various other javascript frameworks like Prototype, YUI etc.

For example in case of YUI I had to do add the following in the HTML head section:

                <!-- Yahoo YUI 2: Dom Collection -->
                <!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo/yahoo-min.js">
</script>
                <!-- Source file -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/dom/dom-min.js">
</script>  
....and finally to find elements by class name I had to write the following:

  var viracct_posts_eles = YAHOO.util.Dom.getElementsByClassName('viracct_posts');
  

Thanks to HTML5 for bringing this support at the browser level. We no longer need to load these external libraries to avail this facility.

This is how we can find elements by class name in HTML5:

  var viracct_posts_eles = document.getElementsByClassName('viracct_posts');  
  
Very much similar to getElementsByTagName:

  var viracct_apps_eles = document.getElementsByTagName('div');
  
More posts on HTML5 features are coming soon. Stay tuned!

Wednesday, 26 January 2011

HTML5 : Easy Support For Audio Files



To embed an audio file simply wrap the audio file source tag with the newly introduced audio tag as mentioned below:

    <audio id="audio_tag_id" controls autobuffer>
      <source src="audio_files/my_fav_song.mp3" type="audio/mpeg"/>
    </audio>

If you want to give a control to play the audio, create a button with the play event support like this:

<button id="play_the_audio_id">Play</button>
<script>
var audio_file = document.getElementById('audio_tag_id');
var play_button = document.getElementById('play_the_audio_id');
play_button.addEventListener(
'click', function() {
audio_file.play();
},
false);
</script>

Similarly to give control to pause the audio, create another button with the pause event support like this:

<button id="pause_the_audio_id">Pause</button>
<script>
var audio_file = document.getElementById('audio_tag_id');
var pause_button = document.getElementById('pause_the_audio_id');
pause_button.addEventListener(
'click', function() {
audio_file.pause();
},
false);
</script>

Should We Ask for Feedback Before Launching Product?


Have you ever wondered what would be more beneficial- directly getting your product to market or asking for feedback prior to launching it?

If you ask for feedback you are sure to get a mix of positive and negative stuff. You'll get to know third person view. This perspective is likely to be unbiased. Positive feedback will of course encourage you. If you are just getting yes for everything then may be no one is thinking at all since everyone won't think alike! Criticism will for sure help you to improve. It is upto you to decide what to pick to work upon. Any modification and change is likely to extend your time to market. You need to analyse well what feature will add how much value, implementing which there will be no side effects caused by delay in its launching. Not every feedback will be constructive, so be careful in selecting what to pick up.

Look at it from other angle, it will dawn to you that successful products have not gone through market survey before launching. They keep adding features as per user requirements. Some products do get unveiled in stages- from limited users as labs edition to open for all. Getting feedback prior to launch may leave you completely confused. Working on actual users' feedback will be more useful since it is a concrete thing that users want to have.

Going to market without prior feedback may lead to missing of a really useful and must add-on from your product. And yes most of the times you don't get a second chance to leave your first impression on others (exceptions include products from companies like Google which have huge fan following and keep visiting to check for newer versions)! The best way out I feel is discussing with those who might be prospective users of your product, keep some time reserved prior to going to market...this time gap should not be huge and no major changes to be undertaken. While you are developing the product discussing with few folks might prove useful. What is your say?

Monday, 24 January 2011

Keep Mind Engaged!

It sounds very 'schoolish' essay kind of thing to write- An empty mind is devil's workshop......... the more of proverbs, the more of marks you fetch! The proverb holds great truth and rule of thumb in itself (never realized this fact when the proverb was being taught!!).

When ideas and thoughts related to them dwell in mind it is for sure going to give you constructive outcome. Outcome may be direct or indirect. Direct might be like triggering of another idea or feature. You sit at work and your work gets completed faster since you'd already thought how to do it is an indirect outcome in form of increased productivity. But filling mind with some positive thought is not that easy. Try this out- close your eyes and instruct your mind not to think about monkey. And oh you'll get to see so many monkeys!! I'm serious, not kidding (I often experience this reverse kind of behavior of mind). Mind needs to be trained to make it occupied with ideas. Big question- How. I adopt the technique of (re-re-re)enforcing, if unwanted thought occupies mind I simply replace it with the wanted one as soon as I realize! Do you have any other technique?

My dad used to bombard during academic years that 1 hour of reading should be followed by 2 hours of writing and 4 hours of thinking. Yes it really helps. Apparently you are not studying or working but in reality the thought process is running in the backdrop.

So what are you going to opt, all time actual work or keeping mind engaged with ideas?

Saturday, 22 January 2011

Weekly Report (17-22 Jan 2011)


From the Google space we got to hear this week that co-founder Larry Page will be replacing Eric Schmidt as CEO of Google on April 4. Eric is going to be advisor to Larry and Sergey as well as focus on external affairs.Big change queued up. The Social Network movie has won four Golden Globe awards. Wish them luck for Oscars!

Lets talk about the mergers and acquisitions of this week. Amazon acquires LOVEFiLM, which provides online video rental and on-demand video streaming over internet of movies in UK, Germany and Scandinavia. Adobe buys Demdex, the behavioral data management platform. It fetches demographic information about the customers' consuming behavior and makes inferences about it. RightNow gets stronger in customer experience by acquiring Q-go. Appcelerator buys Aptana which provides Eclipse-based web development suite. This strengthens Appcelerator's open source product Titanium development framework for mobile.

Google Venture invests in LawPivot, which is a legal advice type of Quora especially for startups. Qualcomm invests heavily in ChaCha- a web and mobile Q & A website. Kabam, a social games company may plan expansion/acquisition with new funds. Scribd raises a few million with the aim of bringing social reading to every device.

Have a look at what new has come on product releases front. Facebook recently announced the launch of a new application for feature phones that was developed in conjunction with Snaptu, a world of free apps on any phones. Mobile photo sharing app PicPlz gets polished up for Android and begins accepting beta version of API applications.

Did we get to hear any future plans this week? Google Voice will be providing number porting at mere $20. Once this takes off you don't have to change your phone number. We also got to hear that Google is going to launch a Groupon clone Google Offers. Zynga which has numerous games prepares for launching new loyalty program RewardVille. Wow, earning rewards for playing games!

Huffington Post continues with its popularity this week too in Chrome Webstore.  http://www.huffingtonpost.com/NewsGlide/ -Breaking News and Opinion on the Huffington Post.

Stay tuned for coming weekly reports!

Wednesday, 19 January 2011

The Mania of Deals

It is not just in papers that we are looking for coupons and deals now. Now it is on internet too!

After Google failed to acquire Groupon everyone started smelling the next big thing on net. Groupon is valued in billion dollars! Restaurants are running out of stock.....hmmm many folks are having party time, buying stuff at much cheaper rates. There comes a big climax to the story of Groupon getting acquired, Groupon itself is acquiring local clones! India's SoSasta.com, a discount deals offering site and Germany's CityDeal are amongst that list.

In the growing world of e-commerce every second shopping website offers deals. Amazon also offers deals- Deals and Bargains. Some times discounts while some times free shipping! Now a days deals have also turned location-aware. You are being shown deals in and around your place. For every device there are apps offering you deals, be it iPad or iPhone or Android! There is nothing to be surprised if social networking sites also try to enter into the same. It is most foreseen that very soon we'll get to see giants like Facebook or Twitter entering into discounts. People use Twitter to tweet new deals. Statups are also getting deals-crazy. Deals-mania is widespread....from giants to startups!

Ultimately who will win? Those who are dealing directly the merchants or brands have higher probability of winning this race. Will technology underneath the site matter? It will, but the apps driven by technology but without a strong merchant base will fail. Investors are pouring money into this field. And course those with real innovation will be the leading ones in this competition of deals!

Monday, 17 January 2011

Time With Mentor

You make up your mind to have a business mentor and you've even got one. But just having chosen a mentor is not an end to the chapter of mentor-mentee. There might be situations where you feel that you need to have a word with your mentor to get his advice but he is not able to find time for you. A thought that is required before you choose a mentor is does he really have enough time for you! If he himself is busy with his business then having a mentor will hardly give you any advantage. On the contrary it also does not mean prioritising in choosing someone who has no other work than mentoring you ( you might get pissed of by his all time nose poking!!).

Right from the beginning of your business you should be utilizing your mentor's time in best way. Inviting him for a party to have time with together will rarely give you required result. The problem is shift of focus- from business to food and ambiance! Instead choose to meet at office or at some casual place. Know to extract the best from your mentor. Do not assume that you'll be given dose of advice as per your phase of entrepreneurial journey. It is just like any other learning, e.g. how you learn from a senior at job. From mentor's experience try to grasp what applies to you and choose your action step accordingly. If you are surrounded by some problem and need a way out be specific about it. Mentor should know your exact situation, so give him all due details. Open up your mind!

Finally most important to remember is you are responsible to taking business decisions and not your mentor. So never fall prey to the blame game of finger pointing with mentor. Ask again- does your mentor have enough time for you? Are you utilizing it in the best possible way?

Friday, 14 January 2011

Branding Blunder

Have you ever noticed an ad board for tuitions which says 'xyz English Tutions'? I do have, not just once but many times. On at least a person like me it leaves a negative impression- what English will they teach if they themselves cannot spell words correctly! Still I'll say these boards are limited to certain extent like in the locality or at the most in that city. I spare them(not totally, just a bit) saying they've not gone to internet world yet. Once they go online they'll realize importance of correct spellings. But OMG I encounter such typos on net too. Here is one of them:







I was posting a question at a forum today when it popped up a list of Dos and Don'ts in the site. Have a look:










They are advicing users on the front of proper grammar and spellings and themselves don't follow it! If these would have been hand written things we can say there are no tools like spell check. The presence of that content on site and that too not as an image but as a text implies it has been typed. Most of the editors have spell check facility. If you are using Word then spell check is On by default. Do we turn deaf ears and blind eyes to those too?








These were just few. Open your eyes you'll find many. Truly itself most of the times is not written with the real truth in it which is why is gets converted to 'truely'!

I've noticed these issues mainly with Indian brands. Spelling and grammatical mistakes darken the image of the brand. They act as blunders! The mistakes in offer letter or relieving letter still are restricted to your people network. But remember web is open for all!!

Disclaimer: I apologize in case the images posted in my blog resemble(or are actually from) website which you own. They are taken just as examples and not with the intention of maligning image of any website/brand. 

Wednesday, 12 January 2011

Improved Event Management with HTML5

We are strengthened with powerful event management in  HTML5. I especially loved the mouse events. Scroll the wheel of mouse and attach a todo with onmousewheel. This works great when there is no vertical scrollbar in page. If you've both- functionality on wheel scroll as well as scrollbar, behavior may not be as per your expectation. To know whether mouse was scrolled backward or forward use wheelDelta attribute. onscroll is fired when element's scrollbar is scrolled, say as in case of textarea or document. You've got a bunch of events related with dragging of an element- ondrag, ondragstart, ondragend, ondragenter, ondragover, ondragleave, ondrop, uh....huge list! HTML5 promoting provision of drag-drop facilities, isn't it?

Till now I'd only body's onload at rescue. HTML5 is pampering me with choice- onbeforeonload, onerror. I can even trap the changes made to local or session storage. localStorage.setItem(), removeItem(), clear() will fire onstorage event- but of course these should mean 'changing' the earlier values! Other document events include printing- onafterprint and onbeforeprint, visibility- onpagehide and onpageshow, onhaschange, onredo, onundo, onoffline, ononline, onresize, onpopstate (when history changes).

You can attach additional events to form now- oncontextmenu, onformchange, onforminput, oninvalid and oninput. HTML5 also wants us to give better experience with media- audio, video and images. There are number of events for play, pause, ready, duration change, volume change, progress, wait, stalled, suspend, error and many more.

Getting ready to give better user experience?

Lessons from The Social Network

Indeed one of the top-class movies of 2010- The Social Network...a must watch for entrepreneurs! Lots of (startup) lessons get conveyed thru it.


Idea does matter, but success is not just about the idea. Also no one is owner of an idea. It is the time to market of its implementation that matters. You cannot keep idea as a secret of course, since you've to get work done and those working on it need to know the functionality. The ConnectU founders had brilliant idea with them but had a couple of programmers before Mark who had worked and left half-way. On the other hand it was Mark who worked almost non-stop. When others were walking he was running, when other were partying he was coding! It is the fast and aggressive nature that comes contributed to huge success in a short time. Undoubtedly certain things take time to develop and come to market, but there are some other things which must come to market fast and hence grab the right time. Despite the fact that your product need not be first in market, the ones released first tend to gather more crowd because of its novelty!


There are times when your presence will matter even though you don't have real work on your plate. Had the CFO been with the company when company shifted its base, he wouldn't have taken aback with numerous surprises! It is not for being skeptical about your partner that you should maintain your presence!!


On legal front there are n number of lessons- do not keep anything orally, have it documented may it even be a short contract. Your signature holds tremendous weightage- do not sign anything blindly, read carefully before signing. Consider paying anyone in equity as the last option.


The creativity of thinking has to come into action. You'll have to come out of your (assumed)limitations which are mostly rooted in mind. Push your boundaries, dream, believe. So get cracking with your idea.... 

Tuesday, 11 January 2011

Mentors for Entrepreneurs

Are mentors really required for entrepreneurial business? Frankly speaking yes, though nothing hard and fast about this requirement. It is always good to consult a person experienced in the field in which you are a newbie. So why not take advantage of the experience! You need not go through the same hurdles again.

We are usually scared to share something internal with a third party. We never know how that person can misuse that info. So for sure your mentor should be someone whom you can trust. A mentor should be someone without any selfish motive behind mentoring. Another important aspect is mentor should act as a person being consulted for opinion, but should not impose his own decision. If mentor is forcing his decisions, both of you might be seen going in different directions.

We are already tight on budget...do we have to even pay to mentors? Yes or even no. I've seen some people acting as mentors merely because they want young entrepreneurs belonging to their college flourish and grow well. Such mentors are usually the ones who have taken retirement from work, of course retired and not tired! Such folks you'll find only through alumni or network connections. Very rare to find though! Other set of mentors- professional consultants and mentors. They might ask for stake in your company or cash. You can find them through sites and consulting firms. This kind has its own advantage- professional relationship!

Having a mentor though is not a key to success, it is just a plus. Someone with different perspective (different because he is in not in the same position or relation with the company as you are) can prove to be useful. Despite it is ultimately you, the entrepreneur who will make or break things, the value of a business mentor cannot be ignored!

Monday, 10 January 2011

HTML5: Offline SQL Database

HTML5: Offline SQL Database

HTML5 solves the problem of building offline apps by providing support for SQLite at the browser level. The main focus however is not merely to create offline apps, since the applications which don't require internet connection or desktop apps have been there in existence for decades and don't require to be migrated to browser level. The main purpose of this feature is to add offline flavor to the existing online apps!

Before HTML5 got introduced there were applications using Flash, Java Applets, Google Gears etc for making it accessible in the offline mode. But frankly speaking it was a pain for developers as well as users to deal with all kinds of plugin-based storage and/or use browser specific storage techniques.

Thanks to building it on top of SQLite as it is open-source and most of the application developers are very much familiar with the syntax!

Here are a few simple yet powerful code snippets:


//Create Database
documentManager.webdb.open = function() {
 var dbSize = 5 * 1024 * 1024; // 5MB
 documentManager.webdb.db = openDatabase("DOCUMENT_MASTER", "1.0", 
            "Document Manager", dbSize);
}


//Create Table
documentManager.webdb.createTable = function() {
 var db = documentManager.webdb.db;
 db.transaction(function(tx) {
  tx.executeSql("CREATE TABLE IF NOT EXISTS document_manager(
      ID INTEGER PRIMARY KEY ASC, doc_name TEXT, title TEXT, 
      doc_description TEXT, doc_category TEXT, 
      added_on DATETIME)", []);
 });
} 


//DB Transaction 
documentManager.webdb.addDocs = function(title,doc_description,doc_category) {
 var db = documentManager.webdb.db;
 db.transaction(function(tx){
 var addedOn = new Date();
 tx.executeSql("INSERT INTO document_manager(....,title, 
   doc_description, doc_category, added_on) VALUES (?,?,?,?,?,?,?,?)", 
    [...., title, doc_description, doc_category, addedOn],
     function() {
      documentManager.webdb.getAllDocs(loadDocuments);
     },
     documentManager.webdb.displayErrorMessage);
 });
} 
 

Sunday, 9 January 2011

HTML5- Welcome Web Storage

Till web storage was introduced I'd not even thought that something so lightweight as web storage will come up for client side storage. Thanks to HTML 5, we can now say bye to cookies.

It comes as localStorage and sessionStorage, similar in behavior(and methods) but differing in their lifetimes. Key-value pairs are stored where key is a string. Values should be serialized before storing which can be done using JSON.stringify() while deserialized using JSON.parse() method. sessionStorage limits the storage till the session exists. If a site stores something in your localStorage, the data is available even when you next time visit the site.


localStorage["path"] = viracct.png;
Or
localStorage.path = viracct.png;

You can use other attributes of Storage object as well like- length: total key-value pairs currently in storage, key(n): name of nth key. getItem(key), setItem(key, value) and removeItem(key) can also be used for storing, retrieving and removing from storage like:


sessionStorage.setItem('blogUrl','http://viracct.blogspot.com/');

url=sessionStorage.getItem('blogUrl');

sessionStorage.removeItem('blogUrl');

null is returned when either a mentioned key does not exist while calling getItem() or removeItem(), or when n exceeds total number of pairs in key(). To empty the complete Storage use clear().























In Developer Tools under 'Storage' tab you can view all the key-value mappings stored (shown in diagram above). On left hand side click on 'Local Storage' or 'Session Storage' to see the mappings under the respective Storage. To delete a pair, select it by clicking and press the delete cross mark. You can select multiple rows at a time for deletion.

Isn't it indeed nice?

Friday, 7 January 2011

Observer Design Pattern

Observer Pattern Comes Under the Behavioral Patterns.


// Observer interface is available under java.util package.
// This interface has update method which gets called as soon
//as the status of Observable class changes and it
//notifies the observers.
package oops.observer;
import java.util.Observable;
import java.util.Observer;
public class ProjectLead implements Observer{
@Override
public void update(Observable arg0, Object arg1) {
System.out.println(this.getClass().getSimpleName() +" received updates from    "+arg0.getClass().getSimpleName() +" "+arg1);
}
}



//Another observer for project development.
package oops.observer;
import java.util.Observable;
import java.util.Observer;
public class Client implements Observer {
@Override
public void update(Observable arg0, Object arg1) {
System.out.println(this.getClass().getSimpleName() +" received updates from "+arg0.getClass().getSimpleName() +" "+arg1);
}
}



//Developer : does the regular work and notifies observers.
//Observable class belongs to java.util package and has two
// important methods : setChanged and notifyObservers
package oops.observer;
import java.util.Observable;
public class Developer extends Observable {
private String name;
public Developer(String name){
this.name = name;
}
public void doRegularWork() {
workOnAssignments();
sendUpdates();
}
private void workOnAssignments() {
// TODO :
}
private void sendUpdates() {
setChanged();
notifyObservers(name);//NOTE : notifyObservers without argument is also available!
}
}



//ProjectDevelopment : A framework to track the development progress.
package oops.observer;
public class ProjectDevelopment {
public static void main(String[] args) {
Developer dev = new Developer("Anuja");
ProjectLead lead = new ProjectLead();
Client client = new Client();
dev.addObserver(lead);
dev.addObserver(client);
dev.doRegularWork();
}
}

Thursday, 6 January 2011

Chrome as a Container

Google Chrome has broken the bars of predefined area of browsers which was till now just for browsing internet data. Now you can view data while you are offline, which is powered by localstorage of Chrome. So visualize it as a browser with its own mini-database. There are n number of Chrome extensions and apps being developed. You'll get the idea by looking at the vastness of Chrome web store.


Let us look at some of the features that Chrome provides. Press Shift-exc and you'll see task manager related to Chrome. You see which tab/app is occupying how much of memory. If one tab is not responding do not end the complete browser, just that very tab!Similar is the case with Windows task manager- each Chrome tab appears as different process. The url box at the top of browser itself works as a search box. This frees the browser from reserving area for 2 textboxes. You may argue that even 2 boxes are fine for you. But don't you want camera, radio, music player etc. all in your mobile.........despite the fact that there are separate gadgets available for separate functionalities.


You can create desktop/start menu shortcut for any of the web pages. Isn't it very much like the folder/file feature? And of course a very important feature to mention- support for HTML5! This gives user the experience of 3D effect in everything.


So change your persective of Chrome...if you still think it anything lesser than a container! Interested in knowing more features of Chrome?....Stay tuned with upcoming posts.

Wednesday, 5 January 2011

Understanding Visitor Pattern

Visitor pattern comes under the Behavioral Patterns.


//Visitor Interface
package oops.visitor;
public interface Visitor {
void visit(Section section);
}



//Implementation for Visitor Interface
package oops.visitor;
public class NewEmployee implements Visitor {
public void visit(Section section) {
section.getRequiredInfo();
}
}



//Section Interface representing various deptts of a Company
package oops.visitor;
public interface Section {
void getRequiredInfo();
}



//HR dept
package oops.visitor;
public class HR implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//Accounts dept
package oops.visitor;
public class Accounts implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//Admin dept
package oops.visitor;
public class Admin implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//PD dept
package oops.visitor;
public class PD implements Section {// Product Development Section
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



// Company : A container for various deptts
package oops.visitor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Company {
private List departments = null;
public void accept(Visitor visitor) {
List deptts = getDepartments();
for (Iterator iter = deptts.iterator(); iter.hasNext();) {
Section dept = (Section)iter.next();
visitor.visit(dept);
}
}
public List getDepartments() {
if (null == departments) {
departments = new ArrayList();
departments.add(new Accounts());
departments.add(new Admin());
departments.add(new HR());
departments.add(new PD());
}
return departments;
}
public void setDepartments(List departments) {
this.departments = departments;
}
}



//Main class where NewEmployee visits the Company
package oops.visitor;
public class VisitorPatternEx {
public static void main(String[] args) {
NewEmployee employee = new NewEmployee();
new Company().accept(employee);
}
}

Monday, 3 January 2011

Are We Creating Managers and Not Leaders?

These days industries are heavily managed and poorly led. May be it is because of predefined criteria for choosing managers which are usually- number of years of experience, some management related certification, number of years with a company to go up the hierarchy, and not from their leadership skills. This has got so much ingrained that importance of leaders is hardly ever realized and raises question do we even require a leader!

Managers are in place for following processes. This includes getting work done from subordinates in a defined time and methodology. Subordinates do listen to them. But that does not mean that subordinates are happy accepting and doing what has been instructed by their managers. On the contrary people follow the leader voluntarily and happily accept or question their leaders. This relation between leader and followers is of course two ways and the 'people binding' bonds are strong.

Look at most of the people around you at your workplace. Most of them you'll find whining and cribbing. This would not have been the case if real leaders would have played roles of managers (of course there is a small subset of folks who have the habit of cribbing and hence will crib anywhere and forever!).

If we look at real leaders we'll notice they never tell the dos and don'ts. In fact they themselves are the icons whom others follow. A person cannot become a leader just by doing some certification or course. At the most the dormant leader in a person can be awakened. A good leader inspires, motivates and drives others.

Will the industry not benefit if leaders become the managers? Or do we require mere managers and not leaders?

Sunday, 2 January 2011

Factory Design Pattern

Factory pattern is one of the Creational Patterns.
Consider the following EmployeeFactory class which has a method called getEmployee (This method takes two arguments employeeType and employeeName and based on that it creates and returns appropriate Employee class.):


package oops.factory.pattern;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class EmployeeFactory {
private static Map employeeTypesMap = new HashMap();
static {
employeeTypesMap.put(Employee.SOFTWARE_ENGINEER, Developer.class);
employeeTypesMap.put(Employee.MANAGER, Manager.class);
employeeTypesMap.put(Employee.ARCHITECT, Architect.class);
}
public static Employee getEmployee(String employeeType, String employeeName) throws EmployeeCreationException{
Class class1 = employeeTypesMap.get(employeeType);
Constructor constructor;
try {
constructor = class1.getConstructor(String.class);
return (Employee)constructor.newInstance(employeeName);
} catch (SecurityException e) {
throw new EmployeeCreationException(e);
} catch (NoSuchMethodException e) {
throw new EmployeeCreationException(e);
}catch (IllegalArgumentException e) {
throw new EmployeeCreationException(e);
} catch (InstantiationException e) {
throw new EmployeeCreationException(e);
} catch (IllegalAccessException e) {
throw new EmployeeCreationException(e);
} catch (InvocationTargetException e) {
throw new EmployeeCreationException(e);
}
}
public static void main(String[] strAr){
Employee emp = null;
try {
emp = EmployeeFactory.getEmployee(Employee.SOFTWARE_ENGINEER, "Ranjan Kumar");
} catch (EmployeeCreationException e) {
e.printStackTrace();
}
if(emp instanceof Developer)
System.out.println("Developer found!!!");
}
}



package oops.factory.pattern;
public interface Employee {
//By default interface fields are public static and final. Hence no need to explicitely declare it with these keywords.
String SOFTWARE_ENGINEER = "Software Engineer";
String LEVEL_SE = "SE Level";
String MANAGER = "Manager";
String LEVEL_MANAGER = "Manager Level";
String ARCHITECT = "Architect";
String LEVEL_ARCHITECT = "Architect";
//By default interface methods are public and abstract. Hence no need to explicitely declare it like that.
String getName();
String getDesignation();
String getLevel();
}



package oops.factory.pattern;
public class Developer implements Employee {
private String name;
public Developer(String name) {
this.name = name;
}
@Override
public String getDesignation() {
return SOFTWARE_ENGINEER;
}
@Override
public String getLevel() {
return LEVEL_SE;
}
@Override
public String getName() {
return name;
}
}



package oops.factory.pattern;
public class Manager implements Employee {
private String name;
public Manager(String name) {
this.name = name;
}
@Override
public String getDesignation() {
return MANAGER;
}
@Override
public String getLevel() {
return LEVEL_MANAGER;
}
@Override
public String getName() {
return name;
}
}



package oops.factory.pattern;
public class Architect extends Developer {
// You will have to define this constructor. Don't you Agree?
public Architect(String name) {
super(name);//Cool
}
@Override
public String getDesignation() {
return ARCHITECT;
}
@Override
public String getLevel() {
return LEVEL_ARCHITECT;
}
}


If you understood the classes defined above, you understood factory design pattern :). This pattern is very much userful when you have objects having some of the properties in common. So user can instantiate classes based on the data he has without knowing which class he needs to instantiate. In the example explained above user/caller (main method) need not know about what a Developer class is etc etc.