Consider Enums Instead of Constants

Using constants can be error prone. You always need to validate that the value being passed is valid.

<pre class="prettyprint"><span class="kwd">class</span> <span class="typ">Suit</span> <span class="pun">{</span>        
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> CLUBS </span><span class="pun">=</span> <span class="lit">1</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> SPADES </span><span class="pun">=</span> <span class="lit">2</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> HEARTS </span><span class="pun">=</span> <span class="lit">3</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> DIAMONDS </span><span class="pun">=</span> <span class="lit">4</span><span class="pun">;</span>
<span class="pun">}</span></pre>
<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> method</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> suit</span><span class="pun">)</span> <span class="pun">{</span>
    <span class="kwd">if</span> <span class="pun">(</span><span class="pln">suit </span><span class="pun"><</span> <span class="lit">1</span> <span class="pun">||</span><span class="pln"> suit </span><span class="pun">></span> <span class="lit">4</span><span class="pun">)</span> <span class="pun">{</span>
        <span class="kwd">throw</span> <span class="kwd">new</span> <span class="typ">IllegalArgumentException</span><span class="pun">(</span><span class="str">"Invalid suit value: "</span> <span class="pun">+</span><span class="pln"> suit</span><span class="pun">);</span>
    <span class="pun">}</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>

What happens if we add a suit? What happens if we remove a suit? All the client code needs to be updated!

<pre class="prettyprint"><span class="kwd">enum</span> <span class="typ">Suit</span> <span class="pun">{</span><span class="pln">     
    CLUBS</span><span class="pun">,</span><span class="pln"> SPADES</span><span class="pun">,</span><span class="pln"> HEARTS</span><span class="pun">,</span><span class="pln"> DIAMONDS
</span><span class="pun">}</span></pre>
<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> method</span><span class="pun">(</span><span class="typ">Suit</span><span class="pln"> suit</span><span class="pun">)</span> <span class="pun">{</span>
    <span class="typ">Validate</span><span class="pun">.</span><span class="pln">notNull</span><span class="pun">(</span><span class="pln">suit</span><span class="pun">);</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>

Client code:

<pre class="prettyprint"><span class="pln">method</span><span class="pun">(</span><span class="typ">Suit</span><span class="pun">.</span><span class="pln">CLUBS</span><span class="pun">);</span></pre>
<pre class="prettyprint"><span class="kwd">import</span> <span class="kwd">static</span> <span class="pun">....</span><span class="typ">Suit</span><span class="pun">.*;</span>
    <span class="pun">...</span><span class="pln">
    method</span><span class="pun">(</span><span class="pln">CLUBS</span><span class="pun">);</span>
    <span class="pun">...</span></pre>

Enums can also define their own instance variables and methods, so you can remove the if-else blocks from the clients and instead push specific behaviors or values to the enums.


Polymorphism is one of the object oriented concepts. Polymorphism means allowing objects with differing behavior that can be substitutable for one another.

You can take advantage of polymorphism by using Inheritance, either just Interface Inheritance or with Implementation Inheritance .

Method Overriding facilitates the differing behaviors in subtypes.

Without polymorphism …

if (...file...) {
    readFromFileStream(new FileInputStream(&amp;amp;amp;amp;amp;quot;filename&amp;amp;amp;amp;amp;quot;));
} else if (...URL...) {
    readFromURLStream(new  URL(url).openStream());
} else if (...console...) {
} else if ...

  • Notice that the if else statements does similar things – to read from an input stream.

With polymorphism…

<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> readFromStream</span><span class="pun">(</span><b><span class="typ">InputStream</span><span class="pln"> stream</span></b><span class="pun">)</span> <span class="pun">{</span>
    <span class="pun">...</span><span class="pln">
    stream</span><span class="pun">.</span><b><span class="pln">read</span><span class="pun">()</span></b><span class="pun">;</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>

InputStream is an abstract class, so any object of InputStream (extends InputStream) can be passed in the readFromStream(InputStream stream) regardless of the implementation of the read() function.

For example,

<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="kwd">new</span> <span class="typ">FileInputStream</span><span class="pun">(</span><span class="str">"filename"</span><span class="pun">));</span></pre>
<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> URL</span><span class="pun">(</span><span class="str">""</span><span class="pun">).</span><span class="pln">openStream</span><span class="pun">());</span></pre>
<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="typ">System</span><span class="pun">.</span><span class="kwd">in</span><span class="pun">);</span></pre>

FileInputStream extends InputStream, so it is legal to pass FileInputStream object to readFromStream() method.

In general, any object that extends InputStream can be passed to the readFromStream() method.

The type of the object you passed determines the what implementation of the behavior to be executed.



In this blog post, I’ll discuss about one of the concepts of Object Oriented Programming which is Inheritance. 

Inheritance is a way of deriving a class from another class. In the other words, a class can inherit the fields and methods from other class.

Code reuse

Inheritance is one way of achieving code reuse. Here’s why, when you want to create a new class and some functionality in it has already in another class, you can derive your class to the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write the code again in your new class.

Subclass is the class that is derived from another class (also called extended class, derived class, or child class). This is more specific type of a class.

Superclass is the class from which a subclass is derived (also called parent class or base class).

inheritanceIn the picture above, Person class is the superclass of Student class and Employee class. On the other hand, Student class and Employee class are the subclasses of Person class. Student and Employee is a more specific type of a Person.


Look at the class diagram above, notice that the Student class and Employee has no basic fields like firstName, lastName, lastName and age. It is because those fields are already inherited from the Person class. However, you can also declare those fields again with the same name in the subclass, thus, you are hiding the fields in the superclass (it can cause confusion and it is not recommended).

Not only the fields are inherited but also the methods (except for private methods) of the Person class. The methods eat() and sleep() of Person is inherited in the Student and Employee class.

You can add fields and methods to the subclass. In the case above, Student has a course and yearLevel fields and a study() method and Employee has salary and designation fields and a raiseSalary(int percent) method. By adding those fields and methods, you are extending the functionality of the class and that what makes the subclass more specific type.

You can change the behavior of the superclass by overriding it. Override a method by define a method with the same method signature, a method signature is the method name and the number and type of its parameters. Return types are not considered to be a part of the method signature.

If you liked this post, don’t forget to subscribe to this blog for more updates.


In procedural programming language like C, data and behavior are mixed together in one file. The data can be accessed in any behavior. It means that some data can be changed by some behaviors that are not associated with that data. It leads to data corruption.

Reason for Data Insecurity in Procedural Programming

  • It is the global variables that leads to data insecurity
  • Global variables can be accessed in any functions in the program. So it means that the value of the global variables can be changed by the unrelated functions.
  • Whenever unrelated functions accessed that data, data corruption arises.

For example:

#include &lt;stdio.h&gt;

int result = 0;

int main() {
	result = sum(5, 5);
	return 0;

int sum(int firstNumber, int secondNumber) {
	return firstNumber + secondNumber;

int multiply(int firstNumber, int secondNumber) {
	return firstNumber * secondNumber;

void printResult() {
	printf(&quot;Result is %d&quot;, result);

void unrelatedFunction() { //assuming some unrelated behavior accesses the &quot;result&quot; variable


Encapsulation is one of the core concepts in object oriented programming. Encapsulation is the binding of data with their corresponding behavior.

What is binding?

  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding we can restrict the availability of data to the unrelated functions
  • So that unrelated functions cannot access the data
  • Class is the base for encapsulation
public class Room {

	private long id;
	private String roomName;
	private String building;

	public String getRoomName() {
		return roomName;

	public void setRoomName(String roomName) {
		this.roomName = roomName;

	public String getBuilding() {
		return building;

	public void setBuilding(String building) {
		this.building = building;

	public long getId() {
		return id;

	public void setId(long id) { = id;

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id &gt;&gt;&gt; 32));
		return result;

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Room other = (Room) obj;
		if (id !=
			return false;
		return true;

	public String toString() {
		return roomName + &quot; &quot; + building;


Abstraction is a way of dealing with things in a general way as much as possible, separate from specific details, implementations and instances.

According to wikipedia:

Abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.

In this blog post, I will show to you simple ways how to achieve abstraction. Some of you implemented this concept but you’re unaware of it.

Abstraction via Functions

  • Processes can be grouped into functions
  • One function can call other function
  • You don’t have to understand each line, just what the function does
  • You can hide data to be accessible only within the function – local variables

double areaOfCircle(int radius) {

	return PI * radius * radius;


boolean isFirstBiggerThanSecond(int radius1, int radius2) {
	double area1, area2;
	area1 = areaOfCircle(radius1);
	area2 = areaOfCircle(radius2);
	return area1 &amp;gt; area2;

The areaOfCircle() method computes the area of the circle. The isFirstBiggerThanSecond() method compares the size of the circle if the first circle is bigger than the second one given the radius of the two. The isFirstBiggerThanSecond() called the areaOfCircle(). The one who writes the code of the isFirstBiggerThanSecond() method does not need to know how the implementation of the areaOfCircle() method. What he need to do is just to know what the areaOfCircle() does. The implementation on how to compute the area of the circle is separated and factored out so that who will ever use that method does not need to know how the computation is done, only what the function does.

Abstraction via Objects

Combining complex data types and the functions that operates on them give you objects.

public class Rectangle {
    private int length;
    private int width;

    public Rectangle (int length, int width) {
        this.length = length;
        this.width width;

    public int area() {
        return length * width;

    public boolean isBiggerThan(Rectangle other) {
        return this.area() > other.area();

Rectangle rect1 = new Rectangle(3, 4);
Rectangle rect2 = new Rectangle(5, 6);

if (rect1.isBiggerThan(rect2)) {
} else {

Objects are mini-programs, each with its own data and operations.

In Unix, we have a lot of little programs (grep, ls, cat…) that do just one thing. We can combine the little programs into bigger programs by having the output of one become the input of another.

OOP is the same. We make small, simple, specialized programs, and then make bigger programs by combining little programs (“Composition”).

“Think of an OO system as a bunch of intelligent animals (the objects) inside your machine, talking to each other by sending messages to one another.” – Allen Holub

OOP is a way to make programs easier to understand, by allowing bigger programs to be composed of smaller programs, and those smaller programs to be composed of even smaller programs, ad infinitum.

Those are only simple concepts that relates to abstraction. I found an interesting article which discusses abstraction using interface and abstract class in java.

StringBuilder Class

I wrote a blog post about String and StringBuilder last week but I haven’t discussed more in detail about StringBuilder. So in this blog post, I will talk about more in detail on StringBuilder class in Java.

StringBuilder is a mutable sequence of characters. It means that when you modify the contents of the StringBuilder object, java does not instantiate intermediate String objects (except for any String literal you pass into the StringBuilder) unlike String.

new StringBuilder("Live").append("What").append("You").append("Love");


Since StringBuilder is mutable, it can perform these operations:

  1.  Append – appends the string representation of the parameter(boolean, int, char, double, object, etc) to the char sequence.

Append method is overloaded so it can receive different data types like int, long, double, boolean.

new StringBuilder("You are").append(true).append(2).append("me");

//You are true2me

2.  Insert – appends the string representation of  the parameter(boolean, int, char, double, object, etc) to the char sequence. It differs to append because in insert, you can specify the place where you insert whereas append you just adding or concatenating the string after the last character.

StringBuilder couple = new StringBuilder("JunaldBeverly");

couple.insert(6, " Love ");

//Junald Love Beverly

3. Delete – deletes the substring in the char sequence based on the starting index and ending index.

StringBuilder greeting = new StringBuilder("Happy New Year");

greeting.delete(5, 8);

//Happy Year

4. Reverse –  reverses the char sequence.

StringBuilder food = new StringBuilder("stressed");

food = food.reverse();


There are lot of methods in StringBuilder like substring, replace, trimToSize. If you want to learn more about those methods you must check out the Java documentation.

If you liked this post, don’t forget to share! Thanks