Gyaan

When we design an application we are the ones to govern the rules, it’s like a country having its own laws which everyone inside has to abide to and obviously, we don’t want people who won’t follow our jurisdiction. Assuming people keep the same persona both in and outside the country. There are several ways to ensure this, you can have a check-post to ensure whom you wish to allow inside, or you can allow everybody in & have cops to catch intruders when they disobey some laws, or you can simply have enough trust in the outside world to only send good people to your country. I am a big time believer of peace and hence strongly recommend the last. Rest of the blog is for people who simply cannot follow the crappie-big-time-believer-of-peace-ethic

Trust brings with it expectations. Since we programmers, unlike managers, don’t expect impossible things and hence we can say expectations are a small subset of possibilities. All code that you write, should be against expectations and not possibilities, with just one exception which we shall see later in the post. What this means is, your code should be free of try...catch blocks, unless one of the use case is expected to produce some exception, and even in such cases your catch block should be against that particular expected type of exception and not against all subclasses of Exception. Assume our acceptance criteria says, Divide should return Double.Infinity if we encounter division by zero.

A way to do this would be

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

publicdoubleDivide(MyNumber num1,MyNumber num2)

{

doubleresult;

try

{

result=num1.Value/num2.Value;

}

catch(Exception exception)

{

returnDouble.Infinity;

}

returnresult;

}

The above code is sure to return Double.Infinity if num2.Value were to be zero. Here even if we pass num1 or num2 as null, we will be returned Double.Infinity, since num1.Value / num2.Value will throw a NullReferenceException exception, which will be caught. As we are not expecting num1 or num2 to be null, we should be alerted when this happens. By catching it we will never know something unexpected even happened.

Right way to do it would be to only catch the expected DivideByZeroException & not others

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

publicdoubleDivide(MyNumber num1,MyNumber num2)

{

doubleresult;

try

{

result=num1.Value/num2.Value;

}

catch(DivideByZeroException exception)

{

returnDouble.Infinity;

}

returnresult;

}

Another thing to keep in mind is your try block should have as few statements & operators as possible. More the number of statements, less likely the exception occurred at the expected place.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// We are sure the exception occurred at the expected line

publicdoubleDivide(MyNumber num1,MyNumber num2)

{

doubleresult;

doublevalue1=num1.getValue();

doublevalue2=num2.getValue();

try

{

result=value1/value2;

}

catch(DivideByZeroException exception)

{

returnDouble.MaxValue;

}

returnresult;

}

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// We can't say the exception happened during division

// It may have been thrown by one of the getValue() calls too

// If latter was the case, we better come to know about it

publicdoubleDivide(MyNumber num1,MyNumber num2)

{

doubleresult;

try

{

result=num1.getValue()/num2.getValue();

}

catch(Exception exception)

{

returnDouble.MaxValue;

}

returnresult;

}

So what happens to all the exceptions that we did not catch? Any unhandled exception will crash your application. Let our application crash!! Are you crazy? you may say, well craziness is a relative term 🙂 When an exception that we were not prepared for occurs, its better to let your app sink, than to let it continue in an unknown and possibly inconsistent state. But the same can be done gracefully.

All applications/processes/threads have start points, like main() is a start point, so if anything inside fails it cascades back to these start points, this is one place where we use a generic try...catch(Exception e) and in the catch, we should log the exception, and let the user know that the ship is sinking. It gets a bit tricky with multi-threaded applications but most of these do have some event to subscribe to unhandled exceptions, in case of threads one can create a utility method that creates threads, and hence this utility becomes the start point of all user-created threads, and the try...catch can be deployed here. Note that, in case of unhandled exceptions in threads, only that thread will die and not necessarily entire application, some special care may be needed

eg: Catching unhandled exception in main

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

staticvoidMain(string[]args)

{

try

{

//All you code goes in here

}

catch(Exception ex)

{

Logger.log(ex);

Console.WriteLine("Some unknown error occured, the application will close now");

}

}

eg: Catching unhandled exception in multi-threaded applications.
This is the simplest way of achieving a streamlined thread creation mechanism and hence handling any exceptions in the new threads, we just need to make sure that any new thread should only be spawned using this method

Console.WriteLine("Some unknown error occurred, the application will close now");

}

};

}

So what does all this give us? This helps us track down all unexpected behaviors a.k.a defects which may have been hidden due to the improper exception handling. These exceptions in the generic catch blocks are your symptoms to a bigger problem which is waiting to be solved by you, so go and gear up with your debugging hat and get started…

Like this:

This one talks about the power of Interfaces, and how polymorphism can make things highly flexible and decoupled. Interface is a simple view of your class-to-be to the outside world, a perfect form of abstraction. Wikipedia says

A protocol or interface is a common means for unrelated objects to communicate with each other. These are definitions of methods and values which the objects agree upon in order to cooperate.

Lets take an example for better understanding. Assume, I am creating my good old calculator again.

JavaScript

1

2

3

4

5

6

7

8

9

publicclassCalculator{

publicButton[]Buttons;

publicDisplayPanel UserDisplay;

privateint_operand1;

privateint_operand2;

privatechar_operator;

privateintcalculate(){

}

}

Being poor, I can’t afford any staff to work on my jazzy calculator. I have come up with all my classes and stuff, but can’t start working on my calculators logic, as my Calculator has an object of type DisplayPanel, and I will have to complete the implementation of this class in order to use it in Calculator otherwise my compiler will simply keep complaining and won’t let me proceed. But Calculator seems far more interesting to start with than DisplayPanel. So what do I do? You may say, I will write the DisplayPanelclass and leave all the functions blank!! Smart 🙂 What about the non-void functions if any? You would return some random value based on the type of the return type of the function. Well, why do all this? I would simply go ahead and replace the type of UserDisplay from DisplayPanel with its interface (say IDisplayPanel).

JavaScript

1

2

3

4

5

6

7

publicinterfaceIDisplayPanel{

voidShow(stringdisplayString);

}

publicclassCalculator{

publicIDisplayPanel UserDisplay;

//...

}

Now, I can bindass go ahead and keep calling UserDisplay.Show(), without the trouble of keeping my compiler happy. This code will build with no compile errors, but will fail at run time since you can only call a function on a solid class instance, not interfaces. So how do I know if what I have written so far works or not? Well unit tests with mocking is the answer, I would like to defer this topic for a post in the near future.

After showing my Calculator idea to some biggy investors in the silicon valley, I manage to get funding to hire 2 assistants. Yippee, now I can get some work on the DisplayPanel started with their help. I assign this task to Bluto, one of my assistants. While my other assistant, Popeye, has no work for the time being and is enjoying spinach with Olive 🙂 Brutus thinks he has come up with an exciting implementation and even I have finished working on my Calculator

Time to merge the code gentlemen!

Scary??? No, all that we need to do is assign the UserDisplay to a concrete class, the one Brutus wrote, before I make any call to any of its methods. Best place is in the constructor.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

publicclass DisplayPanelByBrutus:IDisplayPanel{

voidShow(stringdisplayString){

//...

}

}

publicclassCalculator{

publicIDisplayPanel UserDisplay;

publicCalculator(){

UserDisplay=newDisplayPanelByBrutus();

//...

}

//...

}

Great !!! All works fine, but….. Brutus, as dumb as he is, came up with a very lame and irritating implementation of the IDisplayPanel, this one throws a big message box (IE Style) to the user with the content to display, that too every time I press any button on the calculator :'( !! Popeye, meanwhile knew how pissed I would be, and had already prepared another implementation that he was ready to show me. Better than I thought, a sleek panel on top of all my calculator buttons to immediately show what key the user presses and the result too. Yes, the windows calculator is a complete rip off of Popeye’s version. Wow!!! Totally wanted to get this into my production code. But code change again!!! Well this time it’s just a one line change, in fact half a line.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

publicclass BakwasDisplayPanelByBrutus:IDisplayPanel{

voidShow(stringdisplayString){

//...

}

}

publicclass AwesomeDisplayPanelByPopeye:IDisplayPanel{

voidShow(stringdisplayString){

//...

}

}

publicclassCalculator{

publicIDisplayPanel UserDisplay;

publicCalculator(){

//UserDisplay=new BakwasDisplayPanelByBrutus();

UserDisplay=newAwesomeDisplayPanelByPopeye();

//...

}

//...

}

Hope the IMagic got through to you by now. Interfaces allow us to decouple our implementations. You are not bound to someone’s speed of coding. Before you get working on your code that uses someone’s code all you need to do now is just sit together, analyze and agree upon an interface that you both are comfortable with, and both can proceed peacefully and independently. Also, this allows easy migration from one implementation to the other, imagine if you had to change the implementation in case of concrete classes, you would change the body of all your functions, and if the new implementation turned out to be worse, you don’t even have the old code to rollback to, unless you have taken some backup, which again would be tedious to some extent. Here all you do is just change the constructor, and still both the implementations co-exist, this gives the user a choice as well.

Another, in my opinion more powerful, advantage that interfaces give, is when we are actually dealing with enterprise software that depend on third party pluggable code. (You may want to skip to the end, if you are an absolute beginner). In a more complex aka real-world application, you may not have all the code in the same file, in fact not even in same project. Here all you would have is the interface, which would generally be shared across projects. In such cases, your Calculator class won’t even know there is something called AwesomeDisplayPanelByPopeye, only the classes using this calculator may know about it. Hence your statement

JavaScript

1

UserDisplay=newAwesomeDisplayPanelByPopeye();

Will give a compile error as the class AwesomeDisplayPanelByPopeye is not present in any of the referenced libraries. In such cases, or even otherwise, a concept named Dependency Injection comes into play. In our case, the Calculator is dependent on IDisplayPanel, we don’t want the calculator to decide which implementation of this interface to use, but let the user of the Calculator decide it instead. This is done in various ways, one of them is through the constructor. We remove the default parameter-less constructor, and instead use a constructor that takes an object of type IDisplayPanel, and assign this object to our UserPanel as follows.

JavaScript

1

2

3

4

5

6

7

8

publicclassCalculator{

publicIDisplayPanel UserDisplay;

publicCalculator(IDisplayPanel someDisplayPanel){

UserDisplay=someDisplayPanel;

//...

}

//...

}

Now, your code is truly agnostic of the implementation of IDisplayPanel that it will use. You can now have n different Calculators from the single Calculator that you wrote. Today’s world is all about choices, more choice you give, more people will use it 🙂

Like this:

Most of us have gone through books with various definitions/introductions on Object Oriented Programming, these contain then-jargon like abstraction, polymorphism, inheritance, encapsulation, etc. in the very first chapter. How to easily understand all that when we are just starting? To some, it’s too much of spices when they don’t know what common salt is.

To begin with, all we need to know is a class. Class, in simple words is Kind or Family. Let’s say I have a calculator, I like to call it Jugal's Calculator giving a sense of possession. So now, we ask Jugal's Calculator is of what kind? The simplest kind we can identify without knowing the brand or functionality this calculator gives, would be of kind Calculator. It so happens that John Doe also has a calculator, which he calls JDC. From what we know, JDC also belongs to the family of Calculator. So here, Calculator is our Class and Jugal's Calculator & JDC, which are things of those kind, are called objects or instances of the class Calculator.

Object Oriented Programming, as name suggests, revolves around these things or objects that we just defined.

What (but not how) this object can do? (encapsulation)

What families does the object belong to? (abstraction)

What it is made up of? (composition)

Does another object already do a part of what I am supposed to? (inheritance)

And more complex (yet interesting) things like Polymorphism, etc

We have very loosely defined these terms for understanding purposes, the real meanings will be clearer as we get a better hang of their usages. I also like to call it Real-World Programming. RWP??? We create data structures/classes with the aim of having an analogy to the real world.

With all that said, let’s see how to create a neat class. Things we need to keep in mind are,

What will be the primary objective of the objects of this class?

What data will they need to have, in order to do these actions efficiently?

These two questions would allow us to define the public part of the class. I would love to use interfaces here, but want to keep things simple till we make them complex ;). If you think you know the answers to these two questions, think again =D.

So, if we have to design a very simple calculator, which even our great grandfathers might not use, what would be our class(es)? Let’s say, this calculator can only perform add and subtract.

JavaScript

1

2

3

4

5

6

publicclassCalculator{

publicintAdd(intx,inty){

}

publicintSubtract(intx,inty){

}

}

And we are all happy? Not me. This wouldn’t be wrong or not serve the purpose, just that it doesn’t translate into the real world analogy concept. How many of you have a calculator that asks for the operator first (Add) and then the two numbers and gives the answer back to you? The way calculators work is to give first operand, give operator and then second operand and get the result.

Lets answer the first question.Add? Subtract? Add & Subtract? I would say, the primary objective of the calculator is to simply Calculate!! Add & Subtract are merely types of calculations.

Now the second question.
It just needs two operands and an operator.

JavaScript

1

2

3

4

5

6

7

publicclassCalculator{

publicintOperand1;

publicintOperand2;

publiccharOperator;

publicintCalculate(){

}

}

So now are we happy? I ain’t yet. This still isn’t real world. A calculator consists of buttons and a display. This is now real world. So we introduce two more types of objects, Button & Display. This is how OOP is supposed to work. Breaking down responsibilities and delegating them so you only do what is your primary role.

In this new approach, the user doesn’t actually interact with Calculator directly, it uses the buttons, which are part of the calculator. The user can press a button. In fact that is all the user can actually do 🙂 Making all the above class members (Operand1, Operand2, Operator, Calculate()) not directly accessible to the user. Thus, they would all become private and an array of Buttons would be the only thing public to the user. Each button would merely expose a method (say, Press()) for the user to interact. Also there would be DisplayPanel that user can view.

I will refrain from going into the implementation details and aim to highlight the process of coming up with the right classes and not implementing them.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

publicclassCalculator{

publicButton[]Buttons;

publicDisplayPanel UserDisplay;

privateint_operand1;

privateint_operand2;

privatechar_operator;

privateintcalculate(){

}

}

publicclassButton{

publicvoidPress(){

}

publicStringDisplayName;

}

publicclassDisplayPanel{

publicvoidShow(stringdisplayString){

}

}

A question may arise, that why not break up the Button or the DisplayPanel into smaller classes too? Yes, sure go ahead, but for the purpose of creating the class Calculator, we are only concerned about the Button and the DisplayPanel, that’s the beauty of abstraction. You are least bothered of the implementation. Calculator doesn’t care if the DisplayPanel consists of LEDs or Printer or whatever, it only knows that it can call on the method Show() with the string it wants to display.

This process may appear to be inundating at first but would come naturally, like any spoken language that you know, once put into practice. Also the real life correlation helps others to quickly understand your code and approach.