Dependency Injection- simplified

I heard this term ‘Dependency Injection’ (DI) a couple of months back, and since then it was at back of my mind and I was planning to read about it. It sounded like some mysterious concept, but it turned out to be a simple one.

DI (or Inversion of Control) is nothing but transferring responsibility of initialization of instance variable to the calling class. This helps in loose coupling and testing of classes.

A very good post on the topic:

http://jamesshore.com/Blog/Dependency-Injection-Demystified.html

Additional Info:
http://stackoverflow.com/questions/130794/what-is-dependency-injection

Using Reflection with Android

Faced an interesting problem today. In my android app I needed to show some random strings on the UI (textview).  So obvious solution was to add the strings in string.xml (for supproting i18n), and then fetch the text based on the random number generated.

textView.setText(R.id.text_1);

or if random number is 2

textView.setText(R.id.text_2);

and so on

I realized that only change happening is the last one digit, so this is a good candidate for using reflections.

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(field.get(null)));

But this actually gave an Exception for ClassCast, so I realized that field.get(null) is actually returning the resource Id (as shown in R.java class) instead of string value.

The fix found was to use getResources().getString(resource_id) to fetch the string from the resource id

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(getResources().getString((Integer)field.get(null)));

Isolation levels of a database

In my last post I talked about ACID properties of the database. Out of these, Isolation is one of the most important (and a bit complex) property as this makes sure that no “dirty-ready” occur. There can be various levels of database isolation.

1. Read Uncommitted: Lowest level of isolation, does not implement any checks, a transaction can read while other transaction is writing and hence dirty read can happen.

2. Read Committed. Reads only committed data. Handles dirty read problem. But say in same transaction, the data for a row in table is read multiple times, and if the data gets updated by some other transaction and committed, between the gap period of the two reads in this transaction, the transaction has read different data at different time intervals for same row.

e.g. select name from employee where id=10;

— do something which takes time

select name from employee where id=10;

commit;

The data can change between the two reads

3. Repeatable Reads: This solves the problem mentioned above with the Read Committed. That is, this level does not allow any modifications or deletion in the data which is being accessed by some other transaction. So in last example, if we read the same data multiple times, it is guaranteed to return the same info. Though we cannot update or delete the data in table being accessed by a transaction, we can still add more data. So if the query was

select name from employee;

instead of select name from employee where id=10;

we still could have different data set.

4. Serializable: This is the highest level of restriction added on transactions. This states, that no updation, deletion or addition can happen on a dataset/ table which is being accessed by another transaction. This will solve the problem which is mentioned in previous example. But the solution comes at a high cost as this restriction level will slow down the rate of transactions being executed.

ACID test for your database

ACID is a set of properties that each database system needs to guarantee in order to make sure that all the transactions will be processed reliably

Atomicity: A transaction is always committed as a full. That means if the transaction had 10 statements, all 10 are executed fully and committed. A partial execution of transaction will never occur.

Consistency: Database state is always stable. So if a transaction moves database from state A to B, both states are stable.

Isolation: All transactions will execute in isolation and do not interfere with one another (one transaction is updating the data and other is reading at the same time – dirty read is handled).

Durability: Once a transaction is committed, the changes will not be reverted by some hardware or software failure.

Interesting Java Facts

I am working with Java for more than 7 years now and still it surprises me with some very basic stuff

Can you guess what is the output of this statement in Java

System.out.println(1+2+” = “+1+2);

3=12

Why? Apparently Java starts treating everything as a String once it has encountered a string in System out statement

Apache downloading the PHP page instead of executing

Faced a weird problem after installing Apache 2 and PHP 5 on my Ubunto 10 machine today. The browser was giving an option to download the page whenever I tried clicking a PHP page link. Clearly the PHP was not getting executed properly by Apache and it was treating it as an unknown file format.

After a couple of hrs figured out this solution.

In httpd.conf file, add following lines

<IfModule mod_php5.c>
  AddType application/x-httpd-php .php .phtml .php3
  AddType application/x-httpd-php-source .phps
</IfModule>

Quick notes for Linux commands- 2

Creating shortcuts in linux- It can be a pain to write down long linux commands again and again. So here is how you can create quick shortcuts for all reusable commands.

1. Edit bashrc: You will have a “.bashrc” file in your root folder. open it up for editing (emacs .bashrc) and add commands to be added for shortcut at the bottom of this file like
alias connect=’ssh kamal@kamal.com’

This will simply create a shortcut for the command ‘ssh kamal@kamal.com’ which will get executed by typing connect.

2. Compile bashrc: Before you can actually use your shortcuts, you will need to compile the .bashrc file by
. .bashrc

3. Use shortcuts: Just type the shortcut command connect and you will see that it actually executes the command for which ‘connect’ is an alias.

Exception Handling- Basic Principles

Do not catch unchecked exceptions
Exceptions in java can be divided into checked and unchecked exceptions. Java compiler would force you to catch the checked exceptions but not the unchecked exceptions. Unchecked exceptions includes error and Runtime exception. These are the conditions in which program will not be able to handle the flow even if these are caught, so better let the JVM throw error and print stack rather than trying to handle these.

Error- A condition which occurs outside the program and causes failure, example, hardware failure.
Runtime Exceptions- An exception condition which occurred because of bad programming practice or unexpected input from user. For example, null value assigned to a variable being used or division by zero. Ideally these errors should be handled by code checks and not exception handling.

This means we should avoid catching superclass Exception as that will cover RuntimeExcpetions

Throw more relevant exceptions
Exception handling is done at multiple levels in code. For example you have, action->Process->Data layer. Now you might catch an exception in Database layer, but you might want to handle the exception actually in Action layer. So rather than throwing back filenotfound or sqlexception, you can create a DAOException and throw it instead. which will travel through Process layer and then to Action. This will help Action to handle fewer exceptions which are relevant at that layer.

Caveat- You might want to make sure you are passing all the relevant information back to the upper layers.

Using multiple try-catches
Instead of using one big block of try catch, create multiple blocks for better handling of exceptions. Make sure to take care of flow, once an exception is handled, the code will move to next try block.

Handle Exceptions late in code flow
Throw exceptions back to higher layers rather than absorbing them at lower layers. E.g. If an exception is caught at DAO layer, you might still want to throw it back to action layer for better handling.


Extend Exception and not Throwable

Here is the hierarchy of Exception class structure. Ideally we should try to extend a class as low as possible in hierarchy

Object->Throwable
Throwable->Exception and Error
Exception-> RuntimeExceptions and [other exceptions like filenotfound]
RuntimeException-> ArtithmeticException, NullPointerException

References:
http://wikijava.org/wiki/10_best_practices_with_Exceptions
http://docs.oracle.com/javase/tutorial/essential/exceptions/

Forgot MySql password?

Forgot the root password for mysql database. Here are easy steps to recover

1. Restart MySql database without password in safe mode
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &

2. Change root password 
mysql -u root
mysql> use mysql;
mysql> update user set password="mypassword" where User='root';
mysql> flush privileges;
mysql> quit

**please note that the password might be in encrypted form. use PASSWORD('some_pass') method 
mysql> update user set password=PASSWORD('mypassword') where User='root';

3. Restart database
/etc/init.d/mysql stop
/etc/init.d/mysql start

References: http://www.cyberciti.biz/tips/recover-mysql-root-password.html

Taking Mysql Backups

If you need to take a backup of myql database in sql format, it is pretty simple

mysqldump -u myDatabaseUsername -p Password >backup.sql

You will get the backup.sql file which you can restore anywhere

mysql – u myDatabaseUser -p -D databseName < backup.sql or simply execute file from the mysql prompt @backup.sql References: http://www.roseindia.net/mysql/mysql_backup_restore.shtml

For creating user and providing privileges
http://www.debuntu.org/how-to-create-a-mysql-database-and-set-privileges-to-a-user