Saturday, November 26, 2011

Re-throwing exceptions.

Today we will talk about re-throwing exceptions. In many cases, after examining a caught exception, it doesn't fulfill some requirements and we must re-throw it. This is a very basic and simple action in C# but for the Java developers there is a trap. In the aforementioned scenario, in Java we would just write:
throw e;
were e is the exception we caught.
Why don't we do the same in C# and see what will happen. Below is a sample code that illustrates such situation:
   class Program
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw e;
}
}
}
Now lets execute it and examine the stack trace:
System.Exception was unhandled
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
What did happen here? We somehow lost the whole stack trace. Now it looks like the exception was created within the Main method – in a real life scenario that may cause many problems when troubleshooting.
How to do it correctly in C# and preserve the whole stack trace? Here is the answer:
   class Program
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw;
}
}
}
Yes! Simple
throw;
solves the issue. Now our stack trace will look as follows:
System.Exception was unhandled
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.m4() in C:\Path\Program.cs:line 210
at ConsoleApplication1.Program.m3() in C:\Path\Program.cs:line 207
at ConsoleApplication1.Program.m2() in C:\Path\Program.cs:line 206
at ConsoleApplication1.Program.m1() in C:\Path\Program.cs:line 205
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
...
Looks much better – we can see which method thrown the exception and thus find the source of the issue.
So Java developers – bear that difference in mind and avoid confusion when analyzing a half empty stack trace! :)

Saturday, November 19, 2011

Exception handling – multiple catch.

Let's talk about the exception handling. Just to ensure that we are standing on the same planet – multiple catch of exception is a situation when we have a method that throws more than one checked exception and we want to handle some of them separetly. The following Java code shows such situation:

import java.util.ArrayList;
import java.util.List;

class Exception1 extends Exception {}
class Exception2 extends Exception {}
class Exception3 extends Exception {}

public class ExceptionHandling {
public static void throwsExceptions() throws Exception1, Exception2, Exception3 {
return;
}

public static void testMethod() {
try {
throwsExceptions();
}
catch(Exception1 e) {
// handle Exception1
}
catch(Exception2 e) {
// handle Exception2
}
catch(Exception e) {
// handle other exceptions.
}
}
}

But what if the logic for handling Exception1 and Exception2 is the same? In this case we get a dirty code duplication. Although, there is a simple remedy for that. What we could do, is to catch a base Exception class and then branch appropriately with if-else statement as the below code snippet presents:

public static void testMethod2() {
try {
throwsExceptions();
}
catch(Exception e) {
if(e instanceof Exception1 || e instanceof Exception2) {
// Do the common handling logic for Exception1 and Exception2
}
else {
// Handle other exceptions
}
}
}

So far so good. We don't have code duplication anymore. Just a note: the above examples use Java language but they also apply to C# - we would face the same issue/remedy when coding in it.
Now you may wonder what more can be done. As for C# not much really. In Java though, there is still some room for improvement. In Java 7 there has been introduced a new multiple catch mechanism so that we can catch multiple exceptions in one catch block! The following code sample shows the solution using Java 7:

public static void testMethod3() {
try {
throwsExceptions();
}
catch(Exception1 | Exception2 e) {
// Do the common handling logic for Exception1 and Exception2
}
catch(Exception e) {
// Handle other exceptions.
}
}

Here we can see how exceptions of type Exception1 and Exception2 are handled in one catch block using the '|' operator.
Summing up – a point for Java :)

Saturday, October 1, 2011

Named arguments in C#.

So today is the day. I'm kicking off with a new series of articles in the category C# vs. Java. Let's start with a feature called named arguments. In a nutshell, it let us name arguments that we are passing when invoking some method. When it can be useful? There are a few different scenarios. First of all, it may happen that we have a method that takes many arguments of the same type. It comes as no surprise that they can get mixed easily and normally compiler won't help us as long as the passed variables' types match the ones from the method signature. Another thing is just code readability – it is much easier to go through it when we can see the variable name from the method signature next to the variable that we are passing.

class NamedArgumentsExample
{
public static void AddStock(string companyShortName, int amount, double price)
{
}
static void Main(string[] args)
{
AddStock("MSFT", 100, 150);
AddStock("MSFT", amount: 100, price: 150);
}
}

In the above code we can see 2 method invocations – the first one without using named arguments. At first glance, it may be hard to get what are the values in the AddStock method invocation for. On the other hand, in the 9th line we can see with no problem that the first value is for the amount and the second for the price of a stock that we are adding.
As for Java, there is no such feature. I'm sure you can see, even from a very simple example above that it is useful. Of course, as with everything, one shouldn't overuse it but apply in a reasonable way, in cases where it will really add clarity.
That's it for today! Hope you enjoyed the post and have a happy Sunday!!

Thursday, September 29, 2011

Back in the game!


Yeah, that's right lads – I'm back to the blogging!! I know, it's been a while since the last post, over half a year but believe me – there was lots of things going on – changed a job, moved to a different country, finished my master thesis and stuff like that. Luckily nobody died so no big deal.
But cutting to the chase, now again, you will have an occasion to read about my thrilling and breathtaking adventures in the code.
You may wonder, what you can expect exactly. In my professional career I have switched to C# and so I came up with an idea to create a new category called “Java vs. C#” where I will be writing down my remarks about interesting differences in those languages and also in the platforms and frameworks associated with them. I have used C# for about 5 months so far and spotted already a few really useful features that Java does not have. On the other hand, I haven't noticed anything that Java has but C# does not – here, speaking only about the language itself.
Other than that I will still continue to bring up topics about software engineering in general and things I find worth sharing with you!
So stay tuned – the next post coming up soon!

Saturday, February 5, 2011

A tiny trick thanks to the autoboxing.

Today it will be short and tiny. The whole trick bases on the Java autoboxing feature. Let's say that we want to implement a method that checks whether a string that the passed reference points to, is evil. The first question that may pop up in your mind is when the string is evil? That mostly depends on you, in our example though, we will assume that it happens when it's equal to “666”. But wait, this article is not really about evilness. Let's go back to the way we should implement our method. The first important thing, is to check whether the reference is equal null. After that we can just invoke the equals() method inherited from the Object class and based on its result return true or false. A sample implementation could look like this:

public class StringTest {
static boolean isEvil(String evil) {
if(evil == null) {
return false;
}
return evil.equals("666");
}
}
But if we would like to get some advantage from the autoboxing feature in Java, we can easily get rid of the null check in our method. You probably ask why we can do that. It's simple – the null check is already done in the equals() method that the String class provides so why would we repeat it? To achieve the above, we have to force the “666” to be autoboxed and then invoke the equals() method on the new object against the passed reference. The following code shows the whole solution:

public class StringTest {
static boolean isEvilEnhanced(String evil) {
return "666".equals(evil);
}
}
It's shorter, still easily readable and what's more important, faster! (The autoboxing in the first example has to be done anyway, since the equals method takes a reference to the Object class)

Sunday, January 23, 2011

Parsing large XML files.

Today I will write about parsing XML files from the Java perspective. Recently I faced a task of reading and eliciting some certain data from a bigger than usually XML file – over half a GB. The most desirable approach when it's about parsing XML files is to use a parser that implements a DOM API interface. For those of you who are not familiar with this mechanism – in a nutshell, it's a tree based API which reads the entire document into memory and represents it as a tree of objects, to which we have random access. It makes a work with XML documents very convenient and easy thanks to the fact that we can easily retrieve any interesting node from the tree and read the data that we need. Unfortunately, there is a huge drawback with this solution – it requires lots of memory, depending on the implementation, up to a few times of the xml document's size which in my case, forced me to seek for another approach.
After a while, I came across to StAX, which stands for Streaming API for XML. It is much different API than the DOM. The first important thing – it does not convert the document into a tree. Instead, it treats it as it is – a stream. But that's not everything. The StAX is a pull streaming model which means that it is up to the programmer when he or she wants to start, pause or resume the parsing process.
Fine! I guess that's enough for an introduction. Let's have a look at the following example of parsing an xml file. First of all, here is how the xml file looks like:

<calendar>
<event type = "party">
<where>Club Mojito</where>
<whom>My friends</whom>
</event>
<event type = "meeting">
<where>A building</where>
<whom>Project Manager</whom>
<date>12/09/11</date>
</event>
<event type = "lunch">
<where>Canteen</where>
</event>
</calendar>

And the code that parses the file using StAX:

package stAX;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class StAXExample {
public static void main(String[] args) {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try {
InputStream in = new FileInputStream("ourFile.xml");
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
String currentElement = "";
while(eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if(event.isStartElement()) {
StartElement startElement = event.asStartElement();
currentElement = startElement.getName().toString();
System.out.println("Start element: " + startElement.getName());
@SuppressWarnings("unchecked")
Iterator<Attribute> it1 = startElement.getAttributes();
while(it1.hasNext()) {
Attribute attribute = it1.next();
System.out.println(" Attribute name: " + attribute.getName() + ", value: " + attribute.getValue());
}
}
if(event.isEndElement()) {
currentElement = "";
}
if(event.isCharacters()) {
if(currentElement.equals("whom") && event.isCharacters()) {
System.out.println(event.asCharacters().getData());
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(XMLStreamException xse) {
}
}
}

In lines 17 – 20 we initialize our parser. The most important thing, is to get an implementation of an XMLEventReader interface. This is the top level interface for parsing xml files which gives an access to all methods that we need. In order to get this implementation we need XMLInputFactory and InputStream with the xml file we want to parse.
In the next part of code we can see the usage of an XMLEventReader interface. The methods that we take advantage of are as follows:
hasNext() It checks if there are more events
nextEvent() returns the next event
isStartElement() checks if the event is a start element, which means, for instance, an opening tag
isEndElement() as the previous method, just that it relates to an end element.
IsCharacters() checks if the event is the plain text, which means, the text between opening and closing tags.

Ok, so for now, we know how to get opening and closing tags, as well the content between them but let's say we would like to get the attributes of some tag and their values. In the lines 29-33 I achieve this with an iterator. The interface StartElement has a method getAttributes() that returns an iterator to the attributes which we can cast to the Iterator. After that the Attribute interface has the methods getName() and getValue() which we use to get the name and value of the tag's attributes.
It is that simple. So now on, if you have a large XML file you will know how big boys do handle it ;-).