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

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 .

  1. Create an IProject with a name
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
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.

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.

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 :

  • 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 :
  • 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
Returning a functional object means applyting a function on the parameters of a method and returning the function rather than calculating the function and returning the value . e.g

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...

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 .

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 :
  1. HashSet
  2. TreeSet
  3. LinkedHashSet
HashSet:
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();

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
  1. pointer to a const
  2. const reference
Pointer to a const:
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
  1. a line
  2. a square shaped block
  3. a L shaped block
  4. a J shaped block
  5. a S shaped block
  6. a T shaped block
  7. a Z shaped block
Now each of these blocks contain exactly 4 squares . So the basic unit is a square and we build blocks out of these squares .

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 :

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 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 .

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

  1. static_cast <>
  2. const_cast <>
  3. dynamic_cast <>
  4. 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


class String {
char * string;
public:
String(const char * str = "");
};

void print(String & str);
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 .

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 .

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

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

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
  • 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.
Generally , it s a good practise to store the implement the hashcode of two objects when you implement the equals of an object . You ask why ??

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
  • 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.
Let me give you a reference implementation first . Then we can discuss about the contract.

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 .
if(&other != this)

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 .