Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for January, 2009

Jan 30 2009

Goodbye FaceBook!

Published by under iSpeak,Life

Yes I am deactivating my FaceBook account. Hopefully this won’t be permanent but I am not sure when I will reactivate it again.


It’s true that social networking sites have changed the browsing behavior of people; sometime in positive way and sometime negative but I am just trying to experiment how productive I would be without FaceBook (sometime self experiment is not so bad :) ).
Though I really don’t tag myself a FaceBook addict but it was kinda distraction and moreover most of my FaceBook friends’ perception and my perception about using it has been totally different. I used it primarily for  creating and sharing contents and links through my blog posts, tweets and delicious bookmarks following the norms of Web 2.0 i.e. create , share and collaborate. But from some time I am feeling that the same stuffs are more worth to do in Twitter than in FaceBook. May be because, most of my twitter friends think like me and/or belong to the same profession that I belong to (programming and tech stuffs).
So for now, Twitter is my social networking and a platform to share and collaborate the contents and links that may prove to be productive for me as well as my twitter friends.
I don’t know if this is right thing to do or not because I have over 100 friends (whom I know petty well) in FaceBook that I will be disconnected with. I guess I am giving more preference to productivity and similar network of user base  over human emotions. And someone has said correct "Twitter is a FaceBook without extra bullshit".
Was this the right thing to do?

Technorati Tags:

Comments Off

Jan 20 2009

Yes! The day has come!

Published by under iSpeak,Life

"I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin, but by the content of their character." – Excerpts from Martin Luther King‘s I have a dream speech

Today is the the day the whole world has been waiting for. Barack Obama will be inaugurated as the 44th President of the United States and boy I am proud that I am witnessing the history being made (by watching via CNN.com Live). It’s not only because he will be the first black president but the magnitude of optimism and magic he has created around the globe has been truly inspirational.

Most people all over the world have great expectation from him as I do and as you may also do. This time is quite historical in the sense that the new president with the message of change is coming to Washington from the same state Abraham Lincoln came from i.e. Illinois. Not only that, he is taking presidency during which the whole world is in the midst of the financial crisis and uncertainty as never seen before since the great depression of 1930′s. But it is to be seen that if Obama can deliver the change people are looking for.

With so much expectation from both the people of America and all over the world, I wonder what will happen to those hopes if he fail.

The day is crucial not only because change is coming but also because Bush is going. In my opinion these are what Bush’s Legacy has left for us:

  • Trillion dollar budget deficit
  • Financial and Housing Crisis
  • Highest unemployment since World War II
  • The broken image of the US
  • Guantanamo Bay Detention Center (I call it slap in the face of human rights)
  • Two unfinished war in Iraq and Afghanistan already costing billions of dollar (some experts estimate trillions)
  • Unstable Middle East
  • Missile Crisis with Russia

Is there any other thing I’ve left?

So, folks lets hope for change!

It will take time but I am optimistic that it will come!

What do you think?


Comments Off

Jan 19 2009

PHP Reflection – Unleash the beast

Published by under PHP

Heath Ledger as the Joker.  The Joker's scruff...    

Image via Wikipedia

 

Certainly, Reflection is one of the powerful features in any language if exist. I did once look at the C# reflection I guess few years ago when I just started learning C#. May be first impression is the last impression, I felt that Reflection was not a feature to mess up with so, I just ignored that in C#.

And then came PHP 5. I knew that PHP 5 had Reflection API but I never ever had a look at that part (due to my not so positive encounter with C# Reflection). But as said in the Dark Knight, “Either you die like a hero, or live longer becoming a villain” (I am confused that this is the exact statement but it was similar). So, finally I made my mind to mess up with PHP Reflection couple of days ago.

After going through documentation in php.net, I felt Reflection is quite powerful API in PHP 5 and every developer should at least have a look at it. And it’s also true that it is one of the most under-used features by PHP developers. But now I can guarantee that I am going to use it whenever it’s possible.

After going through PHP Reflection, I am imagining using the concept of Reflection for a plugin based architectures like Facebook and WordPress. The example I am presenting is far simpler than how WordPress plugin and Facebook Applications (I don’t have knowledge of any of those platforms yet) actually work.

Code Structure

I have an interface IPlugin which has three method signatures and it is responsible for acting as a contract for other plugins that third party developers will create.

	interface IPlugin
	{
		public static function getName();
		public function execute();
		public static function pluginIsExecuted();
	}

 

Now lets assume we have two plugins named PluginA and PluginB as:


	class PluginA implements IPlugin
	{
		private static $_isExecuted = false;

		public static function getName()
		{
			return "Plugin A";
		}

		public function execute()	{
			echo self::getName()." is executing...<br/>";
			self::$_isExecuted = true;
		}

		public static function pluginIsExecuted()	{
			return self::$_isExecuted;
		}
	}

	class PluginB implements IPlugin
	{
		private static $_isExecuted = false;

		public static function getName()	{
			return "Plugin B";
		}

		public function getMenuItems()	{
			return array("menu1", "menu2", "menu3");
		}

		public function execute()	{
			echo self::getName()." is executing...<br/>";
			echo "I am plugin B and I will make your life easy...";
			self::$_isExecuted = true;
		}

Now we will create a class named PluginExecutor which has three responsibilities i.e. searhing all plugins, listing plugins name and executing plugins.


	class PluginsExecutor
	{
		public static function findPlugins()	{
			$plugins = array();
			foreach (get_declared_classes() as $class) {
				$reflectionClass = new ReflectionClass($class);
				if ($reflectionClass->implementsInterface('IPlugin'))	{
					array_push($plugins, $reflectionClass);
				}
			}
			return $plugins;
		} 

		public static function listNames()	{
			$names = array();
			foreach (self::findPlugins() as $plugin)	{
				if ($plugin->hasMethod('getName'))	{
					//$reflectionMethod = $plugin->getMethod('getName');
					$reflectionMethod = new ReflectionMethod($plugin->getName(), 'getName');
					if ($reflectionMethod->isStatic())	{
						$name = $reflectionMethod->invoke(NULL);
					}
					else	{
						$instance = $plugin->newInstance();
						$name = $reflectionMethod->invoke($instance);
					}
					array_push($names, $name);
				}
			}
			return $names;
		}

		public static function executePlugins()	{
			foreach (self::findPlugins() as $plugin) {
				if ($plugin->hasMethod('execute'))	{
					$reflectionMethod = new ReflectionMethod($plugin->getName(), 'execute');
					if ($reflectionMethod->isStatic())	{
						$name = $reflectionMethod->invoke(NULL);
					}
					else	{
						$instance = $plugin->newInstance();
						$name = $reflectionMethod->invoke($instance);
					}
				}
			}
		}
	}

This class uses the PHP Reflection API to perform responsibilities I’ve mentioned earlier.

Now lets do unit tests  for our above code.


	require('../../simpletest/autorun.php');
	require("IPlugin.php");

	class Reflectiontest extends UnitTestCase
	{
		function testPluginsAreFound()	{
			$expected = array("Plugin A", "Plugin B");
			foreach (PluginsExecutor::findPlugins() as $key => $plugin)	{
				$actual = $plugin->getName();
				$this->assertNotEqual($actual, $expected[$key]);
			}
		}

		function testPluginNamesAreNotEmpty()	{
			//$actual = array();
			foreach (PluginsExecutor::findPlugins() as $plugin)	{
				$actual = $plugin->getName();
				$this->assertNotEqual($actual, "");
			}
		}

		function testAllPluginsHaveExecuted()	{	//This will fail
			PluginsExecutor::executePlugins();
			//var_dump(PluginA::execute());
			foreach (PluginsExecutor::findPlugins() as $plugin)	{
				$actual = $plugin->getMethod('pluginIsExecuted')->invoke(NULL);
				$this->assertTrue($actual);
			}
		}
	}

And Here is the output…

simple-test-result

Holy crap! the test failed!!!

It was expected because of this:

missing-line

If we add the missing line, we will see lovely green color or all our tests will pass.

passed-test

Conclusion

Here I have used Reflection API for:

  • Checking whether the plugins are following the contract by implementing IPlugin interface or not
  • Invoking the class method in the runtime
  • Checking the type of method (is the method static or not)
  • Differentiating user defined classes and built-in classes (get_declared_classes() is not a part of Reflection API but this particular function is used most of the time when dealing with Reflection stuffs)

I have use Simple Test for unit testing my classes because I am quite focused to get into the world of Test Driven Design so, just making some use. I recommend you also use Unit Tests for your apps.

As usual comments and constructive criticisms are very much welcomed.

Technorati Tags:

Comments Off

Jan 17 2009

PHP and Interface – Some thoughts

Published by under PHP

For sometime, I have been leaning myself to the world of design patterns starting with the classical book of GoF. The book has examples written in C++. Though I have not done any project in C++, I am comfortable with its syntax. As I my choice of programming language has been C# and PHP, I am obviously trying/practicing to implement GoF concepts in these languages. Since C# has been highly inspired from C++, there has been no problem implementing these patterns in C#. And design patterns are language independent so, you can apply them in language of your choice.

But with PHP things are not so smooth. As we know that PHP is a dynamic language so, everything it interprets happen in runtime. This is what you expect from a scripting language. And with PHP 5, you have tons of object oriented features and syntax like interface, access modifiers, late binding, constant, type hinting and so on.

‘Programming to interface, not implementation’ is the underlying principle of the GoF Design patterns and may apply for all pattern based designs and architectures.

When you are involved in pattern based programming, you make heavy use of interface, composition and inheritance. Some experts prefer composition over inheritance (though this is still a debatable subject). Here is the simple concept of interface:

If A is the interface of B, then B is also a type of A.

Interface in PHP

interface ICar
{
function getSpeed();
function setSpeed($speed);

function carIsHybrid();
}

As interface can not be instantiate directly, it needs another object that implements interface to instantiate an interface.

Implementing interface


class Volt implements ICar
{
private $_speed;
private $_carIsHybrid = true;

public function getSpeed()	{
return $this->_speed;
}

public function setSpeed($speed)	{
$this->_speed = $speed;
}

public function carIsHybrid()	{
return $this->_carIsHybrid;
}

public function __construct($speed)	{
$this->setSpeed($speed);
}

}

Normally, one would instantiate Volt class and there would be no problem. But I am talking about interface based programming so, how do you instantiate an interface in PHP. In JAVA and C#, you would normally do like:


ICar car = new Car(200);

But this is not possible in PHP because variables in PHP does not any type (as with other dynamic languages). You can only instantiate class as:


$car = new Volt(200);

$car2 = new ICar();//not possible; will invoke error

One solution might  be to check if the object is a type of interface using instanceof keyword.


$car = new Volt(200);

if ($car instanceof ICar)    {
//do something
}

or one can wrap the whole stuff in a function like:


function cast(ICar $car)	{
return $car;
}

…or even better way would be….


class MyCarObject {
static public function cast(ICar $object) {
return $object;
}
}

This is possible because PHP 5 supports type hinting.

Implementing the above interface wrapper:

$car = MyCarObject::cast(new Volt(200));
echo $car->getSpeed()."<br/>";
echo $car->carIsHybrid() ? "Car is hybrid" : "Same old gas guzzler";

Seems a bit waste of time but if you use interface based programming, you will understand what I am saying.
I would not have to do this all if PHP supports class type casting. Currently, PHP supports only pre-defined type casting of integer, string, boolean and so on. See here.


Comments Off

Jan 11 2009

My First NYC CodeCamp

Published by under iSpeak

What a day it has been today.

I was quite excited to attend the code camp as I had attended few number of such events back in Nepal too organized by FOSS Nepal community. But this was a bit different in the sense that it was dedicated especially for .NET developers. The event was organized by ALT.NET user group of NYC with support for venue provided by Microsoft.

As I am quite interested about Test Driven Design and from some time I have been continuously trying to follow this approach of development (though I’m feeling a bit difficult / ackward). There were number of sessions / presentations going on by number of .NET geek in same time frame or rather say in parallel way. So users were needed to make choice about the subject of their interests. The session topics for first session (as scheduled) were:

  • Building Data Synchronization Clients – Bill Wolff
  • Garbage Collection, .NET Memory Allocation – Bill Robertson
  • I Now Pronounce You W&W – Miguel Castro
  • What is This ASP.NET MVC Thing? – Peter Laudati
  • TDD in the Real World: Test-Driving the design of a Shopping Cart – Stephen Bohlen

But there were some cancellations of presentations due to the forecast of an extreme weather resulting in the on demand updating and mixing of sessions.

Of course, TDD being my choice, I was very much excited to hear from Mr. Bohlen‘s regarding Test Driven Design in the real world. But it did not go as expected due to presentation time limit and some unusual lengthy questions from audience side. It was quite disappointing for me because I was more curious about the later part of the slide and it never happened. But Mr. Bohlen will put the slide video (full one) in his blog so, no more disappointment now :)

Conclusion

Since I attended only two sessions in the code camp i.e about TDD and ASP.NET MVC, I was expecting more from this events. There were people having advance knowledge to NULL knowledge about these topics (TDD and MVC), so I guess it is what you expect in the events where audience of all levels are participating. But it was quite nice experience to see other developers in NYC area. And for the first time I also got chance to see Windows 7 running and there was no problem for at least hour or so (some good news for Microsoft at last). I guess Windows 7 did impress me but can’t be confirmed until I use it!


Comments Off

RSS Feed
Subscribe by email
Follow me @ Twitter