Here are 2 simple rules to allocating and deleting objects.
MyObject * myPointer;
while updating object memory always use code like this:
MyObject::update(){
delete myPointer;
myPointer = NULL;
myPointer = MyObject::CreateNew();
}
while deallocating always use code like this:
MyObject::~MyObject(){
delete myPointer;
myPointer = NULL;
}
Monday, May 19, 2008
Tuesday, April 29, 2008
Refactoring Large Methods: Refactoring
Refactoring Large Methods:
"The object programs that live best and longest
are those with short methods. Programmers new to
objects often feel that no computation ever takes
place, that object programs are endless sequences
of delegation. When you have lived with such a
program for a few years, however, you learn just
how valuable all those little methods are. All of
the payoffs of indirection—explanation, sharing,
and choosing—are supported by little methods" -
Refactoring Book - Martin Fowler
Large Methods are code smells.To refactor large
methods follow the following methods :
-> Use extract method refactoring to extract a
lot of small methods
-> In case of a method having a number of
temporary variables , temporary variables can be
replaced by query methods
-> A query method is a small method that is
intended to replace variables .
e.g int myVariable = oldValue1 * oldValue2
create a new method like
int getValue(){
return oldValue1 * oldValue2;
}
now replace all usages to myVariable by the
method getValue()
-> Then try introduce Parameter Object
refactoring to take care of huge number
parameters in the extracted method
-> Use Preserve Whole Object Refactoring in case
lot of parameters are passed to methods , and
each of these parameters are local values.
-> If still extract method refactoring becomes
difficult use "Replace method with Method Object"
refactoring
"The object programs that live best and longest
are those with short methods. Programmers new to
objects often feel that no computation ever takes
place, that object programs are endless sequences
of delegation. When you have lived with such a
program for a few years, however, you learn just
how valuable all those little methods are. All of
the payoffs of indirection—explanation, sharing,
and choosing—are supported by little methods" -
Refactoring Book - Martin Fowler
Large Methods are code smells.To refactor large
methods follow the following methods :
-> Use extract method refactoring to extract a
lot of small methods
-> In case of a method having a number of
temporary variables , temporary variables can be
replaced by query methods
-> A query method is a small method that is
intended to replace variables .
e.g int myVariable = oldValue1 * oldValue2
create a new method like
int getValue(){
return oldValue1 * oldValue2;
}
now replace all usages to myVariable by the
method getValue()
-> Then try introduce Parameter Object
refactoring to take care of huge number
parameters in the extracted method
-> Use Preserve Whole Object Refactoring in case
lot of parameters are passed to methods , and
each of these parameters are local values.
-> If still extract method refactoring becomes
difficult use "Replace method with Method Object"
refactoring
Sunday, April 27, 2008
QuickSort : C++
i was having a re look at quick sort.
Here is the code in c++ :
The idea of quicksort is to take an array and divide it into partitions .
First a key is chosen . That is called the pivot . Here 'x' is the pivot .
Based on the value of 'x' other values in an array are put in 2 partitions .
One partition that contains values less than 'x' and other partition contains values greater than x .
Here i and j are used to mark the extent of these 2 partitions .
The beauty of the algorithm lies in the fact , how integers are used to manipulate partitions . 'i' is initially set to value that precedes a real boundary . 'j' is set to the first location in the array . Now as values are compared with 'x' ( the key)
if value is less than 'x' the partition extent marked by 'i' are increased , else the partition extent marked by 'j' is increased . In the first case where values of 'i' is less than 'x' and since 'i' now occupies what 'j' occupied the values at those indices are swapped .
the partition method does in place sorting of the array and the quickSort method is responsible for choosing partitons .
Here is the code in c++ :
template< class T >
int partition(T a[], int p, int r){
T x = a[r];
int i = p - 1;
for(int j = p;j < r;j++){
if(a[j] <= x){
i++;
swap(a[i],a[j]);
}
}
swap(a[i+1] , a[r]);
return i + 1;
}
template< class T >
void quickSort(T a[], int p, int r){
if(p < r){
int q = partition(a, p , r);
quickSort(a, p , q-1);
quickSort(a, q+1 , r);
}
}
The idea of quicksort is to take an array and divide it into partitions .
First a key is chosen . That is called the pivot . Here 'x' is the pivot .
Based on the value of 'x' other values in an array are put in 2 partitions .
One partition that contains values less than 'x' and other partition contains values greater than x .
Here i and j are used to mark the extent of these 2 partitions .
The beauty of the algorithm lies in the fact , how integers are used to manipulate partitions . 'i' is initially set to value that precedes a real boundary . 'j' is set to the first location in the array . Now as values are compared with 'x' ( the key)
if value is less than 'x' the partition extent marked by 'i' are increased , else the partition extent marked by 'j' is increased . In the first case where values of 'i' is less than 'x' and since 'i' now occupies what 'j' occupied the values at those indices are swapped .
the partition method does in place sorting of the array and the quickSort method is responsible for choosing partitons .
Sunday, April 13, 2008
C++ : template specialization
template <>
char* Add<char*>(char* a , char* b){
return strcat(a,b);
}
char * res = Add<char*>("foo","bar");
This code refers to a new type of syntax for templates called template specialization syntax.
Generally when you write code for templates .
you end up using stuff like
template<class>
but say you want the same generic code for many cases . In the above mentioned code for example if the add function used the "+" operator to add two types it would have not worked for char* pointers , because the "+" operator does not work with them .
by using the syntax as mentioned above its possible to tell the compiler that there are exceptions to your generic code and that for special cases these new methods should be called.
char* Add<char*>(char* a , char* b){
return strcat(a,b);
}
char * res = Add<char*>("foo","bar");
This code refers to a new type of syntax for templates called template specialization syntax.
Generally when you write code for templates .
you end up using stuff like
template<class>
but say you want the same generic code for many cases . In the above mentioned code for example if the add function used the "+" operator to add two types it would have not worked for char* pointers , because the "+" operator does not work with them .
by using the syntax as mentioned above its possible to tell the compiler that there are exceptions to your generic code and that for special cases these new methods should be called.
C++ : The need for virtual destructors
With the advent of object oriented languages the use of polymophism became very common .
In C++ when you have a derived Class and a base class .
when you have code like this :
class Base {
};
class Derived : public Base{
};
Base * p = new Derived();
delete p;
what's wrong with it .
Since this piece of code is based on polymorphism , the base pointer will refer to an instance of a derived class object .
when delete on the pointer p is called , due to static typing in c++ , destructor of Base is called , instead of Derived . To correct this
virtual ~Base(){
}
should be added . By making the destructor virtual the destructor of the derived class would be called now .
In C++ when you have a derived Class and a base class .
when you have code like this :
class Base {
};
class Derived : public Base{
};
Base * p = new Derived();
delete p;
what's wrong with it .
Since this piece of code is based on polymorphism , the base pointer will refer to an instance of a derived class object .
when delete on the pointer p is called , due to static typing in c++ , destructor of Base is called , instead of Derived . To correct this
virtual ~Base(){
}
should be added . By making the destructor virtual the destructor of the derived class would be called now .
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 .
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.
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.
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
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 .
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 )
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.
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 .
{
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
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..
So if you want a head start , ThoughtWorks is the place to be ;)
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
- 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 .
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();
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()
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());
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.
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
}
}
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;
}
}
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
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)
{}
};
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 .
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);
}
}
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());
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());
Marker Resolutions for markers : Eclipse
In Eclipse it is possible to associate marker resolutions with markers . This is more commonly known as Quick Fixes also evoked by using the key combination Ctrl + 1.
You need to implement the extension point with id :
"org.eclipse.ui.markerResolution"
for the markerType attribute under that extension point specify the marker id
you want to associate this resolution with .
Then in the "class" attribute specify the class that implements the MarkerResolutionGenerator
You need to implement the extension point with id :
"org.eclipse.ui.markerResolution"
for the markerType attribute under that extension point specify the marker id
you want to associate this resolution with .
Then in the "class" attribute specify the class that implements the MarkerResolutionGenerator
The world of wide characters aka Unicode
Wide characters aka unicode characters are characters that occupy 16 bits per character .
In C we have a header file specifically for that .
that contains special data type for that
wchar_t
wchar_t * text = L"Hello";
is used to tell the compiler that it should use 16 bit aka wide variants of characters.
strlen for wide characters becomes wcslen .
To take care of these problems windows provides TCHAR.H
it contains many functions starting with _t , like. ..
_tprintf
by defining _UNICODE
like
#define _UNICODE
its possible to use 16 bit / 8 bit versions of functions without much verbosity .
the same _t functions then correctly map on to their 8 bit and 16 bit counter parts.
In C we have a header file specifically for that .
that contains special data type for that
wchar_t
wchar_t * text = L"Hello";
is used to tell the compiler that it should use 16 bit aka wide variants of characters.
strlen for wide characters becomes wcslen .
To take care of these problems windows provides TCHAR.H
it contains many functions starting with _t , like. ..
_tprintf
by defining _UNICODE
like
#define _UNICODE
its possible to use 16 bit / 8 bit versions of functions without much verbosity .
the same _t functions then correctly map on to their 8 bit and 16 bit counter parts.
Monday, January 28, 2008
Fnding markers in a workspace : eclipse
If you have a marker or you know a marker id :
let the id be : org.my.marker
then all markers of that type can be easily found . The way to found those markers is :
IWorkspaceRoot root = ResourcePlugin.getWorkspace().getRoot();
root.findMarkers("org.my.marker",false,IResource.DEPTH_INFINITE);
To create a marker :
getProject().createMarker("org.my.marker",false,IResource.DEPTH_INFINITE);
generally since workspace changes are expensive , an IWorkspaceRunnable should be used
to batch many workspace operations together .
IWorkspaceRunnable runnable = new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) {
IMarker marker = resource.createMarker(markerId);
setAttributes(marker);
}
};
the setAttributes method sets the marker . This generally boild down to populating a hashtable
and setting it .
resource.getWorkspace().run(runnable , null);
An imageProvider can be specified in the marker definition to define an image for the marker .
let the id be : org.my.marker
then all markers of that type can be easily found . The way to found those markers is :
IWorkspaceRoot root = ResourcePlugin.getWorkspace().getRoot();
root.findMarkers("org.my.marker",false,IResource.DEPTH_INFINITE);
To create a marker :
getProject().createMarker("org.my.marker",false,IResource.DEPTH_INFINITE);
generally since workspace changes are expensive , an IWorkspaceRunnable should be used
to batch many workspace operations together .
IWorkspaceRunnable runnable = new IWorkspaceRunnable(){
public void run(IProgressMonitor monitor) {
IMarker marker = resource.createMarker(markerId);
setAttributes(marker);
}
};
the setAttributes method sets the marker . This generally boild down to populating a hashtable
and setting it .
resource.getWorkspace().run(runnable , null);
An imageProvider can be specified in the marker definition to define an image for the marker .
Sunday, January 27, 2008
Overloading the && , || , " , " operators : C++
&& , || and comma operator in C++ are very useful . && and || are useful in short circuiting code .
Now when you overload these operator at the global level or at the member level . Then at that case
an expression like
(exp1 && exp2)
gets transformed into something like
(exp1.operator&&(exp2))
that being the case , both the arguments exp1 and exp2 are evaluated . Hence since we are not
sure in which order the arguments are evaluated , short circuiting is thrown out of the window.
So commonsense says it makes sense not to overload the && , || and the comma operator .
Now when you overload these operator at the global level or at the member level . Then at that case
an expression like
(exp1 && exp2)
gets transformed into something like
(exp1.operator&&(exp2))
that being the case , both the arguments exp1 and exp2 are evaluated . Hence since we are not
sure in which order the arguments are evaluated , short circuiting is thrown out of the window.
So commonsense says it makes sense not to overload the && , || and the comma operator .
Friday, January 25, 2008
Little Sugar (Trees : relations)
A complete binary tree has odd number of nodes .
Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree
The number of internal nodes + 1 = number of leaves
number of internal nodes = number of leaves - 1
n = number of nodes
n = number of leaves + number of internal nodes
n +1 = 2 * number of leaves
number of leaves = (n+1)/2
The number of total nodes upto height h :
= pow(2,h+1) - 1
The number of nodes for any binary tree at height (h) :
= ceil(n / pow(2,h+1))
Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree
The number of internal nodes + 1 = number of leaves
number of internal nodes = number of leaves - 1
n = number of nodes
n = number of leaves + number of internal nodes
n +1 = 2 * number of leaves
number of leaves = (n+1)/2
The number of total nodes upto height h :
= pow(2,h+1) - 1
The number of nodes for any binary tree at height (h) :
= ceil(n / pow(2,h+1))
Little Sugar (Trees : relations)
A complete binary tree has odd number of nodes .
Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree
The number of internal nodes + 1 = number of leaves
number of internal nodes = number of leaves - 1
n = number of nodes
n = number of leaves + number of internal nodes
n +1 = 2 * number of leaves
number of leaves = (n+1)/2
Number of leaves + number of internal nodes ( both even) +
1 = number of nodes in a tree
The number of internal nodes + 1 = number of leaves
number of internal nodes = number of leaves - 1
n = number of nodes
n = number of leaves + number of internal nodes
n +1 = 2 * number of leaves
number of leaves = (n+1)/2
Sunday, January 20, 2008
type conversions : C++
Implicit type conversions in C++ can be quite problematic . To take care of type conversion issues , C++ provides us with a simple mechanism .
use the explicit keyword .
so for a class like Array
class Array{
public:
explicit Array(int size){
...
}
};
so by using the explicit keyword in this manner , you tell the compiler to use the constructor only
when explicit object construction is taking place.
another way around the explicit keyword is :
class Array{
public:
class ArraySize{
public:
ArraySize(int size)
this->size = size;
}
private:
int size;
};
Array(ArraySize size){
...
}
};
So by using the nested public ArraySize class in this manner , you 'll see that even if the compiler makes implicit type conversions for cases like
Array a(10);
the integer 10 is correctly transformed to ArraySize and the constructor having ArraySize as a parameter is called .
The beauty of this last technique is that it works in many cases , cause the compiler is allowed to make 1 implicit type conversion but now two.
use the explicit keyword .
so for a class like Array
class Array{
public:
explicit Array(int size){
...
}
};
so by using the explicit keyword in this manner , you tell the compiler to use the constructor only
when explicit object construction is taking place.
another way around the explicit keyword is :
class Array{
public:
class ArraySize{
public:
ArraySize(int size)
this->size = size;
}
private:
int size;
};
Array(ArraySize size){
...
}
};
So by using the nested public ArraySize class in this manner , you 'll see that even if the compiler makes implicit type conversions for cases like
Array a(10);
the integer 10 is correctly transformed to ArraySize and the constructor having ArraySize as a parameter is called .
The beauty of this last technique is that it works in many cases , cause the compiler is allowed to make 1 implicit type conversion but now two.
Tuesday, January 15, 2008
Default Constructors : C++
Just imagine if your class does not have a default constructor and infact has one that accepts a parameter . In that case few things might not be possible . To illustrate
class Piece{
public:
Piece(int n);
};
Things like these will not work
Piece pieces[10];
Why?? -> cause u don t have a default constructor and trying to create an array of 10 piece instances just tries to call exactly that for every one of them .
Piece * pieces = new Piece[10];
wont work.
How to get it working :
Piece pieces[] = {
Piece(1),
Piece(2),
Piece(3)
};
Another way to get it working would be :
Piece * pieces[10];
: here you are just declaring an array of 10 Piece pointers;
Or Piece* *pieces = new Piece*[10];
But you still need to initialize all the pointers like this :
for(int i = 0;i < 10;i++){ pieces[i] = new Piece(i); }
Another way of initializing accomplishing this would be :
void * memory = operator new[](10 * sizeof(Piece));
this will create memory for 10 piece objects . Now we can go an and make the memory more specific to Piece :
Piece * pieces = static_cast<piece*>(memory);
Now that pieces points to memory for Piece , lets initialize the pieces with code like
for(int i = 0;i < 10;i++){ new(&pieces[i]) Pieces(i); }
Though this arcane technique will get the job done . It seriously is arcane . Not only that it also has the disadvantage of boilerplate code like this :
for(int i = 9;i >= 0;i--){
pieces[i].~Piece();
}
operator delete[] memory;
If we do not follow the 1st approach , we see that what problems we can face . A small hack to get around this problem would be :
class Piece{
public:
Piece(int n = Piece::UNDEFINED);
private:
static const int UNDEFINED;
};
const int Piece::UNDEFINED = -1;
class Piece{
public:
Piece(int n);
};
Things like these will not work
Piece pieces[10];
Why?? -> cause u don t have a default constructor and trying to create an array of 10 piece instances just tries to call exactly that for every one of them .
Piece * pieces = new Piece[10];
wont work.
How to get it working :
Piece pieces[] = {
Piece(1),
Piece(2),
Piece(3)
};
Another way to get it working would be :
Piece * pieces[10];
: here you are just declaring an array of 10 Piece pointers;
Or Piece* *pieces = new Piece*[10];
But you still need to initialize all the pointers like this :
for(int i = 0;i < 10;i++){ pieces[i] = new Piece(i); }
Another way of initializing accomplishing this would be :
void * memory = operator new[](10 * sizeof(Piece));
this will create memory for 10 piece objects . Now we can go an and make the memory more specific to Piece :
Piece * pieces = static_cast<piece*>(memory);
Now that pieces points to memory for Piece , lets initialize the pieces with code like
for(int i = 0;i < 10;i++){ new(&pieces[i]) Pieces(i); }
Though this arcane technique will get the job done . It seriously is arcane . Not only that it also has the disadvantage of boilerplate code like this :
for(int i = 9;i >= 0;i--){
pieces[i].~Piece();
}
operator delete[] memory;
If we do not follow the 1st approach , we see that what problems we can face . A small hack to get around this problem would be :
class Piece{
public:
Piece(int n = Piece::UNDEFINED);
private:
static const int UNDEFINED;
};
const int Piece::UNDEFINED = -1;
Hello Windows Facts
windows.h is the mother of all other header files in windows . It includes other header files .
Windef.h => basic type defintions
winnt.h => type definitions for unicode support.
winbase.h => kernel functions.
winusr.h => user interface functions
wingdi.h => graphics device interface functions.
WINAPI => is a naming convention like __stdcall .
Windef.h => basic type defintions
winnt.h => type definitions for unicode support.
winbase.h => kernel functions.
winusr.h => user interface functions
wingdi.h => graphics device interface functions.
WINAPI => is a naming convention like __stdcall .
Moving Patterns
If you have a layer of objects and each object in that layer shares a certain set of methods . Those methods can be moved in a common super type . This super type that is common for a whole layer is called a layer super type .
Remote Facade is a facade for objects that are not part of a given process address space , in other words whenever you need to access objects that line in other processes you should use a remote facade to encapsulate and operate on remote objects via the facade . The facade make a number of operation invisible and may also cache the most commonly use objects.
When ever data has to marshaled across processes boundaries and lot of data needs to sent . A Data Transfer Object can be used . The parameters are packed into a simple POJO called a DTO and marshaled . On the server side , the server used some sort of assembler to break the DTO and set the corresponding properties on domain objects.
Remote Facade is a facade for objects that are not part of a given process address space , in other words whenever you need to access objects that line in other processes you should use a remote facade to encapsulate and operate on remote objects via the facade . The facade make a number of operation invisible and may also cache the most commonly use objects.
When ever data has to marshaled across processes boundaries and lot of data needs to sent . A Data Transfer Object can be used . The parameters are packed into a simple POJO called a DTO and marshaled . On the server side , the server used some sort of assembler to break the DTO and set the corresponding properties on domain objects.
Friday, January 11, 2008
Floating in a Tree
If you have a priority queue setup of many nodes. Lets say we want to bring the node with the highest value to the top . IN orther words if i have given a heap than how do i modify the heap so that the biggest element is always present at the root.
One simple logic can be . Given a root node of a subtree .
void maxHeapify(int * a,int rootIndex, int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = right(rootIndex);
if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(largest != rootIndex){
swap(a[largest],a[rootIndex]);
maxHeapify(a,largest,heapLength);
}
}
The worst case time for floating a node to any another node depending on your optimization would be approximately equal to the height of the tree , which would generally result in something like ~ lg(N) . To give a counter example for a max Heap operating in a heap . lets give a value of 0 to the root , and let all the other nodes be 1 . In that case the program would go all the way down the heap till the last leaf .
One simple logic can be . Given a root node of a subtree .
- Assume the root node is the largest node .
- Now compare the value of root node with left child and mark the one with the bigger value as biggest
- Then compare biggest with the right child now and make the bigger of the two as the new biggest.
- now repeat the above mentioned steps with the new largest node
void maxHeapify(int * a,int rootIndex, int heapLength){
int largest = rootIndex;
int leftIndex = left(rootIndex);
int rightIndex = right(rootIndex);
if(leftIndex < heapLength && a[rootIndex] < a[leftIndex]){
largest = leftIndex;
}
if(rightIndex < heapLength && a[largest] < a[rightIndex]){
largest = rightIndex;
}
if(largest != rootIndex){
swap(a[largest],a[rootIndex]);
maxHeapify(a,largest,heapLength);
}
}
The worst case time for floating a node to any another node depending on your optimization would be approximately equal to the height of the tree , which would generally result in something like ~ lg(N) . To give a counter example for a max Heap operating in a heap . lets give a value of 0 to the root , and let all the other nodes be 1 . In that case the program would go all the way down the heap till the last leaf .
Thursday, January 10, 2008
casts in C++
C++ provides us with 4 types of casting mechanisms . Namely:
In C casting is done via () operator
int i = 7;
e.g double d = (double) i;
in c++ to do something like this one should use static_cast .
e.g double d = static_cast<double>(i);
const_cast
const_cast is used to remove constness of an object .
jump(Person * person);
Person p;
const Person& constPerson = p;
then some thing like this wont work.
jump(&constPerson) , cause jump expects a non const object . To fix this you would have to use something like this.
jump(const_cast<person*>(&constPerson));
dynamic_cast
This cast is used with inheritance hierarchies . Say to cast a between pointers or references of base classes to references or pointers of derived classes.
e.g
Mammal * mammal;
jump(dynamic_cast<person*>(mammal));
if there was a function like
jump(Person& person); then
we would have something like
jump(dynamic_cast<person&>(*mammal));
if the casting is not possible , the dynamic_cast mechaism throws an excetion or the result is null (This is implementation specific)
- static_cast
- const_cast
- dynamic_cast
- reinterpret_cast
In C casting is done via () operator
int i = 7;
e.g double d = (double) i;
in c++ to do something like this one should use static_cast .
e.g double d = static_cast<double>(i);
const_cast
const_cast is used to remove constness of an object .
jump(Person * person);
Person p;
const Person& constPerson = p;
then some thing like this wont work.
jump(&constPerson) , cause jump expects a non const object . To fix this you would have to use something like this.
jump(const_cast<person*>(&constPerson));
dynamic_cast
This cast is used with inheritance hierarchies . Say to cast a between pointers or references of base classes to references or pointers of derived classes.
e.g
Mammal * mammal;
jump(dynamic_cast<person*>(mammal));
if there was a function like
jump(Person& person); then
we would have something like
jump(dynamic_cast<person&>(*mammal));
if the casting is not possible , the dynamic_cast mechaism throws an excetion or the result is null (This is implementation specific)
Wednesday, January 09, 2008
Little Sugar: C++ references
C++ references are a variant of const pointers that always point to something .
Now consider
string s1("abc");
string s2("def");
string & refTos1 = s1;
Now refTosi points to s1.
Even after refTos1 = s2. Its still points to s1 . But the value of s1 is now changed from "abc" to "def"
Now consider
string s1("abc");
string s2("def");
string & refTos1 = s1;
Now refTosi points to s1.
Even after refTos1 = s2. Its still points to s1 . But the value of s1 is now changed from "abc" to "def"
Tuesday, January 08, 2008
Little Sugar : Big Oh
Consider a scenario where you had a list of N numbers . Now say you have an algorithm that finds the does some sort of comparison . If comparison strategy used compares every element with all the succeeding elements . Then on an average the number of comparisons possible in different cases would be something like this :
(n) + (n-1) + (n-2) .... 1
for the 1 st case we have n comparisons
for the 1 st element we have n-1 comparisons
for the 2 nd element we have n-2 comparison .. and so on.
the sum is = ((n)*(n+1))/2 = O(n^2)
(n) + (n-1) + (n-2) .... 1
for the 1 st case we have n comparisons
for the 1 st element we have n-1 comparisons
for the 2 nd element we have n-2 comparison .. and so on.
the sum is = ((n)*(n+1))/2 = O(n^2)
Saturday, December 29, 2007
Java + meta programming framework == EMF
Meta programming is a popular buzz word these days . There is a framework for java , called EMF (Eclipse Modeling Framework ) that tries to add that support to java . The framework makes meta programming look like total crap . It overly complicates stuff to such a large extent that you just feel like just removing it from your project code.
So in short meta-programming in EMF + java = night mare :(
But on the other hand if you are building your domain layer . EMF is a pretty decent choice . It has in build support for a notification mechanism that allows you to listen to various model changes . So your GUI can become lightly couple to the domain layer and can become very responsive .
If other people have tried EMF , i would love to hear their experiences.
So in short meta-programming in EMF + java = night mare :(
But on the other hand if you are building your domain layer . EMF is a pretty decent choice . It has in build support for a notification mechanism that allows you to listen to various model changes . So your GUI can become lightly couple to the domain layer and can become very responsive .
If other people have tried EMF , i would love to hear their experiences.
Monday, December 17, 2007
Little Sugar : Sequences
Given a sequence , the sum of elements from the i th position to the j th position can be easily found by adding the elements from the i th location to the j th location . A better optimization over this is generally to do a cumulative sum of all the elements upto the j th element . Then the
sum of any sub sequence can be found by taking the starting i th location and the ending j th location and subtracting the result of the element at the i th place from the element at the j th place .
sum of any sub sequence can be found by taking the starting i th location and the ending j th location and subtracting the result of the element at the i th place from the element at the j th place .
Saturday, December 15, 2007
All About Heap Sort -- Part 1
HeapSort is a sorting algorithm . It performs in place sorting . Its complexity it O(n lg n).
It makes use of a data structure called heap. The heap data structure is like an array which looks like a complete binary tree.If you imagine the heap array as a tree then each node in the tree will have left and right children . Each of the nodes in the tree map on to elements in the array . Every parent at index (i) will have a left child at index (2 * i ) and a right child at index (2 *i +1 ) in the array . Nodes in the heap follow the heap property . Heaps can be a max heap or a min heap.
In a max heap every Parent will have a higher value than any of its children . Its the opposite in the case of min heap. For the heap sort algorithm a max heap is used , generally a min heap is used for a priority queue.
Since a heap of (n) elements is like a complete binary tree its height is (lg n ) and all basic operations run in a time proportional to the height of the tree . Heap is a complete binary tree filled with elements at all levels except the last one . So the max number of elements in a heap of height (h) is (pow(2,h+1) - 1) . The minimum number of elements is equal to the number of elements in a heap of height (h-1) + 1 element. We add the extra one element because in the actual heap there would be at least one element on the last row containing leaves.
So the minimum number of elements = (pow(2,h) -1 ) + 1
The height of a heap is actually = floor(lg n ) . Since , a heap with height h will have elements (n) = pow(2,h) <= n <= pow(2,h+1)-1 < pow(2,h-1) and hence
h <= lg n < 1 =""> height = floor ( lg n )
It makes use of a data structure called heap. The heap data structure is like an array which looks like a complete binary tree.If you imagine the heap array as a tree then each node in the tree will have left and right children . Each of the nodes in the tree map on to elements in the array . Every parent at index (i) will have a left child at index (2 * i ) and a right child at index (2 *i +1 ) in the array . Nodes in the heap follow the heap property . Heaps can be a max heap or a min heap.
In a max heap every Parent will have a higher value than any of its children . Its the opposite in the case of min heap. For the heap sort algorithm a max heap is used , generally a min heap is used for a priority queue.
Since a heap of (n) elements is like a complete binary tree its height is (lg n ) and all basic operations run in a time proportional to the height of the tree . Heap is a complete binary tree filled with elements at all levels except the last one . So the max number of elements in a heap of height (h) is (pow(2,h+1) - 1) . The minimum number of elements is equal to the number of elements in a heap of height (h-1) + 1 element. We add the extra one element because in the actual heap there would be at least one element on the last row containing leaves.
So the minimum number of elements = (pow(2,h) -1 ) + 1
The height of a heap is actually = floor(lg n ) . Since , a heap with height h will have elements (n) = pow(2,h) <= n <= pow(2,h+1)-1 < pow(2,h-1) and hence
h <= lg n < 1 =""> height = floor ( lg n )
Tuesday, December 04, 2007
Monday, November 26, 2007
What would happen if locks in Java were non re-entrant
Locks in java are re-entrant , that aids locking to work effectively with Object Oriented Programming . Why ??
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Thursday, November 22, 2007
Little Sugar : Showing an Eclipse view
You can use an IWorkbenchPage.showView(viewId) to programatically show a view .
To access the current active page you can use the following code
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = workbenchWindow.getActivePage();
To access the current active page you can use the following code
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = workbenchWindow.getActivePage();
Little Sugar : Eclipse Views live in pages
In eclipse we have a workbench window in which different types of pages exist .
thats is WorkbenchWindow > Pages
> ActivePage
a workbench window also contains the currently active page .
Each page is a IWorkbenchPage. A WorkbenchPage contains many views .
Each view is a IViewPart.
So Views live in pages and pages live in workbench window
thats is WorkbenchWindow > Pages
> ActivePage
a workbench window also contains the currently active page .
Each page is a IWorkbenchPage. A WorkbenchPage contains many views .
Each view is a IViewPart.
So Views live in pages and pages live in workbench window
Wednesday, November 21, 2007
Little Sugar : Why constantness helps
Say u have a method like this :
const Rational operator*(const Rational& lhs,
const Rational& rhs);
Now consider this (a * b ) = c
If the above method returned a non const object then the above mentioned
assignment would make sense , ideally it should not as it would be violating the
api contract for built ins.
Tuesday, November 20, 2007
Little Sugar : Pointers to Member Functions
Pointers to member functions is a feature that not many people use but its good to know .
So lets have a look at it . Lets assume you have a class
class Person ;
typedef void (Person::*PPMF)();
class Person{
public :
static PPMF blahFunction(){
return &(Person::processAddress);
}
private :
Address address;
void processAddress();
};
Here blah function returns a pointer to the member function processAddress .
Now you have the pointer to the member address , even if it private ( its evil to to access private member function like this) you can invoke this member function now on an instance of a person
class.
Person boo;
eg. PPMF pmf = boo.blahFunction();
invoke the member function like this :
(boo.*pmf)();
So lets have a look at it . Lets assume you have a class
class Person ;
typedef void (Person::*PPMF)();
class Person{
public :
static PPMF blahFunction(){
return &(Person::processAddress);
}
private :
Address address;
void processAddress();
};
Here blah function returns a pointer to the member function processAddress .
Now you have the pointer to the member address , even if it private ( its evil to to access private member function like this) you can invoke this member function now on an instance of a person
class.
Person boo;
eg. PPMF pmf = boo.blahFunction();
invoke the member function like this :
(boo.*pmf)();
Tuesday, November 13, 2007
Little Sugar : Casting away constant ness
In C++ if you create a constant object , say
const String A("Hello World");
String& B = const_cast(A);
can be used to create a non constant reference to the so called constant object and hence
manipulate it .
const String A("Hello World");
String& B = const_cast
can be used to create a non constant reference to the so called constant object and hence
manipulate it .
Monday, November 12, 2007
Little Sugar :const function pointers and references
The syntax in c++ for constant function pointers is like this
Handle& (*const getHandle) = handle;
where handle is a function returning a reference to the handle.
The syntax for reference function pointers is like this:
Handle& (&getHandle) = handle;
Handle& (*const getHandle) = handle;
where handle is a function returning a reference to the handle.
The syntax for reference function pointers is like this:
Handle& (&getHandle) = handle;
Thursday, November 01, 2007
Little Sugar : What does virtual in C++ mean
In c++ if a function is declared virtual for any class, then that class has an associated
virtual table . With each of those virtual functions a special type of virtual table pointer is associated , which has an entry in the virtual table associated with the corresponding class.
These virtual pointers are used at runtime to figure out which virtual function to invoke at runtime.
Making virtual functions inline does not make sense ?? why ...
Inline functions are meant to be made inline , so that means they don't have an explicit address but then if it does not have an address and its virtual then how will it have an entry in the virtual table ??
It will have an entry , cause our friend compiler will generate a function body for us and embed the address somewhere for it .
virtual table . With each of those virtual functions a special type of virtual table pointer is associated , which has an entry in the virtual table associated with the corresponding class.
These virtual pointers are used at runtime to figure out which virtual function to invoke at runtime.
Making virtual functions inline does not make sense ?? why ...
Inline functions are meant to be made inline , so that means they don't have an explicit address but then if it does not have an address and its virtual then how will it have an entry in the virtual table ??
It will have an entry , cause our friend compiler will generate a function body for us and embed the address somewhere for it .
Tuesday, October 30, 2007
Private lock Object Idiom
The private lock object idiom is generally used in making a class Thread Safe.
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Sunday, October 21, 2007
Lazy Initailization Idioms
Double check idiom is supposedly the best lazy initialization technique
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
set_new_handler in
The correct way of overriding the new operator can be something. Here i try to highlight how one can go about doing so .
typedef void (*new_handler)();
In the new header file , a typedef new handler is defined . This typedef basically refers to
the function that the new operator will call if it is not able to allocate memory properly.
Generally the new operator specification looks for the new_handler to allocate more or release
memory so that the new operator can call it properly.
new_handler set_new_handler(new_handler handler);
is a function also found in that installs the new handler . A typical implementation
of this should return the old_handler that was replaced.
The new operator throws std::bad_alloc exception when it is not able to allocate memory.
Class specific handlers can be installed for class specific new operator .
The code for managing the operator and the handler can go in one templatised base class.
Derived classes can then inherit from this class . The base class is very specialized class
as it only provides only one type of functionality.Such type of classes are called mixins.
template
class NewHandler{
public:
static new_handler set_new_handler(new_handler handler);
static void* operator new(size_t size);
private:
static new_handler currentHandler;
};
template
new_handler NewHandler::currentHandler;
template
new_handler NewHandler::set_new_handler(new_handler handler){
new_handler oldHandler = currentHandler;
currentHandler = handler;
return oldHandler;
}
template
void* NewHandler::operator new(size_t size){
new_handler globalHandler = std::set_new_handler(NewHandler::currentHandler):
void * memory;
try{
// try to allocate memory using global new operator
memory = ::operator new(size);
}catch(std::bad_alloc &){
std::set_new_handler(globalHandler);
// propogate all the exceptions
throw;
}
// reinstall the saved gloabal handler
std::set_new_handler(globalHandler);
return memory;
}
Now any class X can use NewHandler like this :
class X : public NewHandler {
};
typedef void (*new_handler)();
In the new header file , a typedef new handler is defined . This typedef basically refers to
the function that the new operator will call if it is not able to allocate memory properly.
Generally the new operator specification looks for the new_handler to allocate more or release
memory so that the new operator can call it properly.
new_handler set_new_handler(new_handler handler);
is a function also found in
of this should return the old_handler that was replaced.
The new operator throws std::bad_alloc exception when it is not able to allocate memory.
Class specific handlers can be installed for class specific new operator .
The code for managing the operator and the handler can go in one templatised base class.
Derived classes can then inherit from this class . The base class is very specialized class
as it only provides only one type of functionality.Such type of classes are called mixins.
template
class NewHandler{
public:
static new_handler set_new_handler(new_handler handler);
static void* operator new(size_t size);
private:
static new_handler currentHandler;
};
template
new_handler NewHandler
template
new_handler NewHandler
new_handler oldHandler = currentHandler;
currentHandler = handler;
return oldHandler;
}
template
void* NewHandler
new_handler globalHandler = std::set_new_handler(NewHandler
void * memory;
try{
// try to allocate memory using global new operator
memory = ::operator new(size);
}catch(std::bad_alloc &){
std::set_new_handler(globalHandler);
// propogate all the exceptions
throw;
}
// reinstall the saved gloabal handler
std::set_new_handler(globalHandler);
return memory;
}
Now any class X can use NewHandler like this :
class X : public NewHandler
};
Thursday, October 18, 2007
Finalizer guardian Idiom
Finalizer Guardian idiom is nothing but an anonymous class assigned to a private final instance variable within a class that wants to override the finalize method .
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
Little Sugar (Handling Exceptions in Finalize )
Lets consider a scenario where you have a class A and a subclass of that class called B.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.
So your implementation should look like this :
protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}
}
That way , any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.
Now say you override the finalize method in class B then you need to explicitly invoke the
finalize method of the parent.
So your implementation should look like this :
protected void finalize() throws Throwable {
try{
}finally{
super.finalize();
}
}
That way , any exceptions thrown in the finalize method would not cause the finalize method to terminate and leave the object in a corrupt state.
Little Sugar (Java Finalization )
Uncaught exceptions thrown in the finalize method of an object are not caught . Infact they cause the finalization process to terminate and leave the object in a corrupt state . Now that's weird ...
So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .
So the best of the rule of thumb would be to avoid finalizers. Instead explicit termination methods should be called that can be invoked in the finally block .
Monday, October 08, 2007
Contributing to the Eclipse Cool Bar
To add stuff to the eclipse cool bar , u need to
1) implement the extension point org.eclipse.ui.editor .
2) Specify a contributorClass for the above mentioned extension point.
This contributor class will provide actions that would be contributed to the
coolbar.
Lets call this calls MyContributorClass.
3) Have this class extend BaseEditorContributor , It should override contributeToParentCoolbar .
4) In the given method create a ContributionItem that would be contributed to the coolbar.
Lets call this myContributionItem.
5) Use the parentCoolBarManager to add create a ToolBarManager.
IToolBarManager toolbar = new ToolBarManager(parentCoolBarManager.getStyle())
6) Add myContributionItem to toolbar.
toolbar.add(myContributionItem);
7) Create a ToolBarContributionItem and add it to the parent cool bar.
ToolBarContributionItem toolBarItem = new ToolBarContributionItem(toolbar,myContributionItem.getId())
parentCoolBarManager.add(toolBarItem);
and finally
coolBarItems.add(toolBarItem);
parentCoolBarManager and coolBarItem are protected members and are available from the base class .
1) implement the extension point org.eclipse.ui.editor .
2) Specify a contributorClass for the above mentioned extension point.
This contributor class will provide actions that would be contributed to the
coolbar.
Lets call this calls MyContributorClass.
3) Have this class extend BaseEditorContributor , It should override contributeToParentCoolbar .
4) In the given method create a ContributionItem that would be contributed to the coolbar.
Lets call this myContributionItem.
5) Use the parentCoolBarManager to add create a ToolBarManager.
IToolBarManager toolbar = new ToolBarManager(parentCoolBarManager.getStyle())
6) Add myContributionItem to toolbar.
toolbar.add(myContributionItem);
7) Create a ToolBarContributionItem and add it to the parent cool bar.
ToolBarContributionItem toolBarItem = new ToolBarContributionItem(toolbar,myContributionItem.getId())
parentCoolBarManager.add(toolBarItem);
and finally
coolBarItems.add(toolBarItem);
parentCoolBarManager and coolBarItem are protected members and are available from the base class .
Sunday, September 23, 2007
what is e raised to i * Pi
The other day i was seeing some presentation . During the presentation i came across a mathematical puzzle . The puzzle asked about what is the value of
value = e ^ (i * Pi) ??
now this would have been really really easy if i was in 12 th grade . But Since its a been long time since 12 th grade and few yrs since by B.S degree . It took some thinking ..
So the solution is :
well if you remember complex numbers then then you can say
e ^ (i * x ) = cos (x) + i sin(x)
so e ^ ( i * Pi ) = cos (Pi) + i sin (Pi)
since cos (pi) = -1
sin (pi ) = 0
e ^ (i * pi) = -1
Duh .. so much for my memory :( ..
value = e ^ (i * Pi) ??
now this would have been really really easy if i was in 12 th grade . But Since its a been long time since 12 th grade and few yrs since by B.S degree . It took some thinking ..
So the solution is :
well if you remember complex numbers then then you can say
e ^ (i * x ) = cos (x) + i sin(x)
so e ^ ( i * Pi ) = cos (Pi) + i sin (Pi)
since cos (pi) = -1
sin (pi ) = 0
e ^ (i * pi) = -1
Duh .. so much for my memory :( ..
Tuesday, August 21, 2007
Showing an Eclipse View Programatically
In eclipse non savable containers are called views . It pretty easy to create a view , all you need to do is to implement an extension - point (org.eclipse.ui.views) and add features to a class . If you want to implement your own view , you can google it you 'll find a number of articles about it .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
Monday, August 13, 2007
Little Sugar (Heaps)
- Heap is a data structure whcih satisfies the MAX-HEAP or MIN-HEAP property
- All basic operations on a heap run in a time proportional to the height of the heap (lg n ) where n being the total number of nodes in a heap
- A heap is generally a complete tree
- IN an array represenation of an N-element heap the leaves nodes are indexed by n/2+1 , n/2 + 2 ... n
- In an N element heap , the number of nodes of height H are n/pow(2,h+1)
Sunday, July 29, 2007
Programatically Creating a java package in Eclipse
In my last post we saw how we can create a java project programatically in eclipse. In this post we will see how to create a package in this java project.
The steps needed to do this are :
1. Create a source folder under the java project created earlier .
IFolder src = javaProject.getFolder("src");
folder.create(force , local , nullProgressMonitor);
IPackageFragmentRoot packageRoot = javaProject.getPackageFragmentRoot(folder);
IClasspathEntry[] classPath = javaProject.getRawClasspath();
List entries = new ArrayList(Arrays.asList(classpath));
entries.add(JavaCore.newSourceEntry(root.getPath()));
javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]) , null ProgressMonitor);
The code becomes pretty clear if you had followed my previous post.
2. Create the actual package .
src.createPackageFragment(packageName, force , nullProgressMonitor);
Yeah thats done , in the next post well see how to create a class programatically
The steps needed to do this are :
1. Create a source folder under the java project created earlier .
IFolder src = javaProject.getFolder("src");
folder.create(force , local , nullProgressMonitor);
IPackageFragmentRoot packageRoot = javaProject.getPackageFragmentRoot(folder);
IClasspathEntry[] classPath = javaProject.getRawClasspath();
List
entries.add(JavaCore.newSourceEntry(root.getPath()));
javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[0]) , null ProgressMonitor);
The code becomes pretty clear if you had followed my previous post.
2. Create the actual package .
src.createPackageFragment(packageName, force , nullProgressMonitor);
Yeah thats done , in the next post well see how to create a class programatically
Wednesday, July 25, 2007
Creating a new project in Eclipse Programatically
If you have done Eclipse plugin development you would know that any non trivial task is not obvious , unless you have gone and dug into the eclipse source code. Going through the eclipse source code is not easy cause its a massive rhino . Finding the right code requires tons of patience for a newbie .
Here i am presenting a small snippet that creates a java project programatically
This code can also be found in the eclipse source tree , i am presenting here just for handy reference .
IProject project = root.getProject("dummyProject");
IProgressMonitor nullProgressMonitor = null;
project.create(nullProgressMonitor);
ResourcesPlugin is the plugin that gives us access to all the resources in eclipse including the workspace . When eclipse creates a project it shows a progress bar , we are passing null for that.
2. Open the above created java Project
IJavaProject javaProject = JavaCore.create(project)
'create' is a misonomer . This creates a decorated Java version of an eclipse project.
3. Add the java nature to the project
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[]{JavaCore.NATURE_ID});
project.setDescription(description,null);
Eclipse has the concept of natures , its kinda tagging a project with java label.
4. Set the class path for the java project
IClasspathEntry[] rawClassPath = javaProject.getRawClassPath();
List classPath = new ArrayList(
Arrays.asList(rawClassPath));
classPath.add(JavaRuntime.getDefaultJREContainerEntry());
javaProject.setRawClasspath(classPath, nullProgressMonitor);
Since java and class paths are closely tied . We need to add the different class libraries to the project class path . In Eclipse every plugin has its own class loader . By adding add class libraries to the project class path we make class libraries accessible to the class loader .
5. Create the bin folder and mark it as output folder
boolean force = true;
boolean local = true;
IFolder binFolder = project.getFolder("bin");
binFolder.create(force,local,nullProgressMonitor);
IPath fullPath = binFolder.getFullPath();
javaProject.setOutputLocation(fullPath,nullProgressMonitor);
This code will create a project in the Runtime Eclipse Workbench that appears when you launch a new eclipse instance from your eclipse instance.
Here i am presenting a small snippet that creates a java project programatically
This code can also be found in the eclipse source tree , i am presenting here just for handy reference .
- Create an IProject with a name
IProject project = root.getProject("dummyProject");
IProgressMonitor nullProgressMonitor = null;
project.create(nullProgressMonitor);
ResourcesPlugin is the plugin that gives us access to all the resources in eclipse including the workspace . When eclipse creates a project it shows a progress bar , we are passing null for that.
2. Open the above created java Project
IJavaProject javaProject = JavaCore.create(project)
'create' is a misonomer . This creates a decorated Java version of an eclipse project.
3. Add the java nature to the project
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[]{JavaCore.NATURE_ID});
project.setDescription(description,null);
Eclipse has the concept of natures , its kinda tagging a project with java label.
4. Set the class path for the java project
IClasspathEntry[] rawClassPath = javaProject.getRawClassPath();
List
Arrays.asList(rawClassPath));
classPath.add(JavaRuntime.getDefaultJREContainerEntry());
javaProject.setRawClasspath(classPath, nullProgressMonitor);
Since java and class paths are closely tied . We need to add the different class libraries to the project class path . In Eclipse every plugin has its own class loader . By adding add class libraries to the project class path we make class libraries accessible to the class loader .
5. Create the bin folder and mark it as output folder
boolean force = true;
boolean local = true;
IFolder binFolder = project.getFolder("bin");
binFolder.create(force,local,nullProgressMonitor);
IPath fullPath = binFolder.getFullPath();
javaProject.setOutputLocation(fullPath,nullProgressMonitor);
This code will create a project in the Runtime Eclipse Workbench that appears when you launch a new eclipse instance from your eclipse instance.
Monday, July 09, 2007
Extension Object Pattern : an Eclipse Example
In short an Extension Object pattern is a nice way of extending an interface of class by 3 rd party classes without polluting the base interface of the class.
I am going to take eclipse as an example to explaing this pattern . For those of you , who have done eclipse plugin development . You would have come across ed the interface IAdaptable. This interface is at heart of the Extension Object Pattern implemented by Eclipse .
So what is the Extension Object Pattern ???
Say you have an interface IFile . This interface represents an abstraction of a file . Apart from being a basic file this IFile interface could offer many services . So the question is how do you offer those services .
One simple way would be to extend the IFile interface . Add the extra functionality to the new new interface and have come class implement that new interface . e.g you could have a IUIFile interface . Once you have that interface , you could implement that interface .
But the problem with that approach is that , you end up polluting the base beautiful interface and have a bloated class ( implementor) . Well the above mentioned approach would work if you are fine with extending the object every time you want to implement a new service , but as the number of services increase the class becomes super duper bloated monster .
So how does the extension object pattern help us in solving this evolution problem ??
I ll continue with the IFile interface from eclipse to explain how can we go about using the interface to implement the extension pattern .
We know that IFile might have to support a number of services at some point of time in future . So rather than have IFile implement all the new interfaces , we just implement the IAdaptable interface . This interface is a place holder , saying that the class implementing IFile is now ready to be extended by 3 rd party classes without polluting the base interface IFile.
This Adaptable interface can contain a simple method that does the job of resolving the service to the correct service provider .
public interface IFile extends IAdaptable , .... {
.....
public Object getAdapter(Class adapter);
...
}
}
Now lets say that we want to check if IFile supports ServiceA , or ServiceB.
We can do that now passing ServiceA.class to the getAdpater method .
This method would return a valid object if the service is supported or on the other hand it would return a null object .
Instead of having a number of if conditions in the getAdapter method what eclipse does is that for each interface supported by the type , eclipse creates an adapter factory . The different factories are then registered with an AdapterManager . The getAdapter method then returns
the appropriate AdapterFactory via the AdpaterManager. e.g
public Object getAdapter(Class adapter);
return Platform.getAdapterManager.getAdpater(this,adapter);
}
Something like this can later be used to return the right adapter for intended service.
public interface IAdapterfactory {
public Object getAdapter(Object adaptableObject, Class adapterType);
....
}
The adapter manager uses different adapter factories to resolve the reference for the asked interface , for the given type .
So in this manner multiple behaviors can be added to a single type . This is a nice way to support class extensions.
I am going to take eclipse as an example to explaing this pattern . For those of you , who have done eclipse plugin development . You would have come across ed the interface IAdaptable. This interface is at heart of the Extension Object Pattern implemented by Eclipse .
So what is the Extension Object Pattern ???
Say you have an interface IFile . This interface represents an abstraction of a file . Apart from being a basic file this IFile interface could offer many services . So the question is how do you offer those services .
One simple way would be to extend the IFile interface . Add the extra functionality to the new new interface and have come class implement that new interface . e.g you could have a IUIFile interface . Once you have that interface , you could implement that interface .
But the problem with that approach is that , you end up polluting the base beautiful interface and have a bloated class ( implementor) . Well the above mentioned approach would work if you are fine with extending the object every time you want to implement a new service , but as the number of services increase the class becomes super duper bloated monster .
So how does the extension object pattern help us in solving this evolution problem ??
I ll continue with the IFile interface from eclipse to explain how can we go about using the interface to implement the extension pattern .
We know that IFile might have to support a number of services at some point of time in future . So rather than have IFile implement all the new interfaces , we just implement the IAdaptable interface . This interface is a place holder , saying that the class implementing IFile is now ready to be extended by 3 rd party classes without polluting the base interface IFile.
This Adaptable interface can contain a simple method that does the job of resolving the service to the correct service provider .
public interface IFile extends IAdaptable , .... {
.....
public Object getAdapter(Class adapter);
...
}
}
Now lets say that we want to check if IFile supports ServiceA , or ServiceB.
We can do that now passing ServiceA.class to the getAdpater method .
This method would return a valid object if the service is supported or on the other hand it would return a null object .
Instead of having a number of if conditions in the getAdapter method what eclipse does is that for each interface supported by the type , eclipse creates an adapter factory . The different factories are then registered with an AdapterManager . The getAdapter method then returns
the appropriate AdapterFactory via the AdpaterManager. e.g
public Object getAdapter(Class adapter);
return Platform.getAdapterManager.getAdpater(this,adapter);
}
Something like this can later be used to return the right adapter for intended service.
public interface IAdapterfactory {
public Object getAdapter(Object adaptableObject, Class adapterType);
....
}
The adapter manager uses different adapter factories to resolve the reference for the asked interface , for the given type .
So in this manner multiple behaviors can be added to a single type . This is a nice way to support class extensions.
Friday, June 29, 2007
Logging using the Eclipse Logging Framework
if you are using eclipse in your day to day work and you want to log activities using the in built eclipse logging frame work .
Here is a small example to do the same ,
if u have a plugin class then say MyPlugin that extends AbstrarctUIPlugin then u can a have method in that class that does the logging for you .
public static void log(String message , int status ){
getDefault().getLog().log(new Status(status, getPluginID( ), message,null) );
}
the values , status can take are like :
Here is a small example to do the same ,
if u have a plugin class then say MyPlugin that extends AbstrarctUIPlugin then u can a have method in that class that does the logging for you .
public static void log(String message , int status ){
getDefault().getLog().log(new Status(status, getPluginID( ), message,null) );
}
the values , status can take are like :
- IStatus.ERROR
- IStatus.WARNING
Thursday, June 28, 2007
Immutable Objects In Java
What is an Immutable Object ?
An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..
So how do you create an immutable object :
public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}
public Complex add(Complex left , Complex right) {
// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}
The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat
An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..
So how do you create an immutable object :
- Remove or make setters less accessible.
- Preveting methods from getting overriden.
- Make all fields final.
- Make defensive copies of mutable objects.
- Do not provide a clone method
- Do not provide a copy constructor
- return a fuctional object
public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}
public Complex add(Complex left , Complex right) {
// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}
The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat
Little Sugar ( Mixins in Java)
Mixin ?? what is a mixin ...
Thats what i wondered when i cam accross the phrase . A Mixin is a way of adding features to the core functionlaity of a class . It is different from extending the class , cause it generally pertains to adding features not related to the core or default behaviour of a class .
A little example will make things clear . Say you have a small class Person that represents a person wholly . Not if you want to compare 2 instances of Person , you could implement the Comparable interface . By implementing the Comparable interface you add a functionlity that is not directly related to a Person object but is a help ful feature .
So a simple way to implement a Mixin is to implement an interface .. so much for buzz words...
Thats what i wondered when i cam accross the phrase . A Mixin is a way of adding features to the core functionlaity of a class . It is different from extending the class , cause it generally pertains to adding features not related to the core or default behaviour of a class .
A little example will make things clear . Say you have a small class Person that represents a person wholly . Not if you want to compare 2 instances of Person , you could implement the Comparable interface . By implementing the Comparable interface you add a functionlity that is not directly related to a Person object but is a help ful feature .
So a simple way to implement a Mixin is to implement an interface .. so much for buzz words...
Wednesday, June 27, 2007
Little Sugar (Security Manager , Java)
Today i ll gloss over a few small things worth remembering about security
in java . So lets get started :
In Java , we hava a Java API . The java API provides us with a lot methods to accomplish different type of tasks . Now if for some reason we want to enforce security on these tasks so that only selected operation can be performed and that to by selected users . In that case we need to create a security policy file.
In the security policy file , we specifiy how permissions are applied to different code sources . We specify differnt permissions in terms of Permission objects that are applied to CodeSource objects .
At runtime a policy object is created corresponding to the policy file .
For the policies to take effect a SecurityManager needs to be installed . Once the security manager is installed it uses the AccessController ,which inturn checks the different permissions based on different permission objects .
When the class loader loads a type in the JVM . It places the type in a protection domain , which encapsulates the permissions . At runtime , when methods on the type instance are invoked the security manger is checked to see if the method can be invoked .
in java . So lets get started :
In Java , we hava a Java API . The java API provides us with a lot methods to accomplish different type of tasks . Now if for some reason we want to enforce security on these tasks so that only selected operation can be performed and that to by selected users . In that case we need to create a security policy file.
In the security policy file , we specifiy how permissions are applied to different code sources . We specify differnt permissions in terms of Permission objects that are applied to CodeSource objects .
At runtime a policy object is created corresponding to the policy file .
For the policies to take effect a SecurityManager needs to be installed . Once the security manager is installed it uses the AccessController ,which inturn checks the different permissions based on different permission objects .
When the class loader loads a type in the JVM . It places the type in a protection domain , which encapsulates the permissions . At runtime , when methods on the type instance are invoked the security manger is checked to see if the method can be invoked .
Tuesday, June 19, 2007
Litttle Sugar (Java Collections)
The other day I was reading about java collections . I came accross this trivial point about Sets in java that is worth remembering . In java there are 3 different implementations of the Set interface , namely :
The fastest among the 3 implementations , but does not maintain ordering.
TreeSet:
The slowest among the 3 implementations , uses red black tree to internally store items and orders the items by value.
LinkedHashSet:
Its performance comes in between the 1st two but maintain the ordering in which items are
inserted . Uses hashtable with linked list to store items.
- HashSet
- TreeSet
- LinkedHashSet
The fastest among the 3 implementations , but does not maintain ordering.
TreeSet:
The slowest among the 3 implementations , uses red black tree to internally store items and orders the items by value.
LinkedHashSet:
Its performance comes in between the 1st two but maintain the ordering in which items are
inserted . Uses hashtable with linked list to store items.
Saturday, June 16, 2007
String formatting using C++
Say you need to create a special string that does shows floating point numbers.
Lets put another constraint , say you need to show upto K decimal places.
e.g u need an output like this
123.45 <--- 2 decimal places
say double d = 123.456
then u can create a string which shows upto 2 decimal places like this.
ostringstream o;
o.setf(ios::fixed);
o.precision(2);
o << d;
cout << o.str();
Lets put another constraint , say you need to show upto K decimal places.
e.g u need an output like this
123.45 <--- 2 decimal places
say double d = 123.456
then u can create a string which shows upto 2 decimal places like this.
ostringstream o;
o.setf(ios::fixed);
o.precision(2);
o << d;
cout << o.str();
Thursday, June 14, 2007
Const in C++
The const keyword in C++ is a very useful keyword . Apart from declaring constants it is useful in declaring few important things . Lets talk about two important const advantages
Pointer to a const basically says that the object being pointed to by the pointer should remain const and the pointer should not try to change the contents of that object . But this does not mean that that value of the object will not get changed m it just says the given pointer is not going to change the value of the object.
e.g String(const char * = ""){
.....
}
a simple rule of thumb is that if the function is not going to modify the object it should accept a const object
const reference:
void do_something(const Thing &);
This is analogous to pointers , the only advantage is that by declaring a reference const you prevent unnamed temporaries . Basically its the same concept which says if your not gonna change it then pass it as a const .
cannot use do_something(get_something()) // un named temporary not allowed
Things get_something();
Thing t(get_something());
void do_something(Thing&);
Const member functions:
const member function are member function in which the argument list is followed by the const keyword. In a const instance of an object only const member functions can be invoked.
From non const member functions unnamed temporaries can be invoked.
- pointer to a const
- const reference
Pointer to a const basically says that the object being pointed to by the pointer should remain const and the pointer should not try to change the contents of that object . But this does not mean that that value of the object will not get changed m it just says the given pointer is not going to change the value of the object.
e.g String(const char * = ""){
.....
}
a simple rule of thumb is that if the function is not going to modify the object it should accept a const object
const reference:
void do_something(const Thing &);
This is analogous to pointers , the only advantage is that by declaring a reference const you prevent unnamed temporaries . Basically its the same concept which says if your not gonna change it then pass it as a const .
cannot use do_something(get_something()) // un named temporary not allowed
Things get_something();
Thing t(get_something());
void do_something(Thing&);
Const member functions:
const member function are member function in which the argument list is followed by the const keyword. In a const instance of an object only const member functions can be invoked.
From non const member functions unnamed temporaries can be invoked.
Implementing operator as member or nonmember functions
The answer to implementing an operator as a member or a non member lies in the following simple points
- if any operand of an operator is susceptible to implicit type conversion , implement it as a member function
- if the result of an operation does not effect the two operands or an operand implement it as a non-member function.
Sunday, June 10, 2007
Tutorial: Writing a Tetris Clone using XNA
One of the Hello World programs in game programming is Tetris . I am making the assumption that you the reader have played tetris and know the rules of this simple game knows C# and under stands Object Oriented Concepts . Tetris is a very simple game , simple graphics simple collision detection and animation if you want to call the rotation of blocks as animation . So lets not any more time and lets get started with the code and step by step explanation of how to create a Tetris Using XNA .
Step 1:
Step 1 is figuring out all the the blocks that are used in the Tetris game . If you think about the game it consists of the following blocks
Step 2:
In step 2 ,we will try to see as to how we can map these blocks to their corresponding images and as to how we can rotate the blocks and their corresponding images .Since we saw that each block is made up of 4 squares , we can label the squares as 1 , 2 ,3 ,4 correspondingly . Out of these 4 squares , 1 square we will mark as the pivot around which the block can rotate .
See the image below for a clear understanding of this:

If you look at the blocks they have different names , like L , J , S which basically identify their shape . Each square in a block is numbered and one of the square is circled . The circled square is the pivot for the given block . If you look carefully at block S , that block on rotation looks like the block mentioned directly below it .
Step 3
Now that we understand the basics of the representation and requirements we can get down to some coding , i ll try to avoid the XNA related code till the end . I will try to explain how this simple representation of blocks can be represented using code.
Since we have a number of blocks and each block can rotate and move left , right , down. Also each block has a direction and a current position . So basically every object in this simple game is block and since all these blocks have few things in common , we can take that common functionality and create a simple abstract class called Block . We can then have each one of the blocks extends from this base class called Block . Since the next block that falls from the top should be randomized , we can create BlockFactory that generates these blocks for us . This factory can create an instance of each type of block and cache it . So that we can reuse the block instances . Now that i have explained how Block , BlockFactory fit together lets look at the code for Block :
Step 4:
Lets start with the Square class . A block uses 4 squares . The code for the Square class is pretty simple and looks like this :
The square class is pretty simple . Next there is an interface called Direction .
which looks like this
I have 4 classes implementing this interface . The classes being East , West , South and North . Lets look at the code for the East class .
Directions is not a true factory , but just holds static references to different
types of directions . The movement class is also similar in nature to the direction
class . The movement class is an abstract class and there are classes like Left ,
Right , Down that inherit from Movement . Again Movements is similar in nature to
Directions .
To be continued ....
Step 1:
Step 1 is figuring out all the the blocks that are used in the Tetris game . If you think about the game it consists of the following blocks
- a line
- a square shaped block
- a L shaped block
- a J shaped block
- a S shaped block
- a T shaped block
- a Z shaped block
Step 2:
In step 2 ,we will try to see as to how we can map these blocks to their corresponding images and as to how we can rotate the blocks and their corresponding images .Since we saw that each block is made up of 4 squares , we can label the squares as 1 , 2 ,3 ,4 correspondingly . Out of these 4 squares , 1 square we will mark as the pivot around which the block can rotate .
See the image below for a clear understanding of this:
If you look at the blocks they have different names , like L , J , S which basically identify their shape . Each square in a block is numbered and one of the square is circled . The circled square is the pivot for the given block . If you look carefully at block S , that block on rotation looks like the block mentioned directly below it .
Step 3
Now that we understand the basics of the representation and requirements we can get down to some coding , i ll try to avoid the XNA related code till the end . I will try to explain how this simple representation of blocks can be represented using code.
Since we have a number of blocks and each block can rotate and move left , right , down. Also each block has a direction and a current position . So basically every object in this simple game is block and since all these blocks have few things in common , we can take that common functionality and create a simple abstract class called Block . We can then have each one of the blocks extends from this base class called Block . Since the next block that falls from the top should be randomized , we can create BlockFactory that generates these blocks for us . This factory can create an instance of each type of block and cache it . So that we can reuse the block instances . Now that i have explained how Block , BlockFactory fit together lets look at the code for Block :
Step 3 was big , indeed it was a mini Leap . But it was needed . In Step i will be talking about the classes that are used by above code .
public abstract class Block
{
// the background image used by the game
protected Texture2D backgroundTexture;
// the current position of the block
protected Vector2 position;
// the 4 squares used by each block
protected Square square1;
protected Square square2;
protected Square square3;
protected Square square4;
// before we rotate the block and calculate the new position for the squares
// we'll use the following variables to store the old positions
protected Vector2 _oldSquare1Position;
protected Vector2 _oldSquare2Position;
protected Vector2 _oldSquare3Position;
protected Vector2 _oldSquare4Position;
// the game field where the actual game is being played
// i ll talk about this later
protected GameField gameField;
// the direction of the block
private Direction direction;
// the movement of the block
private Movements.Movements movements;
// this constructor for the block , this is where the block gets created
// it is given an initial position and a direction , based on this starting
// position the 4 squares get initialized
public Block(GameField gameField, Texture2D backgroundTexture, Vector2 origin , Direction direction)
{
this.backgroundTexture = backgroundTexture;
this.position = origin;
this.direction = direction;
this.gameField = gameField;
square1 = new Square(this.backgroundTexture, position);
square2 = new Square(this.backgroundTexture, position);
square3 = new Square(this.backgroundTexture, position);
square4 = new Square(this.backgroundTexture, position);
movements = new Movements.Movements(this,gameField);
// ignore this for while i ll talk about this
setupBlock();
}
// the code that will respond when a block of a given shape is rotatated to
// the North ,
public abstract void RotateTo(North north);
// similarly it also works for East , West , South
// the core rotating logic is here , first of all we save the positions of
// the 4 squares , then based on the current direction we try to rotate
// the current block , this gives us a new set of positions for the 4 squares
// and a new direction for the block , then we make a final check if we can
// possible rotate if not we revert back to the saved positions .
public void Rotate()
{
savePositions();
this.direction = direction.Rotate(this);
if (!canRotate())
revertPositions();
}
// Similar to rotation we first of all save all the positions of the 4
// squares , based on the current movement we check if we can move to the
// left the given number of units , if the block can move we move else
// we revert back to the saved positions .
public virtual void MoveLeft(int units)
{
savePositions();
if (movements.LEFT.CanMove(units))
{
square1.MoveLeft(units);
square2.MoveLeft(units);
square3.MoveLeft(units);
square4.MoveLeft(units);
}
else
revertPositions();
}
// similar logic applies for Right and Down
// the draw method for the block draws the block , by drawing all the 4
// squares , ignore the SpriteBatch i ll talk about that later
public virtual void Draw(SpriteBatch batch)
{
// draw the given square at the given position
batch.Draw(square1.Texture, square1.Position, Color.White);
batch.Draw(square2.Texture, square2.Position, Color.White);
batch.Draw(square3.Texture, square3.Position, Color.White);
batch.Draw(square4.Texture, square4.Position, Color.White);
}
protected void savePositions()
{
_oldSquare1Position = square1.Position;
_oldSquare2Position = square2.Position;
_oldSquare3Position = square3.Position;
_oldSquare4Position = square4.Position;
}
protected bool canRotate()
{
return canRotate(square1) &&
canRotate(square2) &&
canRotate(square3) &&
canRotate(square4);
}
protected void revertPositions()
{
square1.Position = _oldSquare1Position;
square2.Position = _oldSquare2Position;
square3.Position = _oldSquare3Position;
square4.Position = _oldSquare4Position;
}
// ask the gameField if the given square can rotate
private bool canRotate(Square square)
{
return gameField.CanRotate(square);
}
}
Step 4:
Lets start with the Square class . A block uses 4 squares . The code for the Square class is pretty simple and looks like this :
public class Square
{
.....
// move the position of the square to the left by given units
public void MoveLeft(int units)
{
position.X = position.X - units;
}
...
// move the position down by given unite
public void MoveDown(int units)
{
position.Y = position.Y + units;
}
...
The square class is pretty simple . Next there is an interface called Direction .
which looks like this
public interface Direction
{
Direction Rotate(Block block);
}
I have 4 classes implementing this interface . The classes being East , West , South and North . Lets look at the code for the East class .
// East implements the Direction class
public class East : Direction
{
// the rotate method tells the block to rotate itself in the east
// direction . Remember the abstract method in Block that rotate in
// different direction , this is where they are used . Why i did this
// well depending upon the shape of the block and using this type of
// reverse delegation helps in keeping the code managable
public Direction Rotate(Block block)
{
block.RotateTo(this);
// since the next direction in clockwise manner is South return that .
return Directions.SOUTH;
}
}
Directions is not a true factory , but just holds static references to different
types of directions . The movement class is also similar in nature to the direction
class . The movement class is an abstract class and there are classes like Left ,
Right , Down that inherit from Movement . Again Movements is similar in nature to
Directions .
To be continued ....
Saturday, June 09, 2007
Casting in C++
Type casting in c++ can be done in two ways , using the traditional explicit ( ) cast operator or the new cast operators in c++ . The new operators in C++ are
- static_cast <>
- const_cast <>
- dynamic_cast <>
- reinterpret_cast
Implicit Type Conversion in C++
An implicit type conversion process in C++ , happens in two cases .
Case 1:
If there is a type T and another type F . An the type T has a constructor that takes in a Type F , in that case in expressions which involve the usage of Type T and an object of type F is passed . The type F is automatically converted to an object of type T . Lets see this is as example
Case 2:
Using the conversion operator it is possible to implicitly convert one object to another type. If the String class had the following operator defined
operator const char* ( ) const { return string; }
and somewhere in some function if the following code was used
String s("hello world");
cout << style="font-weight: bold;">So, with that also an implicit type conversion happens . Implicit type conversion can get confusing , so should be used with care . Explicit case or function calls are much better as they indicate the intended operation more clearly .
Case 1:
If there is a type T and another type F . An the type T has a constructor that takes in a Type F , in that case in expressions which involve the usage of Type T and an object of type F is passed . The type F is automatically converted to an object of type T . Lets see this is as example
Now here if print is invoked with "Hello , world" i.e print("Hello , world") is called then since we have a constructor for String that takes in an array of characters . So array of characters are automatically converted into a String object which is then passed to then print function .
class String {
char * string;
public:
String(const char * str = "");
};
void print(String & str);
Case 2:
Using the conversion operator it is possible to implicitly convert one object to another type. If the String class had the following operator defined
operator const char* ( ) const { return string; }
and somewhere in some function if the following code was used
String s("hello world");
cout << style="font-weight: bold;">So, with that also an implicit type conversion happens . Implicit type conversion can get confusing , so should be used with care . Explicit case or function calls are much better as they indicate the intended operation more clearly .
Friday, June 08, 2007
Little Sugar (Compound Assignment operator And Implicit Type Conversion)
x += i
'+=' This is what is called the compound assignment operator in Java . An interesting thing about this operator is that , this operator automatically casts the type of expression on the right , which in this case is i to the type of the expression on the left which being x .
'+=' This is what is called the compound assignment operator in Java . An interesting thing about this operator is that , this operator automatically casts the type of expression on the right , which in this case is i to the type of the expression on the left which being x .
Wednesday, June 06, 2007
Little Sugar (Algorithm)
I came across an interesting property about numbers . If u have a number a and you consider multiples of the number , then for some number a the sum of the digits of the multiple is divisible by the number a
More than this , if you just check till the first 4 digit number , in that base then you get to know that for all multiple of the number the above mentioned property holds.
given a sequence [1 .. N] and a base ( b) , and number a . generating the multiples is as simple as doing 1 + a , 2 + a ....
finding the sum of the digits is a given base (b) is same as finding the sum of digits for base 10 that except for base 10 , base (b) is used
in code that looks like
while(n){
sum += n % base;
n = n/base;
}
the maximum 3 digit number is a given base is
base * base * base
More than this , if you just check till the first 4 digit number , in that base then you get to know that for all multiple of the number the above mentioned property holds.
given a sequence [1 .. N] and a base ( b) , and number a . generating the multiples is as simple as doing 1 + a , 2 + a ....
finding the sum of the digits is a given base (b) is same as finding the sum of digits for base 10 that except for base 10 , base (b) is used
in code that looks like
while(n){
sum += n % base;
n = n/base;
}
the maximum 3 digit number is a given base is
base * base * base
Tuesday, June 05, 2007
Little Sugar 1 ( Java)
So often i come across something cool , but important so i thought using blogging about them would be nice idea , so here is my Little Sugar 1
when converting from 1 type to another , sign extension is performed if the source data is signed
eg
byte b = 0xff;
char c = (char) b
if the type is char , no sign conversion is peformed .
if converting from byte to char if no sign conversion is required than bitwise AND with 0xff is nice idea.
char c = (char) b & 0xff
when converting from 1 type to another , sign extension is performed if the source data is signed
eg
byte b = 0xff;
char c = (char) b
if the type is char , no sign conversion is peformed .
if converting from byte to char if no sign conversion is required than bitwise AND with 0xff is nice idea.
char c = (char) b & 0xff
Contract of Object.Hashcode in Java
In continuation with my ongoing summary series , today i am going to write about hashcode and objects in java . So lets get started .
The contract of hashcode in java
Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.
So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values
So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be
Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.
The contract of hashcode in java
- Inrrespective of the number of times hashcode is invoked on an object , it should return the same value.
- If two objects are equal then the hashcode values should also be the same.
Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.
So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values
So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be
public int hashCode(){
int result = 17;
result += 37 * field1;
result += 37 * field2;
return result;
}
Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.
Monday, June 04, 2007
Implementing the Assignment operator for your class in C++
The other day i was reading about the assignment operator in C++ . Here is my small understanding of it . The job of the assignment operator is to overwrite the members of your class , with the new provided members.
Contract of the assignment operator
We need to make sure that the object we are assigning is not the same object , other wise we would end up over writing the data members of the same object.
eg String s
s = s // this would not work if the above mentioned line is not there
Now lets move on to second point of the contract . Since the String class we have here is using characters which is something external to it . We need to delete it , re allocate it and then re initialize it .
// delete the characters
delete[] characters
// reallocate the characters
characters = new char[strlen(other.characters)+1];
Contract of the assignment operator
- The assignment operator must work properly when an object is assigned to itself.
- Since assignment is going to overwrite data for data of your object , the resources external to the object need to be free.
- The assignment operator should return a constant reference to the assigned object.
if(&other != this)
1 const String& String::operator= (const String& other){
2 if(&other != this){
3 delete[] characters;
4 characters = new char[strlen(other.characters)+1];
5 strcpy(characters,other.characters);
}
}
Now lets discuss the implementation step by step .
We need to make sure that the object we are assigning is not the same object , other wise we would end up over writing the data members of the same object.
eg String s
s = s // this would not work if the above mentioned line is not there
Now lets move on to second point of the contract . Since the String class we have here is using characters which is something external to it . We need to delete it , re allocate it and then re initialize it .
// delete the characters
delete[] characters
// reallocate the characters
characters = new char[strlen(other.characters)+1];
// re initialize the characters
strcpy(characters,other.characters);
Now the third point is its important that we return a const reference to the object
being assigned . Thats the reason we are returning *this and thats the reason why
function signature reads .
const String& String::operator= (const String& other)
The reason we need this is to prevent users from trreating assignments as lvalue .
Basically
String s;
(a = b ) = s
something like this should be illegal .
Saturday, June 02, 2007
How to override the equals method in Java
Well the other day i was reading about how to override the equals method in java . Here is brief summary of what i learnt .
Never Assume Anything:
First things first if you are writing a class whose equals method u have not overridden assumi ng that the equals method would never be called . never assume anything and atleast throw a UnsupportedOperationException to prevent others from doing a equality check on the instance of your class.
In terms of Code the equals method in your class should look like ,
The equals method must be
Now ok i ve implemented a hypothetical Point class that has only 1 member entity called x . That entity is an Object rather than being a primitive type.
if(point == this)
return true;
In this line i check the references are equals , if they are then can we can skip other checking cause basically they are the same two references .
if(!point instanceof Point)
return false;
Second we make sure the object that we are comparing against is of the same type and is not null . The not null is implicit in the behaviour of instanceof operator . The instanceof operator makes sure that object on the left is not null othwerise it returns false.
Point other = (Point) point;
Next we perform the casting to the type of this object so that we can check each and every field .
boolean result = true;
result = result &&amp; (x != null && x.equals(other.x));
Next since x is the field being used here , we check if x is not null and if its not null we see if its equal to the x field in the other Object.
return result;
Finally we return the result
Never Assume Anything:
First things first if you are writing a class whose equals method u have not overridden assumi ng that the equals method would never be called . never assume anything and atleast throw a UnsupportedOperationException to prevent others from doing a equality check on the instance of your class.
In terms of Code the equals method in your class should look like ,
Contract of Equals Method:
public boolean equals(Object other){
throw new UnsupportedOperationException();
}
The equals method must be
- reflexive
- transitive
- symmetric
- comapring with a null object should be false
public class Point {
private Object x;
public Point( Object x ) {
this.x = x;
}
public boolean equals(Object point){
if(point == this)
return true;
if(!point instanceof Point)
return false;
Point other = (Point) point;
boolean result = true;
result = result && (x == other.x || (x != null && x.equals(other.x)));
return result;
}
}
Now ok i ve implemented a hypothetical Point class that has only 1 member entity called x . That entity is an Object rather than being a primitive type.
if(point == this)
return true;
In this line i check the references are equals , if they are then can we can skip other checking cause basically they are the same two references .
if(!point instanceof Point)
return false;
Second we make sure the object that we are comparing against is of the same type and is not null . The not null is implicit in the behaviour of instanceof operator . The instanceof operator makes sure that object on the left is not null othwerise it returns false.
Point other = (Point) point;
Next we perform the casting to the type of this object so that we can check each and every field .
boolean result = true;
result = result &&amp; (x != null && x.equals(other.x));
Next since x is the field being used here , we check if x is not null and if its not null we see if its equal to the x field in the other Object.
return result;
Finally we return the result
Dividing a Sequence into K ranges
Problem Statement:
Say you have a sequence of N numbers and you want to partition the sequence into K groups such that after applying a cost function c(i) for each group the sum of all cost functions over all groups is minimized or maximized?
Approach:
To divide the sequence into ranges , we will use K keys . The key used to divide the group can be indices or values . If its values then numbers in the
sequence can be used along with values in the sequence to partition values into groups whose key is K.
One way to do this is to use K-for loops , if the key is value based then probable something like this would work:
After dividing the sequence into keys, use the keys to apply and aggregate the result of individual cost functions . Depending upon the requirement reduce the cost functions using functions like min , max depending upon if you want to minimize or maximize your result.
There you go , now u have 1 simple way of dividing a sequence into groups
Say you have a sequence of N numbers and you want to partition the sequence into K groups such that after applying a cost function c(i) for each group the sum of all cost functions over all groups is minimized or maximized?
Approach:
To divide the sequence into ranges , we will use K keys . The key used to divide the group can be indices or values . If its values then numbers in the
sequence can be used along with values in the sequence to partition values into groups whose key is K.
One way to do this is to use K-for loops , if the key is value based then probable something like this would work:
for i = 1 to n
for j = 1 to n
for k = 1 to n
for l = 1 to n{
key1 = seq[i]
key2 = seq[j]
key3 = seq[k]
key4 = seq[l]
}
After dividing the sequence into keys, use the keys to apply and aggregate the result of individual cost functions . Depending upon the requirement reduce the cost functions using functions like min , max depending upon if you want to minimize or maximize your result.
There you go , now u have 1 simple way of dividing a sequence into groups
Thursday, November 16, 2006
binding Source n Combo box initialization problem
I was trying to bind a combo box to a list of items . Now each item is a domain object .
myBindingSource.DataSource = my list of domain objects
i create a binding between the SelectedItem property of the combo box and the property Value of my domain object in the binding source .
now initially when the value of my domain object is null , i want an empty row to appear in the combo box , which works fine . Now as i choose different domain object values in the combo box , the value of the domain object is not refreshed .
I was using myComboBox_SelectedIndexChanged event to notify of the change in domain object value , but it was not helping the refreshing of other entities that depended on the values of the domain object .
So now instead of the SelectedIndexChanged Event now i use the
myBindingSource_CurrentChanged event and it works like a charm
Subscribe to:
Posts (Atom)
Labels
. linux
(1)
algorithm
(15)
analytics
(1)
bash
(2)
bigoh
(1)
bruteforce
(1)
c#
(1)
c++
(40)
collections
(1)
commands
(2)
const
(1)
cosine similarity
(1)
creating projects
(1)
daemon
(1)
device_drivers
(1)
eclipse
(6)
eclipse-plugin-development
(9)
equals
(1)
formatting
(1)
freebsd
(1)
game programming
(1)
hashcode
(1)
heap
(1)
heaps
(1)
immutable-objects
(1)
java
(19)
JDT
(1)
kernel
(1)
linux
(4)
little sugar
(23)
logging
(1)
machine learning
(1)
marker-resolution
(1)
markers
(1)
mergesort
(1)
mixins
(1)
numbers
(1)
opengl
(2)
patterns
(2)
priority-queue
(1)
programming
(51)
ps
(1)
ranking
(1)
refactoring
(3)
references
(1)
security
(1)
set
(1)
shell
(1)
similarity
(1)
statistics
(1)
stl
(1)
tetris
(1)
threads
(1)
trees
(2)
unicode
(1)
unix
(2)
views
(2)
windows programming
(2)
XNA
(1)