Difference between method and functions

A method is on an object.
A function is independent of an object.

For Java, there are only methods.
For C, there are only functions.

For C++ it would depend on whether or not you’re in a class.

In general: methods are functions that belong to a class, functions can be on any other scope of the code so you could state that all methods are functions, but not all functions are methods:

Take the following python example:

class Door:
def open(self):
print 'hello stranger'

def knock_door():
a_door = Door()
Door.open(a_door)

knock_door()

def orphan_function() :
print “I am not part of class so can never be called method”

The example given shows you a class called “Door” which has a method or action called “open”, it is called a method because it was declared inside a class. There is another portion of code with “def” just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called by itself.

Java Tip : How to avoid an java.util.ConcurrentModificationException with ArrayList?

You need to add/delete an item in an ArrayList when you are iterating the list. You will receive the java.util.ConcurrentModificationException exception. For example, the following code will throw an exception after adding an item into list:

public class Sample {

  public static void main(String[] args) {

    List<Integer>  iList = new ArrayList<Integer>();
    for (int i = 0; i != 100; i++)
      iList.add(i);

    int addValue = 1000;
    for (Integer i: iList) {
      if (i%10 == 0) {
        iList.add(addValue++);
      }
    }
}

To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list. If we do the same as the above code, the next access item in list via the iterator will generate the same exception.

public class Sample {

  public static void main(String[] args) {

    List<Integer>  iList = new ArrayList<Integer>();
    for (int i = 0; i != 100; i++)
      iList.add(i);

    int addValue = 1000;

    for (ListIterator<Integer> itr = iList.listIterator(); itr.hasNext();) {
      Integer i = itr.next();
      if (i%10 == 0) {
        itr.add(addValue++);
      }
    }

}

wicket : Drag and Drop

Latest wicket support drag n drop English: Drag and Drop Ltd Logo
here is the link
http://code.google.com/p/wicket-dnd/

here is the same code, simple define source and target ūüôā

        WebMarkupContainer container = new WebMarkupContainer("container");
    Model<String> model = Model.of(new String("AAA"));
    container.add(new DragSource(Operation.values()) {
          public void onAfterDrop(AjaxRequestTarget target, Transfer transfer) {

              System.out.println("Drag n drop");

          }
        }.drag("span"));

    container.add(new DropTarget(Operation.values()) {
          public void onDrop(AjaxRequestTarget target, Transfer transfer, Location location) {
            // add transfer data

              System.out.println("rrrr");
          }
        }.dropCenter("td"));

    Label label = new Label("aaa", model);
    label.setOutputMarkupId(true);
    container.add(label);

    add(container);

Javatip : Why do we have only public static final variables in interfaces?

An interface defines a protocol of behavior and not how you should be implemented. A class that implements an interface adheres to the protocol defined by that interface.

All fields declared within an interface are implicity public, static, and final. Why?

  • Any implementations can change value of fields if they are not defined as¬†final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.
  • If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.
  • An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.

In general, a field declaration may include the following modifiers:¬†public, protected, private, final, static, transient, volatile. But only¬†public, final, and¬†static¬†are permitted for interface’s variable.

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields. Every field in the body of an interface must have an initialization expression, which need not be a constant expression. The variable initializer is evaluated and the assignment performed exactly once, when the interface is initialized.

Database : SQL to find reference tables

 

To find all tables that referenced “Organization” table use the following SQL query:

select table_name, constraint_name, status from user_constraints
where constraint_type = ‘R’
and r_constraint_name in
(
select constraint_name from user_constraints
where constraint_type in (‘P’, ‘U’)
and table_name = ‘ORGANIZATION’
)
order by table_name, constraint_name;

NOTE: In the query above ‘ORGANIZATION’ can be replaced with the name of any table you are interested in.

 

TestNG : Expected Exception Test

It is always good to test the working and output of your unit. But it is more important to test the negative behavior to make application robust. What if you are expecting an exception from a part of code which is not thrown. the point where application has to get terminated, it is moving smoothly to get a dead lock or a pitty crash. Just to save such situation Testing of exception generation is code is very important. There are annotation in TestNG frame work which helps to make is an easy task.

Example

import org.testng.annotations.*;

public class TestNGTest2 {

	@Test(expectedExceptions = ArithmeticException.class)  
	public void divisionWithException() {  
	  int i = 1/0;
	}  

}

In above example, the divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.

More advanced example can be observed in the snap shot attached.
Where the scenarios to test says – “Calling this method with null argument throws Exception”.
The test will go green if exception is thrown, else it will go red.

Testing the expected exception

Testing the expected exception

Hibernate : How to Use Enum

 

By default Hibernate persists the enumeration value as integer in the database when type param is not specified, In order to store the enum display name, we use a param type, which should be pointed to value in java.sql. Instead of leaving the input open it is a better practice to confine the possible input values in the form of enum. For example, A product can have limited number of state like available, out of stock etc. If we will leave the input out open there are chances of confusion causing data errors eventually. However, if we create the input enum then, changes of data error becomes less.
The details is mentined in the diagram attached.

Java class showing usage of enum

Java class showing usage of enum

 

You might be curious to know how would it persist in the Database table. Below snap shot explains it. Please care of the comments mentioned in the diagrams.

Table view of Enum persisted from Hibernate entity

Table view of Enum persisted from Hibernate entity

 

 

Java Null Pointer Exception guard by using short circuit operators

Most common and horrible exception is NPE  null pointer exception.
Several time programmers evaluate the expression without providing the null guard on the object. It causes null pointer exception if by mistake null argument is passed.

public void doSomething(Object obj){
if(obj.isWoman){
Sysout.out.println(“do shopping”);
}else{
Sysout.out.println(“pay the bill “);
}
}

You are sure that the caller method will pass the some object when calling this method, but some if this method is passed with null value than null pointer exception will spoil the look and grace of your software. so to mitigate that, java short circuit are there for rescue. You just need to add the null gurad with short circuit operator and you have got protection against null.

public void doSomething(Object obj){
if((obj != null) && (obj.isWoman)){
Sysout.out.println(“do shopping”);
}else{
Sysout.out.println(“pay the bill “);
}
}

Here is how it works.
The && and || operators are short circuit operators. A short circuit operator is one that doesn’t
necessarily evaluate all of its operands. Take, for example, the operator &&. What happens when Java  executes the following code?

if (0 == 1 && 2 + 2 == 4) {
out.println(“This line won’t be printed.”);
}

You might expect Java to ask itself if 0 equals 1, and then ask if 2 + 2 equals 4. But with Java’s &&
operator, that’s not what happens. Instead, Java does the following:
Evaluate 0 == 1, discovering that 0 == 1 is false.
Realize that the condition (0 == 1 && whatever) can’t possibly be true, no matter what
the whatever condition happens to be.
Return false (without bothering to check if 2 + 2 == 4).
The condition (0 == 1 && whatever) has to be false, because 0 == 1 is false. (Remember,
the && operator wants both conditions, on its left and right sides, to be true.)
So when Java finds the value on the left side of an && operator to be false, then Java gives up and
declares the entire expression to be false. That’s called short circuit expression evaluation.¬† The same
kind of thing happens with the || operator (another short circuit operator) when the value on the
operator’s left side is true.

if (2 + 2 == 4 || 0 == 1) {
out.println(“This line will be printed.”);
}

Realize that the condition (2 + 2 == 4 || whatever) must be true, no matter what
the whatever condition happens to be.

Importance of flushing data in unit test cases

While writing unit tests it is a good practice to clear and flush the session. When application is executed in real time there are several request and response or different transactions due to which the session/cache gets cleared. However while running unit test, everything happens as the part of single process ie the session (especially hibernate) has rotten values or old references which gives some exceptions at times.

Exception :
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.ptc.fusion.model.learningitem.OnlineCourse#1]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:613)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate

Code Example :

learningItemRepository.saveLearningItem(c3);

sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().clear();

Map<FusionLocale, RootLearningItem> mapBeforeUnMapping = learningItemService.findEquivalentLearningItems(c2);
assert mapBeforeUnMapping.size() == 2;
assert mapBeforeUnMapping.values().contains(c1);
assert mapBeforeUnMapping.values().contains(c2);

sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().clear();

boolean unMappingSuccessful = learningItemService.unMapEquivalentLearningItem(c1);
assert  unMappingSuccessful;

Hence it is always a good practice to clear/flush session after repository calls or hibernate transactions to make unit test case robust.

 

Design Pattern : Adapter in Java

The adapter pattern is a structural design pattern that allows you to repurpose a class with a different interface, allowing it to be used by a system which uses different calling methods.

Adopter Design pattern

 

A square peg in a round hole

A square peg in a round hole

 

The Adapter pattern translates one interface for a class into a compatible interface. It is used when two classes could conceptually work together but cannot because of implementation details. For this example, I create a few simple classes modeling the problem of fitting a square peg into a round hole. A square peg will sometimes fit into a round hole, as illustrated in figure depending on the relative sizes of the peg and the hole:

 

 

To determine if a square will fit into a circle, I use the formula shown here



Figure 2. Formula for determining if a square will fit into a circle

I could trivially solve the square peg/round hole problem with a simple utility class that handles conversions. But it exemplifies a larger problem. For example, what if I’m adapting a Button to fit on a type of Panel that it wasn’t designed for yet can be made compatible with? The problem of square pegs and round holes is a convenience simplification of the general problem addressed by the Adapter design pattern: adapting two incompatible interfaces. To enable square pegs to work with round holes, I need a handful of classes and interfaces to implement the Adapter pattern, as shown in Listing 1:

 

Listing 1. Square pegs and round holes in Java

 

public class SquarePeg {

private int width;

 

public SquarePeg(int width) {

this.width = width;

}

 

public int getWidth() {

return width;

}

}

 

public interface Circularity {

public double getRadius();

}

 

public class RoundPeg implements Circularity {

private double radius;

 

public double getRadius() {

return radius;

}

 

public RoundPeg(int radius) {

this.radius = radius;

}

}

 

public class RoundHole {

private double radius;

 

public RoundHole(double radius) {

this.radius = radius;

}

 

public boolean pegFits(Circularity peg) {

return peg.getRadius() <= radius;

}

}

 

To reduce the amount Java code, I’ve added an interface named Circularity to indicate that the implementer has a radius. This lets me write the RoundHole code in terms of round things, not just RoundPegs. This is a common concession in the Adapter pattern to make type resolution easier.

To fit square pegs into round holes, I need an adapter that adds Circularity to SquarePegs by exposing a getRadius() method, as shown in Listing 2:
Listing 2. Square peg adapter

 

public class SquarePegAdaptor implements Circularity {

private SquarePeg peg;

 

public SquarePegAdaptor(SquarePeg peg) {

this.peg = peg;

}

 

public double getRadius() {

return Math.sqrt(Math.pow((peg.getWidth()/2), 2) * 2);

}

}

 

To test that my adapter does in fact let me fit suitably sized square pegs in round holes, I implement the test shown in Listing 3:
Listing 3. Testing adaptation

 

@Test

public void square_pegs_in_round_holes() {

RoundHole hole = new RoundHole(4.0);

Circularity peg;

for (int i = 3; i <= 10; i++) {

peg = new SquarePegAdaptor(new SquarePeg(i));

if (i < 6)

assertTrue(hole.pegFits(peg));

else

assertFalse(hole.pegFits(peg));

}

}

 

In Listing 3, for each of the proposed widths, I wrap the SquarePegAdaptor around the creation of the SquarePeg, enabling hole’s pegFits() method to return an intelligent evaluation as to the fitness of the peg.

This code is straightforward, because this is a simple albeit verbose pattern to implement in Java. This paradigm is clearly the GoF design-pattern approach. However, the pattern approach isn’t the only way.

UML