Archive

Archive for the ‘Miscellaneous’ Category

Case Study: Factory Design Pattern

17 December 2013 11 comments

I had a job to check our project code quality. And have to report it back to my team leader for any obstacle that i found in the project.  I found a lot of leaks and i think would be good to be discussed on the blog. Not to mock the author, but to learn and improve ourselves together.

Like this code, this is the part that i found in our code.

 public ContactInfoBean(final Reseller resellerInfo) {

        switch(resellerInfo.getType()) {

            case PROGRAM_CONTACT:

                readExecutiveInfo(resellerInfo);

                break;

            case FILE_CONTACT:

                readOperationalInfo(resellerInfo);

                break;

            default:

                break;

        }

    }

The code works fine, and do its job pretty well. But some problem will appear by using this code-style. This class will grow tailing the biz changes, as usual, the bigger one class, the “merrier” to maintain it is. And most likely this class, will be having more than one purpose, can be called low-cohesion.

Better OOP Approach

Well the better approach for the case above would be using the Factory Design Pattern.  We can let the factory of  READER to generate every single instance according to their type. It would be easier to grow the instance type, since we just need to create a new class and do a little modification in the Factory class. The caller class, wont grow and will stand still at its current shape.


public interface InfoReader {

	public void readInfo();

}

public class ExecutiveReader implements InfoReader {

	public void readInfo() {

		// override

	}

}

public class OperationalReader implements InfoReader {

	public void readInfo() {

		// override

	}

}

And The Factory

public enum ReaderType {
PROGRAM_CONTACT, FILE_CONTACT
}

 

public class InfoReaderFactory {

	public static InfoReader getInstance(ReaderType type) {

		InfoReader instance = null;

		switch (type) {

		case PROGRAM_CONTACT:

			instance = new ExecutiveReader();

			break;

		case FILE_CONTACT:

			instance = new OperationalReader();

			break;

		default:

			throw new IllegalArgumentException("Unknown Reseller");

		}

		return instance;

	}

}

And now The Caller


InfoReader reader = InfoReaderFactory.getInstance(resellerInfo.getType());

reader.readInfo();

The Benefits

With the Factory Design Pattern to handle this case, we can achieve some benefits,

  • Specifying a class for one task, means, easier to maintain since one class is for one purpose only (modularity/High Cohesion). i.e: Operational Reader is only to read data for Operational only, no other purpose. Just in case, one day in the future we need another Reader (say: NonOperationalReader). We just need create a new Class that extends (or implements) the InfoReader class and then we can override our own readInfo() function. This Caller class will have no impact. We just need to do some modification in the Factory code (and the Enum of course.
public enum ReaderType {
PROGRAM_CONTACT, FILE_CONTACT, NEW_READER
}

 

public class InfoReaderFactory {

	public static InfoReader getInstance(RaederType type) {

		InfoReader instance = null;

		switch (type) {

		case PROGRAM_CONTACT:

			instance = new ExecutiveReader();

			break;

		case FILE_CONTACT:

			instance = new OperationalReader();

			break;

		case NEW_READER:

			instance = new NonOperationalReader();

			break;

		default:

			throw new IllegalArgumentException("Unknown Reseller");

		}

		return instance;

	}

}

  • Higher Reusability of Parent’s Component (Inheritance): Since we have parent class (InfoReader), we can put common functions and thingies inside this InfoReader class, and later all of the derivative classes (ExecutiveReader and OperationalReader) can reuse the common components from InfoReader . Avoid code redundancy and can minimize coding time. Eventhough this one depends on how you do the code and cant be guaranteed 😀

But, It’s Run Perfectly, Should We Change It?

Obviously the answer is big NO. This is only the case study and for your further experience and knowledge. OOP is good, do it anywhere it’s applicable. But the most important thing is, if it’s running, dont change it. It would be ridiculous if you ruin the entire working code just to pursue some OOP approach. Dont be naive also, no one can achieve the perfect code. The most important is we know what is the better approach.

This blog has some modifications and improvements caused by some comments in here. Personally, thanks for great input so i can keep the quality of this post.

Advertisements
Categories: Java, Miscellaneous Tags: , , ,

Tremendous Moment of NamingException

17 March 2012 Leave a comment

These several months, has been tremendous year for me and my NamingException blog. Last year, around October 2011, ive been asked to be contributor of Java Code Geeks, and not only that. According to my private email with JCG founder, it turns out i’m the only and the first Indonesian Contributor at that time.

And now, in March 2012, ive been asked by Curator of Dzone.com for them to repost my blog content at their JavaLobby lounge and got an offer to join their Most Valuable Blogger (MVB) program. Of course, i accepted that offer.

Too bad, i havent updated my NamingException yet for several months, not because i dont want to, and im not too busy too, but honestly i have no idea about new and quality topic. I dont want my blog only act as “reposter” site, just to fulfill my post-target, for me, quantity is important but quality is still at the top.

If you have any idea to be discussed about, please let me know and help me to make this NamingException better and better in quality. I expect no commercial reason in here, all of my post are always and always will free and open-source. Never did, never do and never will about money. Let share about our skill and experience, from community, by community and to community. Let the benefit come to us by itself 🙂

Categories: Miscellaneous

How Easy to Make Your Own Twitter Client Using Java

12 September 2011 53 comments

Got inspired by my friend, whom built his own Twitter client for his company’s client. So, i tried to build one using Java. And im surprised that how easy to make Twitter client, of course i still use third-party API to make my job easier.

This simple client will only have 2 purposes: reading timeline and post status. Dont worry, you can expand this application later, it’s simple and easy once you have your app got authorized by Twitter.

First of all, you have to go to official Twitter Developer Registration at https://dev.twitter.com/apps/new , and register your application detail there. For this blog purpose, i will create a new application that called “Namex Tweet for Demo“. It’s simple, just fill in some required data and voila it’s done in seconds.

After you passed this registration step, dont forget the most important things in here are these Consumer and Consumer Secret key. Just say, it’s a signature to let Twitter knows your application. These things will be hardcoded at your application. In here, my Consumer key is DXjHgk9BHPmekJ2r7OnDg and my Consumer Secret key is u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0 . Dont use these keys in your application, it’s useless because i will turn off the application as short as this blogging purpose done.

consumer key

And after registration step dont forget to visit Setting page and adjust setting for your application access.

tab setting

app type

Choose Read, Write and Access direct messages to get your application at full functional. you now can download additional java API for twitter, im using Twitter4J . Here, you have to download several jars,

  • twitter4j-async-<a.b.c>
  • twitter4j-core-<a.b.c>
  • twitter4j-media-support-<a.b.c>
  • twitter4j-stream-<a.b.c>

Notes: Dont use twitter4j-appengine.jar, it will cause your application thrown to exception on authorizing process.

In my version a is 2, b is 2 and c is 4. So it would look like twitter4j-async-2.2.4 etc. After these jars being downloaded at your machine, our downloading job has not done yet. We still have to download Apache Commons Codec as Twitter4J dependencies. After all of the jars downloaded, now we can start to code. Open your fave IDE and start it with me.

package com.namex.tweet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class NamexTweet {
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET = "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
	RequestToken requestToken = twitter.getOAuthRequestToken();
	System.out.println("Authorization URL: \n"
		+ requestToken.getAuthorizationURL());

	AccessToken accessToken = null;

	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	while (null == accessToken) {
	    try {
		System.out.print("Input PIN here: ");
		String pin = br.readLine();

		accessToken = twitter.getOAuthAccessToken(requestToken, pin);

	    } catch (TwitterException te) {

		System.out.println("Failed to get access token, caused by: "
			+ te.getMessage());

		System.out.println("Retry input PIN");

	    }
	}

	System.out.println("Access Token: " + accessToken.getToken());
	System.out.println("Access Token Secret: "
		+ accessToken.getTokenSecret());

	twitter.updateStatus("hi.. im updating this using Namex Tweet for Demo");

    }

    public static void main(String[] args) throws Exception {
	new NamexTweet().start();// run the Twitter client
    }
}

Compile and run the code, it will create permission for “Namex Tweet for Demo” to be linked with your Twitter account. Just open the “Authorization URL” shown at the screen and input the PIN shown by the website. Your application will send back the pin to Twitter, if it’s match your account will be linked with this new application and you can see you just posted a new status using “Namex Tweet for Demo “. Congratulation!

Notes: Authorization URL and PIN will generated differently each time it’s run.

auth url

auth pin

update tweet

In here you can see, we input no username and password of Twitter account but we can use our account within application. Yeah it’s possible because of OAuth . It “transformed” password-input-process to sending-receive-token. So dont worry, Third-party Twitter client application cant read and store no password of your Twitter account. In simple, it’s safer and prevent password thieving.

Now we still have a tiny problem, at this point, your program still need to open Twitter’s website and input pin back to the application. So, maybe you are asking on the cloud, do i need this annoying authorization on the future ? well, gladly the answer is NO. At the time your app being authorized by Twitter, you have no use to re-authorize it again — with a simple note you have to save the Access Token and Secret Access Token . What the hell is that, how could i get that. Well, you have it already, see the image below, i put it in a big red rectangle so it will be more eye-catchy. In here, our token is and our secret token is. These 2 tokens have to be saved somewhere, you can choose your own method to save it: Persistence, CSV, DBMS, etc. It’s all up to you.

access token

So, i saved the tokens! How do i reuse it? It’s simple, see below code. It’s how to use your tokens, so you wont have the re-authorization process again. Try to post and read your timeline now.

package com.namex.tweet;

import java.io.IOException;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class NamexTweet {
    private final static String CONSUMER_KEY = "DXjHgk9BHPmekJ2r7OnDg";
    private final static String CONSUMER_KEY_SECRET = "u36Xuak99M9tf9Jfms8syFjf1k2LLH9XKJTrAbftE0";

    public void start() throws TwitterException, IOException {

	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);

	// here's the difference
	String accessToken = getSavedAccessToken();
	String accessTokenSecret = getSavedAccessTokenSecret();
	AccessToken oathAccessToken = new AccessToken(accessToken,
		accessTokenSecret);

	twitter.setOAuthAccessToken(oathAccessToken);
	// end of difference

	twitter.updateStatus("Hi, im updating status again from Namex Tweet for Demo");

	System.out.println("\nMy Timeline:");

	// I'm reading your timeline
	ResponseList list = twitter.getHomeTimeline();
	for (Status each : list) {

	    System.out.println("Sent by: @" + each.getUser().getScreenName()
		    + " - " + each.getUser().getName() + "\n" + each.getText()
		    + "\n");
	}

    }

    private String getSavedAccessTokenSecret() {
	// consider this is method to get your previously saved Access Token
	// Secret
	return "oC8tImRFL6i8TuRkTEaIcWsF8oY4SL5iTGNkG9O0Q";
    }

    private String getSavedAccessToken() {
	// consider this is method to get your previously saved Access Token
	return "102333999-M4W1Jtp8y8QY8RH7OxGWbM5Len5xOeeTUuG7QfcY";
    }

    public static void main(String[] args) throws Exception {
	new NamexTweet().start();
    }

}

post again

tl

Now our simple Twitter application has been -could be- done, we can read and post to Twitter. Of course, many things still on the task list if you want to make it professionally and -perhaps- sell it. A nice UI, reading and sending Direct Message, Searching Users, Follow and Unfollow. I put these jobs on your shoulder, cause i just want to share it’s easy to make a Twitter client and i hope this short tutorial can help you in developing Twitter client using Java.

Happy Code All !

Categories: Java, Miscellaneous Tags: , ,

Learn fundamental of Java ? Use ancient JDK

Many Java developers are categorized as a good one in developing program using Java. But, i met so many of them are weak and less in java fundamentals itself. They can develop new program easily. But when i asked, what happening in background of java itself. Only few of them can explain it goodly and in appropriate way. Start to investigate what happening with them, reflecting they are not a newbie as Java Developer, 2 or 3 years in field experience.

After some research about situation and background of few developers. I can pull out my own conclusion, they are facing some fundamental problems because they are started to code using JDK 1.5, i classified this version as modern JDK. In 1.5 and later there are boxing-unboxing feature to make easier relationship between primitive and its wrapper, foreach loop statement to make looping process simpler. We wouldn’t see those things in 1.4. In 1.4 we have to use primitive data types and the wrapper explicitly and we still have to do explicit type-casting instead of using foreach. In my simple words: “Almost everything run by write it!”.

I’m not saying here that manual is the best way to do everything, but i found many cases during my professional experience, that with manual ways, we can learn how one process in a code could be done and doing analytic about whats happening with the code.

For the simplest example, look at between 2 pieces of code.

  • int myNumber = new Integer(10);
  • int mySecondNumber = 10;

On JDK 1,5 those codes will produce exact results. Nothing error and nothing produce runtime  exception. I give simple question to some people that declared as Java Developer. Only few of them can give me satisfaction answer.

Now with JDK 1.4 one of those 2 codes will produce error. The first one will produce compilation error. Meanwhile with 1.5, the first one will run perfectly but the code will take some unnecessary processes, means the code will use some space of memory for useless thing.

And yet another example,

  • List<SomeClass> myList= new ArrayList<SomeClass>();
  • List mySecondList= new ArrayList();

Whats the difference between both lists? well the most common answer i got only, “You can use foreach for myList but not to mySecondList”, well the answer is right, i wont hesitate about that. But still, the answer i got wasn’t the answer that i looking for. I’m looking for deeper answer, fundamentally.

For the ancient one, i still give 1.4 my humble recommendation. Maybe it’s a little bias because i started my java code using 1.4, forgive me for this. And please dont take me wrong, i’m not saying that the latest JDK is bad or automatic process is bad. I believe in thought that Java Architects have done very good job by providing simplicity and easiness in use of Java. But still, responsibility to know Java in fundamental way itself still be ours.

So, if you want to know better about Java Fundamental, maybe you should try ancient JDK. Watch and learn the process. And spread your own knowledge.

Well, i wouldn’t give you the answer for the differences of my codes above. Let it be your tasks, considered this is your homework 🙂

And for the last, this article based on my truly experience so maybe the content wont fit you at all. Please share your own or give me correction if you are thinking my article is too cheesy, old-style or maybe too idealist. Im glad to read from you soon 🙂

Categories: Java, Miscellaneous

Dont be a Programmer, be a Consultant

29 March 2011 10 comments

So, what is the difference between them? well imagine the situation i had before. My boss told me to develop a system to retrieve CSV(Comma Separated Value) file that sent by another company. As a programmer, it’s nice and easy to do, the things i have to do are:

  1. Listening to the certain connection.
  2. Accept the file.
  3. Save the file.
  4. And done.

Easy and easy, right? but… as a consultant, i have to think more than those 4 steps. At least i still have many pre and postconditions, such as:

  • What if the connection isn’t established well?
  • What if the client is sending the wrong file?
  • What if the connection down meanwhile process is still on progress?
  • What if the client is sending the file twice?

What if, what if and what if. They are still many of Ifs available. Of course we cant handle all of the IF situations, but at least we prepared for common and certain problems already. We cant anticipated all of them, but we try to reduce the possibilities.

So, from my point of view, the huge and main differences between Programmer and Consultant are:

  • Programmer does ONLY the code, meanwhile Consultant has to be a solution maker.
  • Programmer is preparing for now situation, meanwhile, Consultant is preparing the ‘future’ condition and try anticipating a new born problem.
  • Programmer does the job with their technical skill, meanwhile, Consultant does it with combination of Technical Skill and Experience.
  • Programmer solve the task, meanwhile, Consultant solve the problem.

Easy to be a Programmer, you can learn it if you have a passion, patience, and practicing the programming language, but not all of us can be a good consultant, it need time and experience, sometimes the problem cant be solve with common and text-book based solution, sometimes we have to solve it (or patch it) with a tricky solution.

So, from now on, prepare and learn to be a Consultant, not only do the code but try to learn the problem with sense, feel, analyze and give solution for it.

Categories: Miscellaneous

Development Tools I Can’t Live Without

25 February 2011 Leave a comment

There are so many Software Development Tools that spread widely on the cloud, and these are my favourites. Im not mentioning they are the best, but they are fit me and i’m happy to use them in my daily professional life. If you have different opinion, so be my guess. 🙂


Integrated Development Enviroment (IDE).

Candidates: Eclipse, Netbeans and JBuilder.

Winner: Eclipse, eclipse is available freely on the cloud. It has so many plugins, start from various servers plugins, subversion integration, Reporting tools integration and still many more. And now it supports other languages too, such as PHP. Well frankly, i’m start my career with JBuilder as my escoter through the Java code while im a trainee, but lately i found the eclipse is the better solution compared to JBuilder. I use Netbeans several times found it good, but still eclipse is the most suitable for me, the UI, fonts, shortcut and plugins are so into my style.


Versioning Tool

Candidates: Microsoft Visual Source Safe (VSS) and Subversion (SVN).

Winner: SVN. Compared to VSS, SVN is free and open source, thats one point. The second point is, SVN can be installed on cross platforms, server on Linux and Client uses Windows, they are not a problem at all. If you asked me, i have no trust on Windows to handle my entire source codes, since it has so many vulnerabilities on security issues, such as: virus attack. Can you imagine, the whole project’s source code is vanished by a virus ? just in a second, your job will be gone by (almost) forever. The third point is, SVN can be accessed from many varians of clients, RapidSVN, TortoiuseSVN, can be integrated with Eclipse through plugin feature, and it can be accessed with Command Line Interface too, just in case you have no UI Manager installed.


Application Server

Candidates: Weblogic, Tomcat, Glassfish

Winner : Glassfish and Tomcat. On this category, i have double winners. Tomcat win because of the simplicity, it’s so easy to install and using it, even if you are still a green developer. If you just (keep in mind: JUST) looking for an application container server and you arent using many J2EE features, such as: JMS, Connection Pooling,etc. i would love to give Tomcat two thumbs up. BUT, if you are looking for a container server and have a need in using many J2EE Enterprise Server Features, use Glassfish, it’s free, open source, has so many users, easy to use, set up and to manage. Weblogic is a good (if not the best) application server that i had used before, but sometimes, i found it hard to use and expensive too to be use as production server, Weblogic trial version is free but only allow 5 concurrent users.


Database Engine

Candidates: Oracle, mySQL, Sql Server.

Winner: Nobody, each server has their own usage domain. Examples: If you looking for a free, cross-platform,easiness and liteness, use mySQL. If you are a Sql Server Expert and have support license of Sql Server and only use Windows OS, use Sql Server. If you looking for a huge features of DBMS Engines and when money isnt big problem for you use Oracle. So, i cant decided which one is the best, i use them all and found they have their own unique features depend on the case.


Plain Text Editor

Candidates: Notepad++, PSPad

Winner: Notepad++. Both are free, support plugins, and support programming language style highlighter. But i found PSPad works slowly when experiencing with huge size of text files, Log files for the example. Meanwhile, Notepad++ can open it faster (though not fast or fastest).

 


Database Designer

 

Candidates: Mysql Workbench, Software Ideas Modeler, Power Architect, Microsoft Visio.

Winner : Power Architect. It’s free, easy to use and cross platforms. Frankly, Workbench works greatly, but i found so many bugs on it and it only supports for the mySQL DBMS. So when i have to handling other DBMSs, it won’t work, for example:I can’t design table that handling Oracle’s Varchar2. So, i choose Architect as a winner. Software Ideas is great too, but i prefer Power Architect because of the taste of UI Flavour. And Visio, though many developers like it, i’m not a big fan of it.


PDF Creator

Candidates: Cute PDF Writer, Primo PDF

Winner: Cute PDF Writer. Though my main job is Software Developer, sometimes, i have to handling with documentation problem. Such as: Database Design, Source code documentation, and Coding Guideline. I think it would be nice and neat to give the document on PDF format, it can be opened cross platforms, from browsers and even from mobile devices. So I need the PDF Creator to give me a hand to create PDF documentation. I found Cute PDF is faster and more bug free rather than Primo PDF. I use Primo for the first time and got good impression on it, until my OS got crashed and became nag screen every time i tried to create a PDF, meanwhile with Cute PDF, i can create PDF smoothly.

 


File Merge and Compare

 

Candidates: Beyond Compare, WinMerge

Winner: WinMerge. Why WinMerge is my winner, it can be integrated into Subversion, so i can easily use WinMerge from inside the Subversion to determine the difference and do the merge between two files.

 


SSH Client

Candidates: Putty, WinSCP

Winner: WinSCP. Absolutely WinSCP is a winner. Nice GUI, easy to use, and can ‘translate’ the console view into nice UI experience. Though, i’m still looking for a better SSH Client, still i couldn’t found anything better.


Well, i think those are all. Based from my personal taste, those are the best and the most suitable for me. Please let me know if you have anything better or any disagreement.

Categories: Miscellaneous

Easter Egg in Java Class

12 October 2010 1 comment

In my post today, i’m sure all of you already know what is Java, maybe you know it better than me. But, have you already known about Easter Egg in Java ?  Well, this Easter Egg is easy to read. Just prepared all of these things:

  1. A .class file from Java compilation.
  2. Any Hex Editor, in this example im using HEX-ED, a freeware Hex Editor from http://www.nielshorn.net/prog/old/hexed/

Well, if you already have these, lets started with open your .class file with Hex Editor and see the first four bytes, it will show you the word CA FE BA BE.  Why and what is CA FE BA BE ? really, i have no idea, but presumably they had to pick something as their magic word to identify class files, and there’s a limit to how many Java or coffee related words you can come up with using just the letters A-F 🙂

Well, thats all for today guys, hope i can post more in a few days.

Categories: Miscellaneous