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.

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 .

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 )

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.

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();

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

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)();

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 .

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;

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 .

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

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

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 {
};

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

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.

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 .

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 .

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

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 .

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 .

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 ,


public boolean equals(Object other){
throw new UnsupportedOperationException();
}
Contract of Equals Method:
The equals method must be
  • reflexive
  • transitive
  • symmetric
  • comapring with a null object should be false
So say if we want to compare two Point Objects


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;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:


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