<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Shyam &#187; polymorphism</title>
	<atom:link href="http://theshyam.com/tag/polymorphism/feed/" rel="self" type="application/rss+xml" />
	<link>http://theshyam.com</link>
	<description>Ramblings from the Real Shyam; You know, unlike those other fake Shyams!</description>
	<lastBuildDate>Sun, 08 Jan 2012 13:07:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Polymorphism instead of Conditionals</title>
		<link>http://theshyam.com/2009/09/using-polymorphism-instead-of-conditionals/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-polymorphism-instead-of-conditionals</link>
		<comments>http://theshyam.com/2009/09/using-polymorphism-instead-of-conditionals/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 16:49:38 +0000</pubDate>
		<dc:creator>shyam</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Technique]]></category>
		<category><![CDATA[conditionals]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[polymorphism]]></category>

		<guid isPermaLink="false">http://theshyam.com/?p=223</guid>
		<description><![CDATA[Interviewing nowadays with tech companies has become run of the mill. You have phone screens, then you are brought on for on site interviews. And in each one of these, you are asked one mind-bending, off-ball algorithm question after another. I personally have been on both sides of the interview table, having asked and been [...]]]></description>
			<content:encoded><![CDATA[<p>Interviewing nowadays with tech companies has become run of the mill. You have phone screens, then you are brought on for on site interviews. And in each one of these, you are asked one mind-bending, off-ball algorithm question after another. I personally have been on both sides of the interview table, having asked and been asked my fair share of these. And after a while, I started questioning whether these questions provided any insight into how interviewees think other than their knowledge of algorithms.</p>
<p>It was then that I decided I wanted to try and find out if the candidates really understood polymorphism and other concepts, rather than their knowledge of algorithms, since every other interviewer would be covering that. And that was when I stumbled upon this gem of a question, which also underlies a fundamental concept of object oriented programming.</p>
<p>The question is simple. <strong>&#8220;Given a mathematical expression, like 2 + 3 * 5, which can be represented as a binary tree, how would you design the classes and code the methods so that I can call <em>evaluate() </em>and <em>toString()</em> on any node of the tree and get the correct value.&#8221;</strong>. Of course, I would clarify that populating the tree was out of the scope of the problem, so they had a filled in tree to work with. It also gives me a chance to figure out how the candidate thinks, whether he asks whether filling in the tree is his problem or whether he just assumes stuff. You could preface this question with another about Tree&#8217;s and traversal to check the candidate&#8217;s knowledge and whether this one would be a waste of time or not.</p>
<p>Now, one of three things can happen at this point. One, the candidate has no clue about trees and traversals, in which case there is no point proceeding down this line. Second, which seems to happen more often than not, is the candidate gives a class and method like the following :</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">class</span> Node <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">char</span> operator<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">int</span> lhsValue, rhsValue<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; Node left, right<span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> evaluate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">int</span> leftVal <span style="color: #339933;">=</span> left <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">?</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lhsValue <span style="color: #339933;">:</span> left.<span style="color: #006633;">evaluate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">int</span> rightVal <span style="color: #339933;">=</span> right <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">?</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rhsValue <span style="color: #339933;">:</span> right.<span style="color: #006633;">evaluate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>operator <span style="color: #339933;">==</span> <span style="color: #0000ff;">'+'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> leftVal <span style="color: #339933;">+</span> rightVal<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>operator <span style="color: #339933;">==</span> <span style="color: #0000ff;">'-'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">// So on and so forth.</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">// Same for toString()</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>
<p>Whenever I see code like the example above, it just screams that whoever is writing it has no clue about how to work with Polymorphism. While I agree that some conditionals are needed, like checks for boundary conditions, but when you keep working with similar variables, but apply different operations to them based on condition, that is the perfect place for polymorphism and reducing the code complexity.</p>
<p>In the above case, the biggest problem is that all the code and logic is enclosed in a single method. So when a candidate presents me with this solution, the first thing I ask is what happens when we need to add another operation, like division or something. When the prompt answer is that we add an if condition, that is when I prompt and ask if there is not a cleaner solution, which would keep code separate. Finally, often, you depend on third party libraries for functionality. Well, in those cases, you won&#8217;t be able to edit the original source code, leaving you cursing the developer who wrote it for not allowing an extensible design.</p>
<p>The <strong>ideal answer</strong> would, for this question, be that <strong>Node is an interface</strong> with evaluate() and toString(). Then, we have <strong>different implementations of Node</strong>, like a <strong>ValueNode</strong>, an <strong>AdditionOperationNode</strong>, and so on and so forth. The implementations would look as follows :</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">interface</span> Node <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">int</span> evaluate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ValueNode<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> value<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> evaluate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> value <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AdditionOperationNode<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">implements</span> Node <span style="color: #009900;">&#123;</span><br />
&nbsp; Node left, right<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> evaluate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> left.<span style="color: #006633;">evaluate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933;">+</span> right.<span style="color: #006633;">evaluate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> left.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; + &quot;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933;">+</span> right.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>
<p>You could go one step further and have an abstract base class for all operations with a Node left and right, but I would be well satisfied with just the above solution. Now, adding another operation is as simple as just adding another class with the particular implementation. Testing-wise, each class can be tested separately and independently, and each class has one and only one responsibility.</p>
<p>Now there are usually two types of conditionals you can&#8217;t replace with Polymorphism. Those are comparatives (&gt;, &lt;) (or working with primitives, usually), and boundary cases, sometimes. And those two are language specific as well, as in Java only. Some other languages allow you to pass closures around, which obfuscate the need for conditionals.</p>
<p>Of course, one might say that this is overkill. The if conditions don&#8217;t really make it hard to read. Sure, with the example above, maybe. But when was the last time you had just one level of nesting? Most times, these conditionals are within conditionals which are within loops. And then, every bit of readability helps. Not to mention there is a combinatorial explosion of the amount of code paths through a method. In that case, wouldn&#8217;t it be easier to test that the correct method is called on a class, and just test those individually to do the right thing?</p>
<p>So next time you are adding a conditional to your code, stop and think about it for a second, before you go ahead and add it in.</p>
]]></content:encoded>
			<wfw:commentRss>http://theshyam.com/2009/09/using-polymorphism-instead-of-conditionals/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Is Inheritance overrated ? Needed even?</title>
		<link>http://theshyam.com/2009/08/is-inheritance-overrated-needed-even/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=is-inheritance-overrated-needed-even</link>
		<comments>http://theshyam.com/2009/08/is-inheritance-overrated-needed-even/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 20:51:27 +0000</pubDate>
		<dc:creator>shyam</dc:creator>
				<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[noop]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[polymorphism]]></category>

		<guid isPermaLink="false">http://theshyam.com/?p=172</guid>
		<description><![CDATA[To give some context to this topic, the idea was brought forward to me by Alex Eagle. I was happily coding away when Alex sprung his idea for Composition over Inheritance for Noop &#8211; a language we are developing with testability and dependency injection in mind. My gut reaction was that this was blasphemy, and [...]]]></description>
			<content:encoded><![CDATA[<p>To give some context to this topic, the idea was brought forward to me by <a href="http://jakeherringbone.com/" target="_blank">Alex Eagle</a>. I was happily coding away when Alex sprung his idea for <a href="http://code.google.com/p/noop/wiki/ProposalForComposition">Composition over Inheritance</a> for <a href="http://code.google.com/p/noop/">Noop</a> &#8211; a language we are developing with testability and dependency injection in mind. My gut reaction was that this was <strong>blasphemy</strong>, and it <strong>couldn&#8217;t be done</strong>. You can&#8217;t just do away with inheritance, its one of the building blocks of OO based programming languages. But now, after I have let the idea digest for a few days, it doesn&#8217;t seem so far fetched any more. And here&#8217;s why.</p>
<p>Let me first talk about the biggest problems with vanilla inheritance as we have it in Java. Joshua Bloch hits it on the nail in his <strong>Effective Java</strong> book item about &#8220;<strong><em>Favoring composition over inheritance</em></strong>.&#8221; But lets do a quick recap anyway.</p>
<p>The biggest problem is that inheritance often ends up <strong>breaking encapsulation</strong>. This is because the child class depends on the implementation of the parent class. But between releases, something in the parent class implementation can change and can break all child classes without even touching its code. Another common gotcha is in how protected fields and members are used. Often, the parent class changes the value of fields depending on how methods are called. Not understanding this behavior often leads to buggy or simply wrong behavior from the subclasses.</p>
<p>Another problem with a subclass &#8211; especially from the point of view of unit testing &#8211; is that there is <strong>no way to create an instance of the subclass in isolation</strong>. By this, I mean that everytime I create an instance of the subclass, I am forced to have the parent class as well. In most cases, this shouldn&#8217;t be a problem, but I have run into situations where the parent class is just a landmine waiting to explode, with the default constructor not being explicit in stating its dependencies. So instant Kablaam!!! Or the parent class will load things you don&#8217;t really care about and make things slow in a test. There was this insidious test I ran into once, which extended a base test case, which did the same thing. About 7 layers deep. And the test itself didn&#8217;t really care about 3 or 4 of those layers, but had to jump through all the hoops and get everything because it was a parent class.</p>
<p>There are a few more issues, which are well documented in Effective Java item 16, &#8220;Favor composition over inheritance.&#8221;. I won&#8217;t bore you further on this, assuming I have convinced the skeptics about the problems with inheritance. If not, go read that book, and you shall be convinced. But then, I wanted to postulate on whether it was at all possible to have a programming language which does away with inheritance (As <a href="http://code.google.com/p/noop/wiki/ProposalForComposition" target="_blank">Noop proposes</a>).</p>
<p>So when do we use inheritance ? To me, Polymorphism is about the only time when inheritance and subclassing is deemed appropriate. Be it having different subtypes or just plain old code reuse. So unless you want to have a base abstract class which has some methods defined (Like Shape with draw() method and Circles and Rectangles), inheritance is not really needed.</p>
<p>In Java, interfaces allow you to perform polymorphic operations with abandon, and convert between types. And interfaces don&#8217;t straddle you down with the requirement that you get the base class for every instance.</p>
<p>Also, if you use composition, then you can reuse code by using delegation. For example, you could define a Shape interface with a DefaultShape implementation. Now rather than subclassing a concrete type Shape, you could have a Rectangle which implements Shape. And if you wanted to reuse some code, let Rectangle take in a DefaultShape instance and just delegate to it when necessary. This offers multiple benefits. One, you are not tied down to getting things from the base class. In your test, you could pass in a mock, a null, whatever you want. The only problem is that this option is not viable if you don&#8217;t have an interface. If that is the case (or the thing you are subclassing is in a package outside of your control), then you are stuck doing inheritance the old fashioned way.</p>
<p>And this is (atleast the last time I heard the proposal) what Noop aims to solve. When you want to subclass, you tell the class what you want to compose. Regardless of whether it is an interface or not, it will create that class with an instance of your composition type. By default, all methods in the composition type will be available in the subclass, and it will delegate automatically, unless you override it. You get complete control over object creation, and this could potentially support multiple inheritance through this approach.</p>
<p>What do other people think ? It this feasible ? Am I missing something obvious when inheritance is the only approach and composition just doesn&#8217;t cut it (both right now and in the Noop proposal) ? Are you interested in Noop ? Drop me a line.</p>
]]></content:encoded>
			<wfw:commentRss>http://theshyam.com/2009/08/is-inheritance-overrated-needed-even/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

