Wednesday, September 10, 2014

Why Scala?

Of late, there has been a tremendous surge in interest for programming in Scala. Here are some of the reasons why people are choosing to program in Scala.


  • Java/JVM compatible
    • Runs on the JVM
    • Can reuse Java libraries
  • Concise code 
    • Less boiler plate code
    • Type inference
  • Type system
    • Statically typed
    • Rich type system
  • Supports OOP style
    • Mixin composition - traits
    • Companion objects (Singletons tied to types)
  • Supports Functional Programming style
    • Functions are first class values
    • Function literals
    • Emphasis is on using vals, immutable objects, functions without side-effects
  • Is scalable
    • User defined types
    • User defined operators
    • User defined control structures
    • Can be used to write scripts
    • Can be used to write large applications

Friday, March 07, 2014

MySQL Reference


Useful mysqladmin commands

1. Get MySQL version
[root@host]# mysqladmin --version
2. Post MySQL installation, the root user password is blank. To set the password, use the below command:
[root@host]# mysqladmin -u root password "new_password";
3. Create database
[root@host]# mysqladmin -u root -p create TUTORIALS
Enter password:******
4. Drop database
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******


Adding new user

root@host# mysql -u root -p
Enter password:*******
mysql> use mysql;
Database changed

mysql> INSERT INTO user 
          (host, user, password, 
           select_priv, insert_priv, update_priv) 
           VALUES ('localhost', 'guest', 
           PASSWORD('guest123'), 'Y', 'Y', 'Y');
Query OK, 1 row affected (0.20 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT host, user, password FROM user WHERE user = 'guest';
+-----------+---------+------------------+
| host      | user    | password         |
+-----------+---------+------------------+
| localhost | guest | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)
or
root@host# mysql -u root -p password;
Enter password:*******
mysql> use mysql;
Database changed

mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    -> ON TUTORIALS.*
    -> TO 'zara'@'localhost'
    -> IDENTIFIED BY 'zara123';

Remember to FLUSH PRIVILEGES after doing the above!!


Administrative commands

# USE <database>;
# SHOW DATABASES;
# SHOW TABLES;
# SHOW INDEX FROM <tablename>;


Storage Engines

mysql> SHOW ENGINES\G
*************************** 1. row ***************************
 Engine: MyISAM
Support: DEFAULT
Comment: Default engine as of MySQL 3.23 with great performance
*************************** 2. row ***************************
 Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
*************************** 3. row ***************************
 Engine: InnoDB
Support: YES
Comment: Supports transactions, row-level locking, and foreign keys
*************************** 4. row ***************************
 Engine: BerkeleyDB
Support: NO
Comment: Supports transactions and page-level locking
*************************** 5. row ***************************
 Engine: BLACKHOLE
Support: YES
Comment: /dev/null storage engine (anything you write to it disappears)
...

CREATE TABLE t (i INT) ENGINE = INNODB;
CREATE TABLE t (i INT) TYPE = MEMORY;
The older term TYPE is supported as a synonym for ENGINE for backward compatibility, but ENGINE is the preferred term and TYPE is deprecated.
SET storage_engine=MYISAM;
SET table_type=BDB;

Miscellaneous

1. Get table status such as type of storage engine etc

# SHOW TABLE STATUS;
2. Get server meta-data

CommandDescription
SELECT VERSION( )Server version string
SELECT DATABASE( )Current database name (empty if none)
SELECT USER( )Current username
SHOW STATUSServer status indicators
SHOW VARIABLESServer configuration variables





Wednesday, January 29, 2014

Static factory methods vs Factory pattern

Many of us are familiar with the use of static factory methods for object creation. However, there is quite a bit of confusion as to whether such static factory methods are the same as the factory pattern. Let me attempt to explain the difference between the two here.

Static factory method
A static factory method also known as named constructor is employed either in place of or in addition to traditional constructors for creating objects of the class. 

The advantages of using static factory methods are:

  1. Meaningful names for constructors
  2. Choice of creating new object or returning existing one (Ex: used in singletons)
  3. Can return sub-class objects

Now, static factory method has nothing to do with the Factory pattern. In case of factory pattern, one or more factory methods are defined in a factory class and are used to create objects of multiple possibly unrelated types.

Factory pattern

This pattern hides the object creation logic while providing a well defined interface for object creation.



Friday, January 17, 2014

Double checked locking optimization

Double checked locking aims to improve performance by reducing the need to acquire a lock by checking for the locking criteria first without acquiring the lock. Subsequently, if the lock is acquired, the locking criteria is checked again in order to ensure thread-safe code.

The locking criterion variable needs to be volatile for this to work correctly. If it not volatile, the compiler might optimize access to the variable thus allowing for it to contain an older value when the locking criterion check is made.

This technique is generally used in Singleton definition.

Example
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;  
  
  private MySingleton() {
  }

  public static MySingleton getInstance() {
     if (instance == null) {
         synchronized(this) {               
               if (instance == null) {
                   instance = new MySingleton();
               }   
           }
     }
      return instance;
  }  
}

Wednesday, January 15, 2014

Singletons in Java

As developers, we all have heard of Singletons. It would not be an exaggeration to state that it is the most popular design pattern. Having said that, what exactly is a Singleton?

A class that can only be instantiated only once is referred to as a Singleton.

In order to design a Singleton class, the following rules should be adopted:
  • Private constructors
    • This prevents creating objects of the class at will and ensures that object creation can only be done by code inside the class
    • It also prevents sub-classing
  • Class should be final
    • This prevents sub-classing
    • It also makes it explicit to the developer that the class cannot be sub-classed
  • Private static Object reference 
    • This is to store the reference to the singleton
    • Should be static
    • Should be private
    • Should be volatile
  • Static method that returns the singleton reference
    • Should be static
    • Should be public
    • Should be synchronized. This is to ensure that the method is thread-safe and a single object is created even in multi-threaded scenarios
    • Create object if not created
    • Return object reference
  • Prevent cloning
    • Implement Cloneable interface and throw the CloneNotSupportedException
    • This prevents cloning of the singleton

Example 1:
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;
  
  private MySingleton() {
  }

  public static synchronized MySingleton getInstance() {
      if (instance == null) {
          instance = new MySingleton();
      }
      return instance;
  }  

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

Approach II
Another approach is to create and assign the object to the static reference variable in the definition itself. Since, static members are initialized only once during class loading, it obviates the need to serialize calls to the static method which returns the singleton.

Example 2:
public final class MySingleton {
  private static MySingleton instance = new MySingleton();
  
  private MySingleton() {
  }

  public static MySingleton getInstance() {
      return instance;
  }  

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

References
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

Wednesday, January 08, 2014

Exception handling v/s returning status codes - which is better?

I am sure that as a programmers we would have definitely pondered how best to report errors. Let us consider the available options:
  1. Return special values indicating the occurrence of error (or)
  2. Throw exceptions 
The first approach is the only method possible in older generation languages such as C where as exceptions are available in the newer languages such as Java, Python etc.

Exceptions are much superior mechanism for reporting errors as compared to returning status codes. Why that is so is enumerated below:
  • Exceptions cannot be ignored unlike status codes - As checking for status code is not mandatory, it is very common for developers to ignore the return values of methods. This implies that the error is not reported when it occurred causing the application to fail at a later point in code thus making the debugging that much harder. Exceptions on the other hand propagate up the calling stack until a matching handler is found or is caught by the runtime in the absence of a matching handler in code usually causing the application to fail. Thus an error reported via exceptions is always reported.
  • Sometimes returning status codes is not an option
    • Certain constructs like constructors do not return anything, so one cannot use status codes to report errors. 
    • In case of operator overloading which are basically implicit method calls, it is again not possible to return status codes indicating error
  • Exceptions carry context unlike status codes - When an exception is caught, the entire stack trace is made available starting from the point where it occurred. 
  • Exceptions can contain more descriptive error messages unlike status codes - Typically, the error messages reported via exceptions carry more information that what is possible to convey by just a error code.
    • For example, in a readFile() method, if the file is not found it might return a status code say -2 indicating that the file was not found. The same error when reported via a FileNotFoundException can be coded to contain a more descriptive message such as "File /tmp/abc.txt not found" 
  • Unlike exceptions, checking for errors clutters up the business logic - As multiple error code returns are possible, the error checking logic becomes tedious and often overshadows the actual business logic. Exceptions on the other hand result in much cleaner code as error handling can be kept separate from the business logic.
Caveats
Having said the above, there are cases where it is not appropriate to use exceptions
  • Exceptions should NOT be used as part of normal flow - Do not use exceptions to report any of the possible normal states of an operation. In such scenarios, convey the status of the operation by returning appropriate status code. Exception handling is expensive and should only be used to handle exceptional/abnormal conditions
References

Friday, January 03, 2014

Java Annotations

What are Annotations?
Annotations are basically syntactic meta-data that can be applied to packages, classes, methods, variables & parameters. 

Purpose
Annotations serve several purposes such as...
  • Provide extra information to the compiler
    • @Override
    • @SuppressWarnings
    • @Deprecated
  • Reduce boiler plate code
    • See project LomBok
    • AOP as in Spring AOP
    • Replacement for marker interfaces
  • Used by frameworks to glue user defined classes together into an application instead of specifying the same in an external XML configuration file
    • Spring
  • Provide information to be used at run-time 

Examples
Annotations can have elements which have values
@Author(name="kirk",  date="1/1/2014")

If annotations have a single element named value, it can be omitted as shown below:
@SuppressWarnings("unchecked")

If annotations have no elements, then the braces can be omitted as well:
@Override