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

Sunday, December 19, 2010

Call me!


Today you will have a great occasion to call someone you would never expect to call... a thread. We talked already about the concurrency on the blog: Threads part 1: The basics and Threads part 2: functions overview. But the problem with the previous solution to achieve simultaneous computation is the lack of explicit mechanism to retrieve the result from a thread. As luck would have it, since Java 1.5 we have an access to a new interface – Callable. In comparison to Runnable there are a few significant differences:
  • with Callable you can easily return a result of another execution thread.
  • with Callable you can throw checked exceptions.
  • with Callable you have to use a thread executor.
So far so good. Now, to get more familiar with it, let's have a look at some code:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


class Computation implements Callable<Integer> {

@Override
public Integer call() throws Exception {
int result = 0;
for(int i = 0; i < 10000; i++) {
for(int j = 0; j < 100000; j++) {
// Some taught computation
result += (i * j) - (i * j) + 1;
}
}
return result;
}

}

public class CallableExample {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(5);
Future<Integer> f1 = pool.submit(new Computation());
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
try {
System.out.println(f1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
pool.shutdown();
}
}

Ok, there are a few new elements regarding Callable. First of all, if we implement the Callable interface, we have to implement T call() method. This is where the action takes place, it's a method corresponding to the run() method from Runnable interface. And the other important thing – it's the place where we can throw an exception (Exception or any subclass).
When the class implementing Callable interface is ready, we can instantiate it and run through a submit() method of a thread executor what happens in line 27. The submit() method will return some implementation of a Future interface. It represents the thread's computation and provides a few useful methods, among others:
boolean isDone();
which returns true if the task is completed.
T get()
which returns a result of a task of type T, or if the task is not completed yet it waits until it's finished. Actually this could be achieved with a wait() method using a Runnable interface and calling it on the instance of a thread from the main execution thread.

And that's it. I'm sure that the above information and the sample code will let you use the Callable interface in appropriate way.

Wednesday, December 15, 2010

Type erasure in Java.

Probably every Java developer knows what type erasure is. In Oracle tutorial on Type Erasure we can read:

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

The generic types are only for the compile time - after the type checking they are removed and gone for good, for sake of legacy code. Are they really? Let's have a look at the code I just wrote:

import java.lang.reflect.Field;   
import java.lang.reflect.ParameterizedType;   
import java.lang.reflect.Type;   
  
class P1 {}   
class P2 {}   
class P3 {}   
  
class A<T1, T2, T3> { }   
  
public class Gen2 {    

    A<P1, Integer, P3> genTest = new A<P1, Integer, P3>();   
    public static void main(String[] args) throws Exception {      
        ParameterizedType genTestField = (ParameterizedType)Gen2.class.getDeclaredField("genTest").getGenericType();   
        for(Type type : genTestField.getActualTypeArguments() ) {   
            System.out.println(type);   
        }   
    }   


In the above code, we define a generic class A that can be parametrized - in the line 13 we instantiate this class with parameters P1, Integer and P3. And now,
through a reflection of Gen2 class and methods getDeclaredField(String) and getGenericType() we can elicit the parameters used during instantiating generic class A!
The code will print:
class P1
class java.lang.Integer
class P3
So in this way we can get exactly the generic parameters that were used. How this can be accomplished? As I already wrote, through a reflection. When we open a compiled Gen2.class file we can see a section "Signature":
Signature LA<LP1;Ljava/lang/Integer;LP3;>;
which shows the types that we were interested in. So apparently it seems that this information is not completely removed after the compilation time. From the bytecode yes, but in the .class file the information is still available!
In my opinion it's a very interesting and important example especially when we can read in many places that after the compilation we can't get the parameters anymore! Hope it was at least a little bit inspiring and encouraged you to read more on the reflection mechanism.

Saturday, December 11, 2010

String's split() method.


This will be short. Recently I had to use this simple String class method when developing a parser for some pdf documents. Everything was going well until one moment. In the document, among others I had to elicit a range value which was given in the format x..y (for instance, 1..32). After getting the string 1..32 I wanted to use split method to separate the bounds. So in the code it could look like this:


String range = "1..32";
String[] bounds = range.split("..");

But that didn't work! Why? The answer is very simple. The String's split method takes a regex expression as an argument! And in Java "." (a dot) in regex means any character. So that's why the returned array was empty! To solve it we have to use "\\" between any special regex character if we want it to be treated as a string character. So we should change the above code to:


String range = "1..32";
String[] bounds = range.split("\\.\\.");

That's simple! So remember: split's argument = regex expression! Wish all my readers remember this both on the exam and during the work with Java code.