Tuesday, December 22, 2009

The iPhone/iPod As an IT Tool

It's not Christmas, but I've already got my present :) Some days ago, my current employee, gave me an iPod Touch 2G. It was not a simple present, but also a tool to work with a new iPhone application that we're developing.

As many of you, I'm working in a small company. My main job is as developer, but I'm also doing some IT and technical support work, so I was curious to see how could the iPod help me with these tasks.

As I said, I have an iPod, but everything explained here is also applicable to the iPhone. In fact the iPhone is even more useful since you don't need to look for a WIFI connection ;)

Let's start:

A Communication Tool

Here we will see how can we use the iPhone as a communication tool:

  • Mail: Configure your e-mail accounts (check here for the documentation to setup your email accounts)
  • Skype: Even if you have an iPod, you can use Skype to stay in contact with your friends and colleagues. If you also want to talk, you'll need to buy a headphone+microphone kit.
  • Social Networks: Almost all the social networks have an iPhone widget. In my case I installed Facebook, LinkedIn and Twitter (Twitterrific). But you can also find widgets for Xing, MySpaces, ...
An Administrator Tool

Let's see what do we need to have control over our computers and network:
  • Network Ping Lite: It's a simple application that gives you the power of ping, traceroute and telnet commands
  • Mocha VNC: With this tool we can control any computer with a VNC Server installed.
  • iSSH: Another great application. With this one I've all the power of an SSH console, but I can also do remote X connections
  • VPN: Integrated in you iPhone is a cool VPN client, so you are never outside your network.
  • iNet Pro: With this one you can ping, scan ports, scan network, ...

Other Useful Tools

That's the miscellaneous section where I list other tools that I feel are really useful
  • DropBox: Does it even need a presentation?
  • GoodReader: A really good PDF reader
  • AppBox Pro: It's a useful package with different applications.

I'm still investigating what other cool things I can do, but what's your preferred iPhone application?

Sunday, November 8, 2009

How to Properly Comment Code? (Part II)

It took longer than expected to find the time to write the second part, but finally here it's

For some reason, the last month has been full of articles about commenting code, like Is Commenting Your Code Useless?, Code Comments: The Lowest Form of Communication or Comments are a sign of bad code

You're free to visit those sites and see their arguments. I must say that I only agree with the first of them, in fact this article is almost a duplicate of his arguments.

When should I comment my code?

To properly answer this question you need to look at your code and think if your comment is improving in some way the understanding of what you're doing.

// We're done
isDone = true;

Is not really helpful, is it? Your comments must aggregate some value to your code, otherwise are worthless.
Also you must always keep in mind that your code should be clean enough that's self-descriptive. Keeping your code self-descriptive have 2 benefits. The first one is that you'll not need to add comments, the second, and most important, that will make things easier when arrives the time to maintain it  (and believe me, this time will come).

Only in the case that your code is not descriptive enough, you must add a comment. Is that bad? not at all.

My code is self-descriptive, why should I comment it?

Some pieces of code can be quite complex, mainly when you work in real projects. You only need to thing about financial, graphic or simulation software. They require tons of complex coding to achieve their objectives and it's usually quite hard to get the mentioned self-descriptive code.

Even when your code can be really clear, the purpose of this code may be not. I'm going to copy a good example from Jani

//Calculate if two circles intersect
$xd = $c2->x - $c1->x;
$yd = $c2->y - $c1->y;
$diameter = $c1->radius + $c2->radius;
$intersection = ($xd*$xd + $yd*$yd) < ($diameter * $diameter);


Simply reading this code would be a bit hard to known what's happening. The variable names could help, but the comment is giving us the final information

Monday, September 28, 2009

How to Properly Comment Code? (Part I)

If you do a search in Google for "code comment" you'll find 216,000 hits and if you do the search for "comment code" you'll find 505,000 hits. Then, why is so difficult to find properly commented code?

The first point that I want to clarify is that I'm talking about "commenting code" not "documenting code" which is slightly different.

The code documentation is used to generate the API documentation, to known which methods are available, what arguments are accepted and what's the result of the call. The documentation is destined to be used and understood by the users of your code (like users of you code library and/or classes).

On the other hand, the code comments are helpful to understand the internals of your methods. Usually these comments are only read by your colleagues.

Now that the difference is clear we can continue.

As developers we usually ignore or forget the "code comments", but we always try to write some information (even minimum) when is related with the "code documentation", we even have tools to autogenerate the documentation or whine if it's not correct.

Why do we keep forgetting and ignoring the "code comments"? From my point of view there are 2 main reasons:

"It's not needed"

That's what we think when we're writing new code. At the moment the code is always so clear and beautiful that there's no need to document it. Why should we spend time? Who can be so dummy that needs extra info about our code?

Well the dummy guy that will need this comment is usually ourselves. When we come back to this block of code in the future, things will not look so clear and obvious.

"Laziness"

That's the other major reason. The typical "I'm really busy right now, I'll do it later". You known what? If you leave it for later, is almost sure that never will happen.

The lack of proper comments in our code is always going to come back in the future and bite us.

The next day we'll see some tips about how to properly comment our code.

See you.

Friday, September 18, 2009

StackOverflow and the Lazy Developers

Hi again,

During the last days I've been looking deeply into StackOverflow and I must confess that's a great source of information and knowledge. But I've also found something that worries me a bit, lazy developers.

Most of the questions in StackOverflow are really valid. Complex questions about special cases, people looking for the help of a more experience developer or even questions that can be due to a lack of knowledge in an specific subject or a part of a language or API. But I've also found a big number of questions that can only be caused by pure laziness.

Why am I saying that? Because simply putting the question keywords in google you can find the answer. I've even seen cases where the first result in Google points to the valid answer (sometimes even inside StackOverflow).

Why does it worry me? Because I've always believed that a software developer must be capable of reading documentation, creating test cases and find solutions by himself (doing trial and error if needed). If we just limit ourselves to ask the most simple questions, means that we don't care enough about what we're doing. If we just ask about stuff that can be easily in our language/API/SDK documentation, I don't want to think what we'll do with more complex problems.

This behaviors will produce tons and tons of copy&pasted code in our programs and will create a generation of developers unable to think by themselves, solve the most easy problems or understand the real consequences of the pieces of code they write.

See you soon.

Monday, September 7, 2009

Howto Install SwingX in NetBeans 6.7

Today I feel like doing some graphic stuff in my pet application. Even when Swing is really nice, I usually miss a lot of more cool effects. Just thinking in all the needed code to create an usable JTable gives me a headache.

So I've decided to use SwingX. For those of you that doesn't know about SwingX, please check their website, but as a resume I will simple say that are a collections of advanced Swing components and that some of them will become part of the default Swing set in JDK 7.

Let's start the party:

Download SwingX to you computer

You can do it from here: SwingX Download. Now I would recommend you to unpack it.

Add SwingX Library to NetBeans
  1. In NetBeans go to Tools -> Library Manager and click the "New Library..." button
  2. Type a name: SwingX
  3. Now in the ClassPath tab you need to add the jar files you will find the /dist
  4. (Optional) You can also add the SwingX sources and documentation (The SwingX 1.0 javadoc zip file is incomplete, but I used the "Hudson Continuous Build Javadoc" without problems)
Add SwingX to your Project
  1. Right click on your project and choose "Properties"
  2. Select the "Libraries" section in the left tree
  3. Now click in "Add Libraries..." in the right panel
  4. Select the Library you created in the previous step ("SwingX" if you followed my suggestion)
  5. Finally hit the "Add Library" button
Add SwingX Components to the Palette
  1. Create or open a GUI class form. You'll then see the Palette on the right side (by default)
  2. Right click on the Palette and choose "Palette Manager..."
  3. Click "New Category..." and choose a name. I would suggest to type SwingX again.
  4. Select the newly created category and choose "Add from Library..."
  5. Now choose all the components you want to have available (use Ctrl+A to select all)
  6. Finally choose again the "SwingX" category
  7. Click "Finish"
We're done. Now you can use the SwingX components in your NetBeans Projects.

Happy coding

Thursday, September 3, 2009

The Best Way of Working with Zip Files in Java

Finally I found the best way of working with zip files in Java :)

In one of my hobby projects I need to work intensively with compressed files (mainly zip files). My first approach was to use the java.util.zip package, but was too slow. So I started looking for other options.

My second approach was to create a wrapper for the 7zip executable (so I could have cross-platform support). This approach was much better, from a performance point of view, but to retrieve any info I needed to parse console output and solve a lot of problems with the java.lang.Runtime class.

Today I've finally found the best solution .... but before some really simple comparations:

java.util.zipHome Made
7zip.exe Wrapper
"Best Solution"
Extract All 1220341094094
Get Number of Elements4000410978
  • All the measurements are in milliseconds
  • The test was done with a 104MB zip file containing 110 jpg files.
  • The "Get Number of Elements" with the "Home made Wrapper" is also done extracting everything and counting the number of files (I'm sorry I was a bit lazy here)
I don't think that I need to add too much to these numbers. The integrated Java zip package is nice, but painfully slow.

And finally is time to show the "Best Solution" and an example comparing it with the Java zip code ;)

The winner is "7-Zip-JBinding" and has they explain in their website:
7-Zip-JBinding is a java wrapper for 7-Zip C++ library. It allows extraction of many archive formats using a very fast native library directly from java through JNI.

Get the Number of files using java.util.zip
    static public int getSize(File file) {
ZipFile zf = null;
int total = -1;

try {
zf = new ZipFile(file);
total = 0;
for (Enumeration e = zf.entries(); e.hasMoreElements();) {
e.nextElement();
total++;
}
zf.close();
} catch (ZipException ex) {
Logger.getLogger(Zip.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Zip.class.getName()).log(Level.SEVERE, null, ex);
}

return total;
}

And the same with 7-Zip-JBinding

public int getSize (File file) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
int total = -1;
try {
randomAccessFile = new RandomAccessFile(file.getAbsolutePath(), "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));

total = inArchive.getNumberOfItems();

} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}

return total;
}

As you can see the code is quite similar, but the performance is quite different.

See you.

Tuesday, September 1, 2009

Why do we blog? What do we learn?

Blogging takes time and only in rare occasions the bloggers make any money, so why do we do it? Jeff Atwood has a good theory. But I like to think that it is more than an "egomaniac action".

Blogging is, for sure, a good way of promoting yourself. In our blogs we put our opinions and also part of our work. A blog is a good way of showing future employers which kind of person you are.

A blog is also a way of networking, a way of sharing your knowledge, but also a way of learning from other people comments.

And the same can be said for the blog readers. I invest daily near 1 hour reading blogs and news. It is a great way of learning from other developers and stay updated.

Our profession/hobby is always evolving really fast, and blogging is, so far, the best way I have found to be in the loop.

See you soon.

Wednesday, August 26, 2009

JUnit: How to test your private methods

Some weeks ago I was creating some unit tests for a hobby project I'm working with. But I found myself stuck trying to test some private methods.

My first though was "Should I even need to test those methods?" I invested some time looking for alternatives, but those methods must be private. What could I do?

One option was to modify those methods to be public, anyway this is a hobby project and I know I'm not going to call them from outside. But since the main reason of this project is to learn I though I would best invest the needed time to find the correct solution.

Being a fan of the Java reflection API, I decided to investigate this approach. This is the result:

/**
* Convenient method to execute private methods from other classes.
* @param test Instance of the class we want to test
* @param methodName Name of the method we want to test
* @param params Arguments we want to pass to the method
* @return Object with the result of the executed method
* @throws Exception
*/
private Object invokePrivateMethod (Object test, String methodName, Object params[]) throws Exception {
Object ret = null;

final Method[] methods =
test.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
if (methods[i].getName().equals(methodName)) {
methods[i].setAccessible(true);
ret = methods[i].invoke(test, params);
break;
}
}

return ret;
}
As you can see the code is simply doing the next steps:
  1. Retrieve an array of declared methods
  2. Loop the array looking for the method we want to test
  3. Once found, set the method as public
  4. Execute the method and return the result
And we want to use it, we only need to do something like:
MyClass instance = new MyClass();
String expResult = "Expected Result";
Object[] params = {"A String Value", "Another Value"};
String result = (String) this.invokePrivateMethod(instance, "myPrivateName", params);
assertEquals(expResult, result);
This is the best I could find. Fair enough but, do you know of a better or more elegant solution?

See you soon.

Monday, August 24, 2009

Can I do 'this' with my favorite language?

When we need to start a new project we use our favorite language by default. Is it wrong? The short answer is "No, it's not wrong". But the correct answer is a bit more complex.

Before starting a new project we should answer some basic questions.
  • Is our project a desktop or a web application?
  • Do we need a user interface?
  • Should it be cross-platform?
  • Do you need to integrate with some external service/platform?
Answer these points and now think for a couple of minutes if your favorite language is good enough.

Almost all the "
General Purpose Languages" (and here) are good enough to do any kind of application, but there are cases where it is much better to use some "Domain Specific Language" or, at least, a different language that is better suited to do the specific kind of application we want to do.

Let's see some extreme examples:
  • If I need to create a program to automatize my connection to different SSH server, I could do it in Java, but that would be overkill, and too complex. A simple BASH script will be faster and easier.
  • If I'm a PHP developer and I need to create some simple desktop application. What should be my choice? Sure I can compile PHP code into an exe file, but probably I would get a much better and faster solution using Java, C# (or any other .NET language) or even Python.
  • As I said, these are radical examples, but I think that shows my point. Don't be lazy when choosing the language you need. Even when a lot of languages would be OK to solve the problem, maybe your choice is not the best one.
See you soon.

Sunday, August 23, 2009

Keep performance in mind

Almost anywhere you will find that your first step when coding is making it to work and only later worry about performance. I only half agree.

It's true that your code must work, otherwise you'll have nothing. But while you're coding you must always keep in mind the performance of this code. I don't mean that you should invest extra time trying to make your code faster, you just need to keep in mind some general recommendations about performance that will help you.

For Java developers, this is a good checklist, but most of them are valid for almost any language:
  1. Do not recalculate constants inside a loop.
  2. Reduce the number of network operations by returning complete results rather than smaller intermediate results.
  3. Reduce the distance between objects during operation. It is better to perform complex operations locally.
  4. Avoid object creation and destruction except as necessary. Reuse existing objects.
  5. Use open source frameworks which are established and tested.
Find a list of performance check points for your favorite language and keep it in mind.

See you soon.

Thursday, August 20, 2009

Don't understimate the need of tools

Hi again,

When we choose a language/framework/platform to start a new project we usually think that we'll have all the tools that we need. False. Doesn't matter what we do, we'll always need a new tool that doesn't exist in the market to solve some problem.

Ten years ago I was working in a company using C/C++ in a cross-platform product (Windows, Solaris and Linux). I though that I would find absolutely anything I would need "I'm working with C, everything is available" And I was almost right, I found almost anything I needed, but almost none of them were cross-platform. At the end of the day I needed to create my own cross-platform API.

Six years ago I worked for another company where we worked mainly with Java. Then I though "Great, Java is cross-platform I will have no problems" you know what? I was wrong. We were mainly working with code stored in an Oracle Database Server, together with thousand of string literals for the User Interface in multiple languages (Spanish, English, French, German, ....) And we also wanted to move from Java 1.3 to Java 1.4 (I know, but was an enterprise system) On top of that there was no way of compiling everything, since the code of every single operation was stored in the Database, so no real source files were available.

So at the end of the day I needed to create a data mining tool to spell check all the strings from the Database, also was capable of retrieving and compile the code of every operation to check if it could compile properly and detect deprecated code (so I could simulate the migration to Java 1.4) and also look for other potential problems merging my tool with FindBugs and CheckStyle.

Four years ago I started to work for my actual company. There I was expecting anything. The main language was Tcl/Tk. I was wrong again, now was a matter of creating almost any tool that I would need, since Tcl is one of the less used languages in the world and I'm working in what's probably the biggest application wrote with it.

What have I learned from all these cases? Doesn't matter which technology do you use, at the end of the day you'll need to write some tools to solve unexpected problems/situations.

And don't be lazy about it. These tailored tools will always help you, so don't leave them for later.

See you soon.

Monday, August 17, 2009

Is it possible to finish a hobby project?

I've seen this scenario tons of times, both in colleagues and myself.

When I am working in a real project (paid for) I have a full project roadmap, I set deadlines and I work focused in the project. But when I start some hobby project it's never finished, I'm never satisfied by its quality, why?

So far I have detected the next problems:
  • I focus only in the most appealing features to me, and not in getting something working
  • I can rarely invest quality time or work more than a few hours in the project
  • There's no external pressure
  • I use my hobby projects to experiment with new technologies, so sometimes I write the same program with different languages and/or libraries.
What should I be doing?
  • I should define a minimum set of features and focus on them before jumping to more fancy and funny stuff
  • I should work on my projects only when I can really invest time (vacations, weekends)
  • Put deadlines and give me a prize if I make it
  • Experiments are great and needed, but I should do them one by one and not try to test multiple things at the same time
What do you think? What are your tips?

See you soon.

Sunday, August 16, 2009

Good Support is Important

As developers we usually think that our code is the most important part of the product. We focus in getting the best possible piece of code, fast and bug free. Sadly there's no such a thing like "bug free" software (in fact there's no such a thing like "problem free product". When shit happens then is the turn of our support colleges to solve the problem.

A good support department will make the customer forget about the real problem and be happy for the great help he received. And that's really important if you want to keep your clients/customers happy and loyal to your product.

I'm lucky enough to work in a company where the support department is really friendly and our customers love it. Doesn't matter which kind of problem do they have (bug, feature request or simply a question about how to use our software for an specific task) our support department is always there to help and find some solution or workaround.

But let me talk about a especific issue I had some days ago with my wife's laptop.

In January I bought for her a Dell Studio 17 laptop. Nice computer, fast, big screen. She loved it. But just 2 weeks ago the screen started doing funny stuff. I did some checks and finally concluded that the problem was with the monitor, so I was decided to complain to Dell support about the shitty monitor that broke down in just 8 month.

I phoned, and as soon as I explained my problem, the support guy politely asked me to run some tests through the bios. After that he told me that they would send me home a tech guy within the next 5 working days. The next day I got a call from Dell to coordinate when it would be for me the best time for them to come, so we schedule it for Saturday (2 days later), between 9:00 and 13:00. I was sure I was going to waste the whole Saturday morning waiting for the guy.

Saturday 9:30 I got a phone call from the tech guy to confirm that I was at home. He arrived 30 minutes later with a brand new monitor. Unplugged the damaged one, connected the new one and ask me to check if everything was working properly. Everything was fine :) Even better 3 days later I got another call from Dell to check if everything was still working fine and if I was happy with the tech guy that came to do the fix.

So basically I got a damaged monitor replaced by a new one in less than 4 days. The tech guy came to my home and I didn't pay a cent. And then I realized that my next laptop is also going to be a Dell, why? Because shit happens, any piece of any machine of any manufacturer can break down. But Dell can fix it in just a few days and with a friendly and helpful group of people.

That's why I think that a good support department is important. Because they can change a potential angry customer into a happy and loyal one.

See you soon.

Hello World

Saying "Hello World!" is probably the best way of starting a new blog about programing. But why a new one? We can find thousands of blogs out there, but I have the impression there's a gap that needs to be filled.

My name is Carlos and nowadays I live in Majorca, Spain, but I've lived also in Barcelona and Hanover (Germany). I've worked as Software Engineer the last ten years, and this is the first time I write a blog.

Working in different countries, cities and companies gives an interesting overview about what's important and what's not (or at least what I think it's important). For years I've been reading blogs finding, from time to time, really good comments and appreciations, but rarely I've found a blog where I can identify myself.

In this blog I'll try to share my point of view about things, without being too technical. And I really hope that you'll find it interesting. I'm also hoping that other people is going to collaborate and comment here adding their comments, experiences and ideas.

I really hope you will like the contents of this blog.

See you soon