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
}
}
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)