façade pattern

Hiding the complex code behind a simple interface.

Think of using an electric toothbrush that has a simple on/off button on the plastic case and a complex motor/battery/charger functionality inside.


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

Java: Date manipulation

The method below that gets current date, returns the next exact hour (i.e. 12:00:00:00).
Notice ".add" method.

public static Date getNextHour(Date date)

   

{

Calendar cal = new GregorianCalendar();

  cal.setTime(date);

  cal.add(Calendar.HOUR, 1);

  cal.set(Calendar.MINUTE, 0);

  cal.set(Calendar.SECOND, 0);

  cal.set(Calendar.MILLISECOND, 0);

  Date time = cal.getTime();

 

  return time;

    }

Single Purpose Principle

This is one of the most important principles in clean programming.

It applies to:
  • Interfaces
  • Classes
  • Methods
  • Whole Modules
The piece of code should be named to precisely reflect the functionality in contains and it should be developed,  and subsequently extended, to preform ONLY the functionality intended.

If there is a need to add different functionality, a new piece of code should be refactored out.





Ambiguous Method Result

 /**  @deprecated  TODO: this bad code, do not use it */

public TeamGame fetch(Game game)

{

Query query = getSession().createQuery("select gameSummary from TeamGame gameSummary where teamGame.game.id = " + game.getId());

List list = query.list();

if (list != null && list.size() > 0) { return (TeamGame) list.get(0);  }

return null;

}

Use static methods whenever possible

Avoid over-using class variables, they are appropriate for log, DAO, service and other classes that are used in most methods.
Before (we are not sure where winnerTeamGame is coming from):

private String getDayPlaceList()

{

Game game = winnerTeamGame.getGame();

String isDayOrNight = ((getHour(game)) > 17) ? " night at " : " at ";

return (getDayOfWeek(game.getStartDate()) + isDayOrNight + game.getLocation());

}

After:

 private static String getDayPlaceList(TeamGame teamGame)

{

Game game = teamGame.getGame();

String isDayOrNight = ((getHour(game)) > 17) ? " night at " : " at ";

return (getDayOfWeek(game.getStartDate()) + isDayOrNight + game.getLocation());

}

SQL: CONCAT(), GROUP BY and DATE formatting

SELECT
(CONCAT( MONTH(date_time), "/", DAYOFMONTH(date_time) ,"/", YEAR(date_time))) as date,
COUNT(*) as visits
FROM metrics_session m 
GROUP BY YEAR(date_time), MONTH(date_time), DAYOFMONTH(date_time);



"Did you find this post useful? Sponsor marathon for cancer"

Programming visualization exercise

Imagine that you could walk inside the code as if it was a city street...

The "if()" statements would be the corners where you make decisions where to turn.

The classes would be the buildings and the method interfaces the doors you would enter.

The bags you carry into these doors would contain the objects you need.

Oh, and the "Windows" would be the "exceptions" you would use to jump out off when everything goes bad.

Sorry, I had to put it in, I am a Mac guy.

iPhone and Android

The iPhone 2.0 has been out for a second day and so is the new set of the 3rd party applications. 
I tested a few of them, but I will mention about that later...

First, I want to thank Google for creating Android. 

Because of Android we have iPhone SDK, even if this is not 100% true, at least the prospect of thousands of Android developers made it easier for Apple to release it.  
We also now have iPhones that are half the original price ($199) - probably to win the public before public learns that there is a real competition out there. 
Most of all the intense competition will force both sides to strive for better solutions, and both of the sides win (sorry Winblows Mobile, Palm OS, CrackBerry you don't count anymore).

Why Android?

1) Java API - that fact alone wins Android for me, and thousands others, Apple really mess me up with Objective-C. Hear me out Apple: Java API, and if you want a clean, modern, dynamic language, use Groovy for JVM.
2) Linux core for stability and ability to run on multiple platforms (personally I love OS X UNIX core)
3) great user interface; mostly rip off from iPhone, but I cannot blame them -- there is nothing better out there.

I have a feeling that in some unexpected way there will be a bridge between the two, most likely Android Java apps running on top of iPhone (Java VM coming to the phone near you very soon).

Now, back to iPhone 2.0.

Steve Jobs is a very smart guy (OK, that is a severe understatement). He wanted to control three things, of which he mentioned only two: the quality of hardware and software.
Since Android will not control the hardware quality (open source), I expect that it will be hit-or-miss, some good, some bad. Just like Linux. I hope the big handset manufacturers (Nokia) offset the bad ones.
This brings me to the second control point, the software. The software from Apple is amazing, I had Treo before (Palm OS yuck!). 
As I said before I downloaded a 3rd party AIM chat application, one of the most downloaded today and it crashes for most users!!! 
This is precisely why Steve Jobs wanted iPhone to have Apple apps only, for the initial launch, smart guy. Android will have no control on quality of the apps, but hopefully they will get the market share.

Then there is the 3rd thing that Steve Jobs wants to control. Money. Almost every piece of good software written for iPhone (except for jailbreak.app) makes money for Apple directly (30% of the cost) or indirectly (iTunes traffic). Google may make more advertising money, but there is no money for them in Android, it is open source, so people can write and install their apps without asking Google, or anybody else.

I think it is worthwhile for us Java developers to learn Android, meanwhile I hope this article is formatted well on your iPhone.





Book "ProBlogger" by Darren Rowse and Chris Garrett

Even if this is not strictly a technology book, since most of us "geeks" are bloggers, I highly recommend it.
I've been blogging for the most of the last 7 years, still I was able to learned many useful tips from this book that help me put some direction into my blogs.




click me to shop

MYISAM vs. InnoDB

Recently, I have to investigate differences between MYISAM and INNODB:
MYISAM: 
does not support transactions rollback and row level locking. 
INNO DB: 
supports above features as well as ACID (Atomicity, consistency, isolation, and durability).
To convert from MyISAM to InnoDB use script:
SET NAMES utf8; SET FOREIGN_KEY_CHECKS = 0; ALTER TABLE table_name1 TYPE = innodb; ALTER TABLE table_name2 TYPE = innodb; SET FOREIGN_KEY_CHECKS = 1;

Java: generic replace all method

public static String replaceAll(String phrase, String token, String replacement)

    {

if (phrase == null || phrase.length() == 0)

    return phrase;

if (token == null || token.length() == 0)

    throw new IllegalArgumentException("The token you are looking for cannot be empty.");

if (replacement == null)

   replacement = "";

int start = phrase.indexOf(token);

if (start == -1)

    return phrase;

log.warn("Phrase: \"" + phrase + "\" token found at: " + start);

int end = start + token.length();

phrase = phrase.substring(0, start) + replacement + phrase.substring(end, phrase.length());

phrase = replaceAll(phrase, token, replacement);

return phrase;

    }

Hibernate: disjunction

Junction junction = Expression.disjunction();

    junction.add(Expression.or(Expression.eq("plurality", phrase.getPlurality()), Expression.eq("plurality", Constants.PHRASE_NEUTRAL)));

    dcPhrase.add(junction);

Hibernate: detached criteria

DetachedCriteria dcSport = DetachedCriteria.forClass(PhraseSport.class);

    dcSport.add(Expression.eq("sport.id", phrase.getSportId()));

    List sports = hibernateList(dcSport);

SQL: update statment

To update a column in an sql table:
update  team set is_plural = true;

JUnit class not found (not loading) in Eclipse


I get below error when I run jUnit test class n Eclipse:

Class not found com.ucc.csd.server.PhraseGeneratorTest
java.lang.ClassNotFoundException: com.ucc.csd.server.PhraseGeneratorTest
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:316)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:425)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:445)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Solution:
1. Right-click on the test class, go to "run as" option
2. Select "classpath" tab 
3. Select "user entries" option.
4. Click advanced.
5. Select "add folder" and click "Ok"

Sometimes you may have to right-click on project -> properties -> uncheck the default output directory. Then clean your project and run your jUnit tests.





Mysql installation on Mac

To properly install mysql on your Mac computer:
- Remove /usr/local/mysql directory (if you have attempted to install mysql previously).
 
- Remove /Library/receipts/mysql directory.
- Download mysql in e. g. /opt/mysql directory. Navigate to and install  mysql-5.0.51b-osx10.4.

Hibernate equals(); hashCode(); toString() methods

Implementing the interface below in all model classes.

http://www.hibernate.org/109.html

package com.ucc.csd.server.model;

public interface HibernateModel
{
    public int hashCode();
    public boolean equals(Object otherObject);
    public String toString();
}



SVN: commands

To check out a project from a given svn remote repository:
svn checkout svn://**.***.*.**:port# projectName
workspace/$ svn checkout svn://x.240.1.10:3692/CSD csd
A    csd/pom.xml
...