When you know a thing, to hold that you know it, and when you do not know a thing, to allow that you do not know it - this is knowledge. -Confucius-

The gift of fantasy has meant more to me than my talent for absorbing positive knowledge. -Albert Einstein-

Science investigates religion interprets. Science gives man knowledge which is power religion gives man wisdom which is control. -Martin Luther King, Jr.-

Those who have knowledge, don't predict. Those who predict, don't have knowledge. -Lao Tzu-

Our treasure lies in the beehive of our knowledge. We are perpetually on the way thither, being by nature winged insects and honey gatherers of the mind. -Friedrich Nietzsche-

Tuesday, August 6, 2013

Encapsulation - A simple approach to OOP

We wrote a class. And some other developers will use it. And somehow we want to change our class because others use it for their purposes in a way that we don't want to be. It is like there is a variable in our class and we don't want it to be less than zero , but the developers who use our class can easily change it to any value because lack of our code quality.
Take a look at this code.
class BadClass {
    
    // public unprotected variables
    // any one who has an instant can change them to any value
    public int age;
    public String name;
 }

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        //Since we can access the age variable directly
        //we can change it to any value
        b.age = -10;

        //this assignment is not illegal. But obviously an age cannot be negative !! 
        //So this is bad and we have to stop this been happening. 

    }
}

Think that now we want to change our class. Will our changes affect other codes ? Will our changes bring errors to others codes. ?
That means our code not supporting flexibility and maintainability (which are two main benefits of OOP ).So we have to write our code in a way that it supports flexibility and maintainability . The ability to make changes in our implementation code without breaking others code who use our code is a key benefit of ENCAPSULATION.
The idea of ENCAPSULATION is hiding information behind a Public Programming Interface. That means our codes API. !!
To do that we have to keep instance variables protected (by making them private). and make public methods to access the variables and force others to use them. (our API)
after that our code will looks like this
 
  
class BadClass {

    //protect the instance variables 
    private int age;
    private String name;

    // make publicly accessible methods   
    // we can now protect our code and others as well !!
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        b.setAge(-10);

        // (-10) will not be assigned 
        System.out.println(" age = " + b.getAge());
    }
}

A well protected code !!! :)

Wednesday, July 31, 2013

Test Driven Development example - Part 4 (Simple Unit Testing for Java with NetBeans)

Lets code the all tests in the to do list. (this should be done one by, for the tutorial i used it just to show how to do it)
The FibonacciTest.java file will be look like
 
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;
 
public class FibonacciTest {

    @Test
    public void testGetFibonacci_0() {
        int x = 0;
        Fibonacci instance = new Fibonacci();
        int expResult = 0;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_1() {
        int x = 1;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_2() {
        int x = 2;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_3() {
        int x = 3;
        Fibonacci instance = new Fibonacci();
        int expResult = 2;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_4() {
        int x = 4;
        Fibonacci instance = new Fibonacci();
        int expResult = 3;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_5() {
        int x = 5;
        Fibonacci instance = new Fibonacci();
        int expResult = 5;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetFibonacci_6() {
        int x = 6;
        Fibonacci instance = new Fibonacci();
        int expResult = 8;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
}


Just run the tests and see before progress. :)
we added 4 tests, they will fail.

lets pass the 4th test.
Edit the Fibonacci.java like below to produce the first 4 Fibonacci number correctly
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        } else if (x==3) {
            result = 2;
        }
        return result;
    }
}

The result will be

Lets write in the typical way to pass all the test correctly.
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        } else if (x == 3) {
            result = 2;
        } else if (x == 4) {
            result = 3;
        } else if (x == 5) {
            result = 5;
        } else if (x == 6) {
            result = 8;
        }
        return result;
    }
}


Then all the tests will be passed. We can do this type of code for every other input as well. But we know that it cannot be done manually :) so we have to seek for a pattern in this input outputs.
And there is a pattern. The nth Fibonacci number is equal to the
(n-1)th Fibonacci number + (n-2)th Fibonacci number
Lets modify the code to produce every Fibonacci number correctly
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int fibNumber = 1;
        if (x == 0) {
            fibNumber = 0;
        } else if (x <= 2) {
            fibNumber = 1;
        } else {
            fibNumber = getFibonacci(x - 1) + getFibonacci(x - 2);
        }
        return fibNumber;
    }
}


Lets check the correctness of the program by some random test cases. :)
Lets add this test to check some other known Fibonacci numbers.
 
 @Test
    public void testFibonacci() {
        Fibonacci fibonacci = new Fibonacci();

        int cases[][] = {{7, 13}, {8, 21}, {9, 34}, {10, 55}, {11, 89}, {18, 2584}, {19, 4181}};
        for (int i = 0; i < cases.length; i++) {
            assertEquals(cases[i][1], fibonacci.getFibonacci(cases[i][0]));
        }

    }


Looks like our code pass those random cases as well. ok now we can assume that our code is working :)

Test Driven Development example - Part 3 (Simple Unit Testing for Java with NetBeans)

Our 2nd task in the to do list is,
[2] getFibonacci(1) ==> 1
now we have a passing code.
we have to make it fail. to that we can ask it the 1st Fibonacci number.
change the FibonacciTest.java file as below.
Here i have introduced a new method for check the result for input 1. Then it will be easy to identify what is going on.
 
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;

public class FibonacciTest {

    @Test
    public void testGetFibonacci_0() {
        int x = 0;
        Fibonacci instance = new Fibonacci();
        int expResult = 0;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
    @Test
    public void testGetFibonacci_1() {
        int x = 1;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }
}


Then run the code and see the result. You will see that our first test will pass and the second one is failing. That is because the getFibonacci method only return value '0' for any input.
So our test is failing. And now we have a failing code. :)

Lets make it pass. To do that we have to edit the getFibonacci method to correctly return the first 2 Fibonacci numbers.
Do the following changes in Fibonacci.java file
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1) {
            result = 1;
        }
        return result;
    }
}

Run the test file and see the results.

seems it is working :)
our second task is done. lets look at our to do list :)

[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8


lets move to our next task
[3] getFibonacci(2) ==> 1
and again we have a passing code. we have to make it fail. when we pass the '2' as input it will fail. make another testing method to do it.
 
 
 @Test
    public void testGetFibonacci_2() {
        int x = 2;
        Fibonacci instance = new Fibonacci();
        int expResult = 1;
        int result = instance.getFibonacci(x);
        assertEquals(expResult, result);
    }


result will be looks like

ok our 3rd test is failing. :) lets make it pass. we have to correctly produce first 3 Fibonacci numbers to that.
Edit the Fibonacci.java like below
 
 
package tdd;

public class Fibonacci {

    public int getFibonacci(int x) {
        int result = 0;
        if (x == 1 || x == 2) {
            result = 1;
        }
        return result;
    }
}


and the result will be

So we have completed our 3rd task also. :)
we can use if else and do that for any input. A brute force method. But after some time we may able to identify a pattern of the inputs and the out puts.

Test Driven Development example - Part 2 (Simple Unit Testing for Java with NetBeans)

After following the  previous work now we are good to code :)

First of all lets edit the Fibonacci.java file. lets add a new method.

package tdd;
 
public class Fibonacci {

    public void getFibonacci(int x) {
    }
}
Now edit the FibonacciTest.java file like below.
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;

public class FibonacciTest {

    public FibonacciTest() {
    }

    @Test
    public void testGetFibonacci() {
        fail("The test case is a prototype.");
    }
}

now just right click on the FibonacciTest.java file and run it.
The result will be as below.

Ok now we have a failing code :) We have to make it pass now.
lets make a to do list.

[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8

case 1) we have to generate the first Fibonacci number. now we have a failing code. lets make it pass and return the correct answer (0) for input (0)
change the Fibonacci.java files getFibonacci method as follows. So that it return the correct answer to the input '0'. If you remember the 3rd point it says that "we are not allowed to write any more production code than is sufficient to pass the one failing unit test" . so we have a failing test case. We have to write the code only to pass that failing code.
 
 
package tdd;
 
public class Fibonacci {

    public int getFibonacci(int x) {
        return 0;
    }
}


Then change the FibonacciTest.java file as below.
 
 
package tdd;

import org.junit.Test;
import static org.junit.Assert.*;

public class FibonacciTest {

    public FibonacciTest() {
    }

    @Test
    public void testGetFibonacci() {
        //fail("The test case is a prototype.");
        
        // this is the xth fibonacci number
        int x = 0;
        //make an instance of the Fibonacci class to access
        //getFibonacci method
        Fibonacci instance = new Fibonacci();
        // this is our expected result
        int expResult = 0;
        // get the actual  result
        int result = instance.getFibonacci(x);
        // this will  check and compare the result and the 
        // expected result. If both match test will pass.
        assertEquals(expResult, result);

    }
}


The comments will help you to understand what is going on. :)
lets run the code and see

wow we have just made our failing test case passed. :)
Our code will correctly return the 0th Fibonacci number (lets use the 0th indexing)
our first task in the to do list is done :)
[1] getFibonacci(0) ==> 0
[2] getFibonacci(1) ==> 1
[3] getFibonacci(2) ==> 1
[4] getFibonacci(3) ==> 2
[5] getFibonacci(4) ==> 3
[6] getFibonacci(5) ==> 5
[7] getFibonacci(6) ==> 8

way to go :)

Saturday, July 20, 2013

Test Driven Development example (Getting started)

There was a workshop in our university to give us an introduction about TDD by OrangeHRM. The followings are based on those experience. 

You can read about TDD here .
Simply the TDD coding process has 3 rules.(for more details refer this)

 1) You are not allowed to write any production code unless it is to make a failing unit test pass.  
 2) You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. 
 3) You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
 Here i used java and the net beans IDE to do the example.

We have to develop a program which give us the n-th Fibonacci number.

Let's create a new project called TDD first. Then create a new JUnit test. (right click the project and select JUnit test- If it is not there use other option to find it)

First create a class in Source Packages.(name it  Fibonacci )Then create a test class in the Test Packages.(name it FibonacciTest)(Don't worry if you haven't the Test Packages yet, just right click the project and create a new test, it will create a new Test Packages section ). (you can do it in 3 ways)

In the Test Packages ,
1) Create a normal java class and we can import the relevant Unit Test packages later.
2) Create a JUnit test and give the name "FibonacciTest" manually.(This will automatically call the relevant imports)

3) Create a JUnit test class by using Test for Existing class. (It will automatically set the name "FibonacciTest" and will  call  the imports as well)

Then add the JUnit library (here i used JUnit 4.10) to the Test Libraries.

The Project folder structure will  looks like this.


 

Tuesday, July 16, 2013

Create a Chrome extenstion to highlight paragraphs on user click event

I started to create a Google chrome extension to highlight the web content. As the first step i was able to create this extension which highlight the whole "p" tag when a user click on it. There are 4 file. (manifest.json, tabcolor.js ,color.js,popup.html (to call the js files,but not necessary,there are other ways )) the manifest.json file looks like
   
{
  "name": " page color 2.",
  "version": "1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
      "default_title": "Set this page's color.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version": 2
}

the popup.html file will looks like
<!doctype html>
<html>
  <head>
    <title>Set Page Color Popup</title>
     <script src="color2.js"></script>
  </head>  
</html>
the color.js file looks like
   

function clickcolor(e) {
   chrome.tabs.executeScript(null,{file : "tabcolor.js"});
   window.close();
}

document.addEventListener('DOMContentLoaded', function () {
     clickcolor();
 
}); 

the tabcolor.js file looks like
  
var divs = document.getElementsByTagName("p");
  
    for(var d in divs) {
    divs[d].addEventListener('click',function(){this.style.background='yellow';}); 
     }
 
It will appears to be like this ,

Thursday, April 4, 2013

SQL TRIGGERs


When we were doing a database project we faced to a little problem when we try to check some constraints on a table on insert , update, delete operations.
There is a table called 'infos' and there is a column called age. The values of the age should be greater than 0. So to check that constraint we used SQL CHECK constrain. It appears to be accepted by mySQL as a valid one but when inserts happens we noticed that it is not working properly. (negative values can also be added as the age).
create table infos (
id        varchar(10) NOT NULL,
name      varchar(30) NOT NULL,
age       int ,
PRIMARY KEY (id),
CHECK (age > 0)
)
After some searching we found that CHECK constraint is not yet implemented in mySQL version that we have and we have to use SQL TRIGGERs for check those constraints.

Here are the things what we found . This is not all about SQL TRIGGERs but this was enough to accomplish our task.

Sometimes we need to control , check , monitor and manage a group of tables whenever an insert, update, or delete operation is performed.
The SQL CREATE TRIGGER statement provides a way for the database management system to actively do those things.
The statements specified in the SQL trigger are executed each time an SQL insert, update, delete operation is performed. These SQL triggers cannot be directly called from an application. They will automatically invoked by the database management system when a insert , update or delete operation take place in a relevant table.
the definition of the SQL trigger is stored in the data base management system and is invoked by the data base management system.

BEFORE SQL triggers
These triggers may not modify the tables. Using these triggers we can check for some constraints before add data to the data base table. And we can use them to modify other values based on the data to be inserted or updated or deleted.

AFTER SQL triggers
These triggers may modify the tables. After make the changes to the table we can check for some constraints or we can update some other tables or the same table values based on the new state of the table.

So let's see how we can use SQL triggers to accomplish that above task.

First we have to create the table.
create table infos (
id         varchar(10) NOT NULL,
name       varchar(30) NOT NULL,
age        int ,
PRIMARY KEY (id)  
)
The Trigger can be define as follows.
delimiter $$
create trigger infos_insert BEFORE insert on infos
for each row
begin
if(
   new.age <0
)then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: Invalid age';
end if;
end;
$$
delimiter ;
As the delimiter we define another new one. (the default one is the semicolon )
And this a BEFORE SQL trigger . So the constraints will be checked before the data is entered and data will be entered if and only if the age is greater than 0. (assuming other constraints are satisfied ).
If error occurs (age is not valid) message will be displayed. We can catch this in our application also.

Inside the 'if section' we can have complex SQL parts also.
Assume that we want to insert persons to infos table only such that no 4 persons can have the same age.
To check that constraint we can use the below trigger.
(Some versions of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table')
delimiter $$
create trigger infos_insert BEFORE insert on infos
for each row
begin
if(
(select count(*) as counts   from infos
where age =new.age
group by age )+1 >3 
)then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: Maximum ageGroup limit reached';
end if;
end;
$$
delimiter ;