Saturday, April 12, 2008

Refactoring : Self Encapsulate Field

Some times in a code base , especially inside a class , a field is referenced from many places.
Say you decide to move this field to another class .

A clean way of doing this is to first extract a getter method for that field within the same class .
Now with all occurances replaced by the getter method , move this getter method to the new class .
Similarly replace the code where the field is being set by the appropriate setter code and then move the setter code to another class .

Refactroing : Handling Duplicate Code

In legacy code bases we see lot of duplicate code . so how do we handle it ?

I am assuming you are using a tool that supports refactoring . In that case ,

Case 1:

If in a class you have lot of repeated code , use extract method refactoring to move the repeated code into a common method inside the class . Now replace if not automatically all occurance s of the repeated code with the call to the newly created method.

Case 2:

You have 2 sibling classes that have same piece of code .

Use extract method to create method with the same name in the 2 classes . Then use pull up refactoring to pull up the common method now in a super class . If the super class does not exist create it now .

Case 3:

You have 2 sibling classes that have almost the same piece of code , but some different bits here and there .

Use extract method to create method with the same signature in both the classes . Then identify the parts that are different , extract these different parts into methods of their own . Make sure that the names of these different parts is same in both sibling classes.

Now use template method design pattern , to create a common method in a super class of these 2 siblings . Using polymorph ism and inheritance to implement the different methods in the sibling classes.

Tuesday, April 08, 2008

C++: Object slicing and pass by value

In C++ , when a object is passed by value to a function that accepts a parameter then object slicing might happen. Consider the following class

class Base {
public:
virtual const char * toString() throw();

};

class Derived : public Base {
public:
virtual const char* toString() throw();
};

Derived derived;
Base base;

void doSomething(Base base){
....
}

doSomething(base);
doSomething(derived);


now we have 2 classes Base and Derived with a common virtual function that have been overridden in the derived class . We create 2 objects "derived" and "base".

Both of them are passed to the function doSomething . What happens in this case .

In the first case , it works the way its supposed to . In the second case , object slicing takes place and the members that are just of derived class are chopped off and the virtual function of the base class is called.

Monday, April 07, 2008

C++ : pointer to member function

class Foo{
public:
int iVal;
int Bar(int);
};


int Foo::* pm;

is a pointer to a member variable that is an integer.

pm = &Foo::iVal;

is used to initailize a pointer to a member variable

Foo foo;

int i = foo.*pm

is used to retrieve values of the pointer to member variable

int (Foo::*pmf) (int) = &Foo::Bar;

is a pointer to member function that is initialized by the address of member function Bar

C++ : Preventing implicit type conversion

class Foo{
public:

Foo(int n ){
...
}

};

Foo foo(42);
Foo boo = 42;

In the above mentioned snippet , the first constructor is matched and called. In the second case , for the assignment operator since the right hand side is 42 and since we have a constructor that takes integer as an argument . The corresponding constructor is called . This is syntactic sugar that can lead to lots of problems . To prevent something like this .

the explicit keyword should be used in front of constructors .

Wednesday, April 02, 2008

C++: Rethrowing exceptions

Consider the following piece of code

catch (Base& w)
{
...
throw;
}
catch (Base& w)
{
...
throw w;
}

What do you think is the difference between the 2 approaches above .

In the first case , the exception is re thrown . In the second case a copy is made and a new exception is thrown . Also the copy is based on the static type i.e
Base (copy constructor is called )

C++ : Object Copies in C++ are based on Object's Static Type Not Dynamic Type

Consider the following piece of code

class Base { ... };
class Derived: public Base { ... };

void passAndThrowDerived()
{
Derived local;
...
Base& rw = local;

throw rw;

}


In the above mentioned case . When a copy of rw is made while throwing it .
The copy constructor for the type is called . In this case the since rw is a reference to Base there fore the copy constructor of Base is called rather than the
Copy Constructor of Derived class.

C++ : Why are objects thrown as exception always copied

When an exception is thrown , the objects are generally copied. To explain this consider the following :

{
MyObject myObject;
cin >> myObject;
throw myObject;
}

if the object myObject was passed by reference then the same myObject would be thrown out . If the same object is thrown out then as soon as it goes out of scope , its destructor would get called and as a result of which some garbage would finally reach the exceptional handling code .

It is for this reason that copies of myObject are thrown rather than the original one .

Monday, March 24, 2008

Little Sugar : C++

In C++ have you imagined what would happen if the destructor of your class throws an exception . For starters , the object would not get destroyed properly . Actually in reality the control would go back to the callee from the current point directly.

Alright , now think what would happen if the destructor got called as a part of some exception handling code and this destructor threw an exception .

Since the active callee is calling the destructor due to some raised exception .
it would result in the terminate() function getting called and though would terminate the program immediately

Sunday, March 23, 2008

ThoughtWorks: Why it should be your first Software Company ??

ThoughtWorks , should be your first software company because:

You will learn..

  • What good software design is all about. You will hone the skills that will enable you to write good solid beautiful code .
  • Good coding practices e.g ( Test Driven Development .. )
  • To re factor code properly and effectively .
  • How to test your code like crazy
Other reasons why you will love Thoughtworks..

  • People adore Ruby and Python ;) and use them for their project work
  • Fellow developers try out cool and technologies like Erlang and haskell and incite you to try something or do something different.
  • Free Food
  • XBox , PlayStation
  • Table Tennis and other games .
  • Cool outings and free booze ;)
  • Amazing people from whom you 'll learn like crazy almost everyday , till the next 1.5 yrs
  • You can play pranks on the CEO and he wont fire you .
And finally an average ThoughtWorker with 1.5 yrs of work experience = most of the Software Engineers with 3.5 yrs of experience .

So if you want a head start , ThoughtWorks is the place to be ;)


Thursday, March 20, 2008

Java Thread Programming : Using Semaphores

The java concurrent framework provides Semaphore . Semaphores are useful when the end user wants to implement some kind of resource pool.

In a semaphore permits can be acquired and released . A semaphore when created can be initialized with the number of entries it can contain at any point of time .

Semaphore s = new Semaphore(N);

// acquire a permit

s.acquire();

// release a permit

s.release();

Java Concurrent Programming : CountDownLatch

CountDownLatch in the concurrent programming framework provided by java is pretty cool.
In principle it works like a binary latch . (Once set it remain in that state for ever )

So when would something like a countdownlatch be useful for thread programming .

Consider a scenario , you have a big task T to be done by N threads .

1) Now you want all the threads to be started at the same time so that they get equal opportunity
to participate in the completion of the task .

2) You want your main thread to do something when all the threads finish .

You can create two CountDownLatch objects.

CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(N);

Then you can construct all the threads like this

Thread thread = new Thread(){
public void run(){
try{
startLatch.await();
// do the task
endLatch.countDown();
}catch(InterruptedException e){
Thread.currentThread.interrupt();
}

}
}


thread.start();

so when the thread starts it will block cause of the CountDownLatch (await method call)

when startLatch.countDown() is called the latch opens and all the threads can flow now and start working .

similarly the main thread that is waiting for all threads to finish .

will continue when all the threads have called endLatch.countDown()

Monday, March 17, 2008

Eclipse Plugin Development : Small nuggets

Small snuggets for eclipse plugin development are small snippets of code useful in eclipse plugin development.

In eclipse windows that you see contains pages . Each of this page hosts a view or an editor .
Generally these editors are not hosted directly but indirectly via references ( aka proxies to the actual editor / views )

So to get reference to the actual editors / views from the pages use code like this :

IWorkbenchPage page = getPage();
IEditorReference[] editors = page.getEditorReferences();

Once you have the references you can get the actual hosted editor / view.

Editors in eclipse implement IEditorPart , so to get an editor some thing like this would work:

IEditorPart editor = editor.getEditor(true);

To reveal IJavaElement in the editor ( basically any java method , entity ) using JDT ( eclipse for java development is based on it )

JavaUI.revealInEditor(part , javaElement);

To add an action (aka tool bar item ) in the toolbar for your view something like this would work :

IActionBars actionBars = view.getViewSite().getActionBars();
IToolBarManager manager = actionBars.getToolBarManager();
manager.add(new MyToolBarItem());

Thursday, March 13, 2008

Eclipse Plugin Development : Programatically saving all open editors

In Eclipse editors are contained in WorkbenchWindow . To save all open editors one can call code like this

IWorkbench workbench = PlatformUI.getWorkbench();
return workbench.saveAllEditors(false);

This will get the current workbench and save all open editors.

Sunday, March 09, 2008

Java : Inner Classes and Parent Reference Escaping

When an inner class is created inside a class in java, it transparently contains a reference to its parent class. If by chance this reference leaks out , it compromises the thread safety of the parent class. To avoid these kind of issues , factory methods should be used to create inner classes .

Another thing that should be best avoided is : starting of a thread inside the constructor of a class.
Since the thread object also shares the reference to its parent class, this reference might be in an inconsistent state when the thread is started .

To prevent these type of scenarios factory methods are best.

e.g

public class Prent {

private childThread;

private Parent(){
childThread = new Thread();
}

public static Parent newInstance(){
Parent parent = new Parent();
childThread.start();
return parent
}

}

Monday, March 03, 2008

Eclipse : Adding nature to a project

In Eclipse plugin development terminology adding a nature to a project is like tagging the project with a specific tag . Generally natures are used to install various builders for the project. I will talk about builders in a later post . Lets look at some code and see how how natures are added to projects:

IProjectDescription projectDescription = project.getDescription();

description is a description of the project . It gives a lot of information including the entire list of
nature ids and build commands.

String[] ids = projectDescription.getNatureIds();
String[] newIds = new String[ids.length + 1];
System.arraycopy(ids,0,newIds,0,ids.length);
newIds[ids.length] = YOUR_NATURE_ID;
projectDescription.setNatureIds(newIds);
project.setDescription(projectDescription,null);

the remove nature id code is kind of similar .

To actually implement your nature , you need to contribute to the extension point
org.eclipse.core.resources.natures

Basically that boils down to adding something like this in your plugin.xml

id="yourNatureID"
name="Your Nature Name">







"id" here represents the id of the nature .
"name" represents the name of the nature .
"class" represents the class implements the IProjectNature .

the requires-nature here represents the nature id that is required for this nature to be successfully installed .

Next , finally the class that implements the IProjectNature interface.

public class YourProjectNature implements IProjectNature {
IProject project;
public YourProjectTestNature() {
}
public IProject getProject() {
return project;
}
public void setProject(IProject project) {
this.project= project;
}
}

Sunday, March 02, 2008

Little Sugar : C++

The only to initialize const pointers in c++ within a class , is via member initialization list.

class MyClass{

Data * const data_ptr;

MyClass(Data * const value) : data_ptr(value)
{}
};

Tuesday, February 05, 2008

Remove from Array : Java Quickie

lets say you have a problem . You have an array of N numbers . You want to remove the i th number . Then you need a new array not containing the j th number . You are using java . How can you do it ??

Here 's a quickie:

int[] result = null;

result = new int[n-1];
if(i > 0 ) System.arraycopy(array,0,result,0,i);
if(i+1 < n ) System.arraycopy(array,i+1,result,i,n-1-i);

}

This is quick way of removing the element you need and getting a new array devoid of the removed number .

Thursday, January 31, 2008

Thnking in Heaps : Algorithms

An interative version of max-Heap :

void iter_maxHeapify(int * a,int rootIndex,int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = left(rootIndex);

for(int largest = rootIndex;
(leftIndex < heapLength) || (rightIndex < heapLength);
leftIndex = left(rootIndex),rightIndex = right(rootIndex)){

if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(rootIndex != largest){
swap(a[largest],a[rootIndex]);
rootIndex = largest;
}
}

}

Building the Heap:

void buildMaxHeap(int * a,int heapLength){
for(int i = heapLength/2;i >=0;i--){
maxHeapify(a,i,heapLength);
}
}


Sorting a heap:

void heapSort(int * a ,int heapLength){
buildMaxHeap(a,heapLength);
for(int i = 0;i < heapLength;i++){
swap(a[i],a[heapLength-1]);
maxHeapify(a,1,heapLength-i-1);
}
}

Tweaking JDT : eclipse

To create a new Java Class/Interface using JDT you can use the following code :

IJavaproject prj;
IPackage package;

prj.createType(package, "your class body");

To find subclasses of a given type using JDT use :

IType type = prj.findType("class name");
ITypeHierarchy typeHierarchy = type.newTypeHierarchy(prj,new NullProgressMonitor());
IType[] subclasses = typeHierarchy.getAllSubtypes(prj);



To check if the given class aka IType is part of this project

IType type;

IResource resource = type.getUnderlyingResource();

boolean isPartOfClass = resource.getProject().equals(project.getProject());