Monthly Archives: March 2013

Methods must be stupid

3se4um
Find small error in architecture sense.

Wrong realization is as following:

public class Login {

  private String username;

  public boolean isAuthenticated() {
    return username != null;
  }

  private void init() {
    if (username == null) {
      // Some actions to get data...
      username = "Johnny Depp";
    }
  }
}

As you see, method init() checks the value of username field. That’s not right.
Methods must perform some action regardless to any external state. But decision to call or not must be accepted by caller.

Here is right implementation:

public class Login {

  private String username;

  public boolean isAuthenticated() {
    if (username == null) {
      init();
    }
    return username != null;
  }

  private void init() {
    // Some actions to get data...
    username = "Johnny Depp";
  }
}

Collection key implementation in Java

Collection-Interfaces
Interface-and-Classes
In case you have to use custom key in collection, key of collection must override equals() and hashCode() methods.
The example snippet:

package com.test;

import java.util.HashMap;
import java.util.Map;

public class Test {
  public static void main(String[] args) {
    Map<CollectionKey, Object> map = new HashMap<CollectionKey, Object>();
		
    CollectionKey key1 = new CollectionKey("0", "1", "2");
    map.put(key1, new Object());
		
    CollectionKey key2 = new CollectionKey("3", "4", "5");
    map.put(key2, new Object());
		
    Object obj1 = map.get(key1);
    Object obj2 = map.get(key2);
}
    
  private static class CollectionKey {

    private final String prop1;
    private final String prop2;
    private final String prop3;

    private CollectionKey(final String prop1, final String prop2, final String prop3) {
      this.prop1 = prop1;
      this.prop2 = prop2;
      this.prop3 = prop3;
    }

    @Override
    public final boolean equals(final Object obj) {
      final CollectionKey key = (CollectionKey) obj;
      return prop1.equals(key.prop1) && prop2.equals(key.prop2) && prop3.equals(key.prop3);
    }

    @Override
    public final int hashCode() {
      return prop1.hashCode() + prop2.hashCode() + prop3.hashCode();
    }

    @Override
    public final String toString() {
      return prop1 + ":" + prop2 + ":" + prop3;
    }
  }
}

Using @PostConstruct annotation for initializing a Bean

ejbcon-statefulsblifecycle
Suppose, you have to initialize some of your beans. This are two ways. The first is to use the bean constructor. But this is wrong way regardless to architecture stuff, because occurring any sort of exceptions in constructor destroy the object has been created.
Another way is to use an init() method and call it when object exists. So, we can handle the exceptions appeared.

But in EJB world there is more useful thing like annotations, and @PostConstruct is great for our task to initialize the object.
Just add the attribute @PostConstruct to init() method and container shell call it every time when object creating (but only one time per creating).

Another pros of using the attribute @PostConstruct is that if you have any dependency injections in your bean, in constructor you have no injected objects yet! But in @PostConstruct method your object already have they injected and you can use injected fields as you wish.

The code snippet is:

public class SomeBean implements Serializable {

  public SomeBean() {
    // your safe actions here...
  }

  @PostConstruct
  public void init() {
    // make init here...
  }
}

For more info:
http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html
http://docs.oracle.com/javaee/6/tutorial/doc/giplj.html

Enum with String values implementation in Java

enum_data_type
This is classical realization of enum with string values:

    private enum SomeTestEnum {

        ITEM1("TheStringNameOfItem1"),
        ITEM2("TheStringNameOfItem2"),
        ITEM3("TheStringNameOfItem3");

        private final String name;

        /**
         * Default constructor
         */
        SomeTestEnum(String name) {
            this.name = name;
        }

        /**
         * Getter for current instance name value
         */
        public String getName() {
            return name;
        }

        public static SomeTestEnum getByName(String name) {
            for (SomeTestEnum item : SomeTestEnum.values()) {
                if (item.getName().equals(name)) {
                    return item;
                }
            }
            return null;
        }
    }

Bubble sort in Java

bubbleSort
Well known classical bubble sort algorithm, just for snippet:

public static void bubbleSort(int[] unsorted) {
    for (int i = 0; i < unsorted.length - 1; i++) {
        for (int j = 1; j < unsorted.length - i; j++) {
            if (unsorted[j - 1] > unsorted[j]) {
                int temp = unsorted[j];
                unsorted[j] = unsorted[j - 1];
                unsorted[j - 1] = temp;
            }
        }
    }
}

As always, thanx to http://java67.blogspot.com/2012/12/bubble-sort-in-java-program-to-sort-integer-array-example.html

Network configuration in Linux

networkCfg
As a rule, network configuration in Linux is placed in /etc/network/interfaces file.

Here is the example of such config:

## The primary network interface - use DHCP
# auto eth0
# iface eth0 inet dhcp

## The primary network interface - use Fixed IP
auto eth0
iface eth0 inet static
address 192.168.2.10
gateway 192.168.2.1
netmask 255.255.255.0
network 192.168.2.0
broadcast 192.168.2.255

## This dns entry will push information to resolvconf.
dns-nameservers 11.22.33.44 55.66.77.88

To restart network configuration just use next commands:

# /etc/init.d/networking restart

or this:

# ifdown eth0
# ifup eth0

Reverse String in Java

str
It is really amazing simple! Just use recursion to reverse a String:

public static String reverse(String value) {
    return value == null || value.length() <= 1 ? value 
        : reverse(value.substring(1)) + value.charAt(0);
}

Thanx to javinpaul http://javarevisited.blogspot.com/2012/01/how-to-reverse-string-in-java-using.html