Sunday, August 24, 2014

EJ-36 Consistently Use the Override Annotation

This is the case I meet frequently, thanks to Eclipse, it puts automatically when a class implements an interface or extends a super class.

Ref: Effective Java by Joshua Bloch

Can you spot the bug?:

The program tries to utilize equals method of Object by intention of overriding equals method, but it can not, since to override Object.equals, you must define an equals method whose parameter is of type Object. 

Luckily, the compiler can help you find this error, but only if you help the compiler by telling it that you intend to override Object.equals. To do this, annotate Bigram.equals with @Override as shown below

@Override public boolean equals(Bigram b) {
      return b.first == first && b.second == second;

Therefore, you should use the Override annotation on every method decleration that you believe to override a superclass decleration.

EJ-35 Prefer Annotations to naming patterns

Ref: Effective Java by Joshua Bloch

Prior to release 1.5, it was a common to use naming pattern to indicate that some program elements demanded special treatment by a tool or a framework. For example, the JUnit testing framework originally required its users to designate test methods by beginning theri names with the characters test. This technique works but
  • it is open to typograhapicals error.
  • There is no way to associate parameter values with program elements (such as marking a test method with exception expectation)

Annotations solve all of these problems. Here is a sample annotation type, named Test:

Annotations have no direct effect on the semantics of class, they serve only to provide information for use by interested programes, enabling it for special treatment by tools such as this simple test runner by checking isAnnotationPresent on method, see line 10.


EJ-31 Use Instance Fields instead of Ordinals

Ref: Effective Java by Joshua Bloch

All enums have an ordinal merhod which returns the numerical position of each enum constant in its type. You may be tempted to derive an associated int value from the ordinal

While this enum works, it is a maintenance nightmare to depend ordinal value which value changes in case of constants are reordered. The enum specification has this to say about ordinal: "Most programmers will have no use for this method, it is designed for use by general-purpose enum based data structures as EnumSet and EnumMap".

Luckily, there is a simple solution to these problem. Never derive a value associated with an enum form its ordinal; store it in an instance field instead:


Saturday, August 23, 2014

EJ-30 Use Enum instead of Int Constants

Ref: Effective Java by Joshua Bloch

Here is how it looks in its simplest enum form.

The basic idea behind Java's enum types is simple: they are classes that export one instance for each enumeration constant via a public static final field. Enum types are effectively final, by virtue of having no accessible constructors. They are generalization of singleton.

Let's go on with richer enum forms with methods and fields. For a nice example of a rich enum type, consider the eight planets of our solar system. Each planet has a mass and radius, and from these two attributes youcan compute its surface gravitiy.

Enums are by their nature immutable, so all fields should be final.

While the Planet enum is simple, it is surprisingly powerful. Note that Planet, like all enums, has a static values method that returns an array o fits values in the order they were declared. Note also that the toString method returns the declared name of each enum value.

The technique demonstrated in the Planet example are sufficient for most enum types, but sometimes you need to associate fundamentally different behavior with each constant. One way to achieve this is to switch on the value of the enum.

This code works but it isn't very pretty. Consider below powerful side of Enum, implementing abstract method in each Enum instance

If you add a new constant to the second version of Operation, it is unlikely that you'll forget t oprovide an apply method, as the method immediately follows each constant decleration.

So when should you use enums? Anytime you need a fixed set of constants. Of course, this includes "natural enumerated types" such as planets, the days of the week, and the chess pieces, but it also includes other sets for which you know all the possible values at compile time such as choices on a menu, operation codes etc.

EJ-23 Java Generics Terminology

Term Example
Parameterized Type List
Actual  Type Parameter String
Generic TypeList
Format Type Parameter E
Unbounded Wildcard Type List
Raw TypeList
Bounded Type Parameter
Recursive Type Bound >
Bounded Wildcard Type List
Generic Method static List asList
Type Token String.class

EJ-21 Use Function Objects to Represent Strategies

Ref: Effective Java by Joshua Bloch

Strategy classes are often declered using anonymous classes and pessed to target operation. The following statement sorts an array of strings according to length:

But note that using an anonymous class in this way will create a new instance each time the call is executed. When it is expected for repeated use, it is generally implemented as a private static member class and exported in a public static final field whose type is the strategy interface

EJ-19 Use Interfaces only to define types

Ref: Effective Java by Joshua Bloch

In this item, Mr Bloch mention about same symptom I have faced previously and shared in this post.

The constant interface pattern is a poor use of interfaces:

Instead use a utility class

If you make heavy use of the constants exported by a utility class, you can avoid the need for qualifying the constants with the class name by making use of the static import facility

In summary, interfaces should be used only to define types, they should not be used to export constants.

EJ-15 Minimize Mutability

Ref: Effective Java by Joshua Bloch

An immutable class is simply a class whose instances can not be modified, all of the information contained in each instance is provided when it is created and is fixed for the lifetime of object.
There are many good reasons for this: Immutable classes are easier to design, implement and use than mutable classes. They are less prone to error and are more secure.
To make class immutable:
  1. Don't provide any methods that modify the object's state 
  2. Ensure that theclass can't be extended.
  3. Make all fields final.
  4. Make all fields private.
Here is a good sample of immutable class, Notice how the aritmetic operations create and return a new Complex instance rather than modifying this instance.

  • Immutable objects are simple, an immutable object can be in exactly one state, the state in which it was created.
  • Immutable ojects are inherently thread-safe; they require no synchronization
  • Immutable ojects can be shared freely. One easy way to do this is to rpvoide public static final constants for frequently used values, for example
public static final Complex ZERO = new Complex(0, 0);
public static final Complex ONE = new Complex(1, 0);
public static final Complex I = new Complex(0, 1); 
 To summarize, resist the urge to write a setter method for every getter method. Classes should be immutable unless there's a very good reason to make them mutable.

A Brake for Music

Gullerin Icinden by MFO,

First recorded by guitar rhythm then another record over it with solo, Hope to enjoy

A Developer's Life In GIF

When I’m deploying code to production :), if I don't have confidence with unit test of course.

A Developer's life in GIF

Here is whole set of list, ATTENTION for convulsions :)

Friday, August 22, 2014

Firefox SesliSozluk add-on DIY

Civilization advances by extending the number of important operations we can perform without thinking. Alfred North Whitehad

In Tip#61 of Pragmatic Programmer , it is said that "Don't use Manual Procedures".

Tonight, I said it is enough each time to look a meaning of a word while reading on internet
  1. open a new tab in browser, 
  2. go to and 
  3. enter the word to get meaning. 

As i searched, there were no appropriated firefox add-on matching to my needs, so why i don't prepare one. It is so simple and does not offer no more than what i have needed :). Just select the word and right click and click on "Sesli Sozluk" from the opened menu. Sesli Sozluk will be pop-up with meaning of the selected word.

Here you can get it and don't forget to rate it by 5 stars  :)

I found chrome alternative here prepared by another gentlemen, and don't forget to rate it by 5 stars too :)

Thursday, August 21, 2014

EJ-5 Avoid Creating Unnecessary Object

Ref: Effective Java by Joshua Bloch

In Item-5 of Effctive Java, Mr Bloch expresses that avoid creating unnecessary object. In essence, this requires knowing your tool, Java.

String s = new String("test"); //DON'T DO THIS

The statement creates a new String instance each time it is executed. The improved version is simply the following:

String s = "test";

This version uses a single String instance, rathe rthan creating new one each time it is executed. This idiom is called String Interning.
Here is a really interesting sample code demonstrating String interning.

First checkEquality results that both two strings are exatly same instance with same identity code and both == and equals() give true.
Second checkEquality results that two strings are different instances created with different identity codes and == results false but equals() results true.


Mr Bloch advices to avoid unnecessary objects by using static factory methods in preference to constructors on immutable classes. If a class preferable immutable, why you should create new instance each time instead of creating one and using it.

Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String)

Boolean.TRUE is implemented inside Boolean class as a static final Boolean element:

public static final Boolean TRUE = new Boolean(true);

EJ-4 Enforce Noninstantiability with a Private Constructor

Ref: Effective Java by Joshua Bloch

Occasionally you'll want to write a class that is just a grouping of static methods and static fields like java.util.Collections. Such utility classes were not designed to be instantiated, an instance would be nonsensical. A class can be made noninstantiable by including a private constructor.

EJ-3 Enforce the Singleton Property with a Private Constructor or an Enum Type

Ref: Effective Java by Joshua Bloch

A singleton is simply a class the is instantiated exactly once, although making a class a singleton can make it difficult to test its clients, as it's impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.
Take a look at Misko Hevery's considerations about Singletons in terms of testability
In one approach, the member is a final field:

In second approach, the public member is a static factory method:

In third and really interesting aproach is to make an Enum type with one element, marked as preferred approach By Mr. Bloch

A single-element enum type is the best way to implement singleton.

EJ-2 Consider a Builder When Faced with Many Constructor Parameters

Ref: Effective Java by Joshua Bloch

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only required parameters, another with a single optional parameters, a third with two optional parameters, and so on...

Telescoping constructor pattern works, but it is hard to write client code when there are many parameters, harder still to read it.

An alternative way is to use JavaBeans patterns, creating instance with a parameterless constructor than calling setter method of each required parameters.  Unfortunately, the JavaBeans patterns has a serious disadvantages of its own, because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction.

Better to use Builder Pattern, client calls setter-like methods on the builder object to set each optional parameter of interest and then calls parameterless build method to generate the object which is immutable.

In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans. 


Wednesday, August 20, 2014

EJ-1 Consider Static Factory Methods instead of Constructors

Ref: Effective Java by Joshua Bloch

In Item-1 of Effective Java, Mr. Bloch emphasize why and how it is important to use Static Factory methods instead of constructors.

Here is goofy and wasteful way to get Boolean instances

Here is shiny and frugally way to get immutable Boolean instance with static factory method

Lets go over advantages of using static factory methods
1.) Unlike constructors, the have names. If parameters to a constructor do not describe object being returned, a static factory with well choosen name is easier to use and resulting client code easier to read.

Another example is multiple constructors with same signature as I met in stackoverflow.
Two constructors with same signature doing different things.

Can be managed by using static factory methods.

2.) Unlike constructors, they are not required to create a new object each time they're invoked. This is demonstrated as in boolean example above and important to use system resources frugally by avoiding unnecessary instance creation.

3.) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. Mr Bloch exemplifies this advantage with Service Provider Framework pattern.

Finally, he give a list of some common method names to statis factory methods.
  • valueOf
  • of
  • getInstance
  • newInstance
  • getType
  • newType
Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.

Sunday, August 10, 2014