Wednesday, May 28, 2008

Unit testing exceptions

When unit testing exceptions, be sure to test for the exceptions that you expect.

I spent nearly an hour rewriting tests to test for what they said they tested.

Here's an example of a bad test.

Exception ex;
// configure mocks
try {
// call test
fail();
} catch(Exception e) {
ex = e;
}
assertNotNull(ex);


Any and all errors that are thrown, including "the mocks are not configured properly" is considered a successful test pass, instead use.



Exception ex;
// configure mocks
try {
// call test
fail();
} catch(Exception e) {
ex = e;
}
assertEquals("the error message I expect.", ex.getMessage() );

Tuesday, May 27, 2008

JRuby pains

I was dickering with JRuby for three days trying to get it to run, I kept getting all kinds of strange errors.

I found out that calling JRuby is actually calling a batch file that deals with compiling things to run as java, so I turned echo on in it and the batch files that it calls. I started tracing the route through looking for the problem.

My environment variables Path, jruby_home, and Java_home were all 3 correct. From a command prompt I could type "java-version" and get 1.6.0_05 and yet, it was giving me a strange error. The only thing I found online for that error was that it was using the wrong version of the runtime, but the runtime and java were fine. Or so I believed.

I went to a different machine and tried installing the Bin version of JRuby1.1.1. It worked. I knew that nothing could be wrong, even inadvertently with the bin code on the web since it worked perfectly on the first attempt on another computer.

Back to the first computer I went. I don't know what brought it on, but for some reason I decided to check that the version of java in java_home matched the version in my path. It didn't. Java_home was using 1.4.2. I updated the environment variable to point to the correct version and everything worked.

If you are having strange errors and your computer has multiple versions of Java installed, you may want to verify that you have the right versions in your environment variables.

Monday, May 26, 2008

What programming languages should you learn?

"a language that doesn't affect the way you think about programming is not worth knowing".
-- Alan Perlis

Saturday, May 24, 2008

Trying the Uniball pen.

I'm trying out a new pen. I've never been real specific about what I write with. I'm using the one with .7mm thickness. Generally I prefer thinner lines, but this one seems to have very concise lines even at this thickness.

The uniball pen is very light and has a similar feel to a pencil. This may be a turn off for others, but for me, I love and prefer writing with pencil. I like the feel of the pencil and the friction it has on the paper, generally I find a pen too smooth.

There are a few downsides to the pencil. It smudges and will continue to smudge even after weeks. It's hard to read it in some lighting conditions, especially flourescent lighting. Since I'm switching to CFLs even at home, it's becoming harder to read pencil. That's why I'm looking for a pen that I am comfortable writing with.

The Uniball pen is very light. It's lighter than just about any other pen I've used, and lighter than most of the pencils I've used, even the mechanical ones.

Friday, May 23, 2008

How to use new technology at work

Don't ask.

That appears to be the answer that's most common. Find technology that's free, so it doesn't cost the company money, bring it in house, set it up without the real powers that be knowing about it, and use it. After it's proven useful, then present it. I've been listening to the Ruby on Rails podcasts from 2006 (I'm just getting into them), and every one of them says that they got Ruby into the office by just doing it and not asking. If they couldn't have flown under the radar they wouldn't have made it.

I've heard it said that it's better to ask forgiveness than it is permission.

What all of this really says though, is that generally corporations are against helping themselves. They go out of their way to prevent new technology and solutions that could help them advance. Look around at your company, is it stuck in the status quo? Does it still do what it did 3, 4, 5 years ago? Even using the same technology to solve those problems? You may be at a company that's in it's own way. Think about that when you start looking for things to do to fill your free time, you may need to start looking at the next language. Figure out what will work best for you, but don't let your skills get stale, just because you are at a company that still does what it used to do.

And as you learn these new technologies, bring them in to work. It's easier to ask forgiveness than permission, and your company probably needs a good internal push anyway.

Thursday, May 22, 2008

Log4j tip

A few log4j tips from mistakes I've made, or things I've struggled with recently.

  1. When using logging to send emails, send to an email group, that way if members that receive the email change, the group can be updated without having to touch the program.
  2. Be sure logging changes for live from test, you probably don't want to log debugging in live. Do it manually, use Ant scripts, whatever, but be sure that logging is set for live when deploying to live.
  3. When writing files to your local box (windows) where the server is running, have the log file path be c:\ Any more complicated of a path may not exist on another developers machine when they pull code out of CVS (or Subversion)
  4. Name our log files with [ProjectName]_log4j.log This should ensure that the file is unique.
Not sure if it's a must, but when I was making changes to log4j, they did not appear until I restarted the server.

Wednesday, May 21, 2008

Method naming conventions

This is just another rehash of what you've probably read many other places.

Start the method with a verb and end it with a noun. You want to make the method name be like what it does.

Bad method names.
verify
get

Good method names
verifyPhoneNumber
getAccount

I ran across a method today that threw me. An object was declared off of my screen and set to
employee = getEmployee()

I was looking for a property of the employee object so I went digging for it, however, the object appeared to be a string. I went looking and yep, it was.

String employee; was declared off the screen above and the method returned the EmployeeName. Inside the getEmployee method it actually retrieved an employee object then returned just the name.

A few refactors later and everything was all better.

Monday, May 19, 2008

Funny Typo

I was typing an email today and typed "toolbra". Ha, Toolbra.

Are Team Agreements Useful?

Jim Brosseau has an article at InformIT titled "Testing That Team Agreement" It goes into the difficulties of setting up a team agreement.

I've read about team agreements:
Each team is required to write up a team agreement form. The purpose of this agreement is to identify, agree upon, and formalize each team member’s individual responsibilities and accountabilities. The minimum length for this agreement is two pages.


I don't like team agreements, because I've never seen one that was anything other than, be nice to each other. How long does the meeting have to be and how many ways do we have to say it before everyone is on the same page with "Be nice to each other". Everyone gets a say, I won't interrupt, I won't personally attack someone, I won't call someone's idea stupid unless it is, I'll be happy, smile, and participate, I'll dance and laugh and sing, oh, and I'll do this all for half price during these meetings because we have a Team Agreement.

Unless you are on a team that has some specific rules that need to be followed in order to further the project, where the rules are not so much team rules, but project management rules, then everything will continue to come down to Be Nice to each other.

I have no use for an agreement that tells me what common sense already tells me, it just makes me want to call the organizer of such an agreement stupid, which would be against the agreement, if they weren't actually being stupid and wasting time.

Here's my proposal. A team has expectations. This is put on the team by the business, it's not negotiable. "You are expected to work as a team, communicate with each other, help each other, stand up for each other, and get along amicably at work. You will communicate your status and let management know when things are behind and why." If you cannot do these things, then you will not be a part of this team. Your agreement is your acceptance of your paycheck. The point at which you no longer agree, you are free to stop accepting your paycheck.

The team agreement now does not ever need to be modified, there is no need for a meeting about what it is, it's be nice to each other. Now please, don't waste any time on the agreement, and get down to accomplishing the goals before you.

Friday, May 16, 2008

SCJP Day 5 Training

The last day of training. A day of goodbyes, and heading home. I've been spoiled by making such good friends from other training classes, it's strange that this one will probably turn into just a class that I attended with some people.

We continued with the Swing application. However, since it's not supposed to be on the exam, I think we spent too much time on it. We spent most of the morning finishing the front end of a chat application so we could learn networking and threading. The networking discussion was very rudimentary. We basically just typed what we needed to open the specific socket. We had decent coverage of threads with how to work with shared data and synchronizing, but I think we could have done gotten more information about wait and yield.

I would have preferred that the last day have started us with a project to load that had the GUI finished and we could have focused more on the threads and networking. These were probably the worst examples of the weak.

I learned more about Swing than I thought I probably ever would, and I find myself asking, what they were thinking with the different layout managers. I've built many VB6 and C# applications that look really good without having any of those layout managers, or their problems.

The most informative thing we learned on the last day is the state pattern. I'm glad Martin also teaches the patterns class, he was able to incorporate a few patterns into the class. Since a few of my classmates were novices I don't know that they got a lot from the design patterns, but it was useful to see them incorporated into the class.

Thursday, May 15, 2008

SCJP Training Day 4

Another day another day.

Day 4 of training was new for me. We covered additional File IO and Stream IO, we covered the Scanner class. The Scanner class was interesting, but probably not something I will use. It does seem to have a good use as a quick tool for a delimited file when you need to deal with every field, however if you have a file with a lot of fields and you only need a few of them, reading the data as a row and parsing it will probably be easier.

Next we went over some Swing. GUIs are not on the certification any more, but we're writing a quick and dirty IM Client to set ourselves up for the networking code that we'll learn tomorrow. Having come from VB and C# for my GUIs I'm surprised at the number of different layout managers that there are. None of those are available in .Net and I haven't really seen the need for them yet. So far, it just looks like creating a Swing application is more of a pain, and a lot more hassle than using .Net, other than the fact that it's more portable.

We're ahead of schedule in class, so we've covered a little bit with patterns as well. Today we talked about the Singleton Patter and the Observer pattern.

Knowig the agenda for tomorrow and what I've learned this week, I'm disappointed. If I had known better what the class was going to cover, I would have saved the money and just bought the book. If you are good at picking up your information from books, then read the SCJP book instead of paying for the SUN certification, it covers everything in at least as much detail as the class will.

There are 3 benefits of the class.
1. It's training, getting away from work for a while every now and then is good, especially when you make new connections.
2. Paying for the class comes with additional online courses that have more material in them, covers the cost of taking the exam, and has a practice exam.
3. It's given me something to blog about.

Wednesday, May 14, 2008

SCJP Training Day 3

Another day of training. By the end of the day we finally have gotten to topics that I do not do all the time already, so I am now starting to learn new things. I wish I could get the past two days back from training, but without them I would not have made the new connections that I have.

It's interesting talking history with the teacher. Being from England originally, he seems to be more of a history buff than many Americans. I missed how the conversation started, but he was talking about Issac Newton Brown who was in charge of the USS Arkansas and faced insane odds in the Civil war, but won. There was a quote. The USS Arkansas was the only Rebel ship in the battle so he said, "Any where I shot I wasn't worried about hitting a friendly ship". It's probably paraphrased, but it's a good outlook on overwhelming odds.

I have stayed ahead on the labs, even now that I'm learning new things I'm a full lab ahead of the class. It gives me time to work on more detailed things with the lab and play with things that are not specifically being mentioned.

Today we covered Interfaces, Abstract Classes, Creating and throwing our own exceptions, handling exceptions, the difference in Checked and unchecked exceptions, Collections, Maps, sets, the new Generics for collections, Serializable. And some File IO coverage.

While discussing the Generics, there was a small communication issue with the terminology, you have to type
List myList = new List();

This is generally spoken as "List Angle brackets String angle Bracket myList ..." At least in all situations that I've been in previously.

Professor Littler though said "List chevron..." and nobody else in class got it. I knew what the Chevron was and it is the right term for the <, thank you StarGate. It was interesting enough that several other students went out and looked it up. It's cool that this class is teaching more than the Java language. US History, English, what's next?

Lunch and dinner were both spent in some deep conversations with one of my classmates, not all of the conversation was code based, but it was all very interesting.

Tuesday, May 13, 2008

SCJP Training day 2

Today was more of the same. The class speed has started picking up. We are going through things faster and covering more interesting topics. Yesterday it felt like everyone was asleep compared to today. The class was involved in a lot more side discussions, which add a lot to classes.

Some of today's discussions were about the John Adams series on HBO. Rugby. Soccer. How hard it is for a common man to succeed in England because of their aristocratic history. Australia and Georgia as penal colonies. How some very famous people are not actually from the countries they are associated with such as Hitler, Churchill, Stalin, and Ben Franklin.

The labs haven't been too hard, I've been able to fly through them. I've been able to play on the internet during that time. I finished the Hands on Ruby tutorial. It's been odd the number of things that don't work in Mozilla on the computer in the lab.

I've made good use of my breaks and taken walks through the building and up and down the stairs instead of using the elevator.

In class today we covered Arrays, Classes, inheritance (interfaces are tomorrow), static, final, imports, Static imports, abstract classes.

I seem to be the only one in the room that's done anything in the way of Object Oriented programming, none of the others have used interfaces or inheritance at all. It's been fun though because I've gotten the chance to explain the benefits of it.

Clint, one of the other guys in the class was a roommate with a guy I work with. He's a newbie to Java, but he's really curious, so he and I talk a lot during breaks and lab time.

Monday, May 12, 2008

iTunes killed my internet connection

Tonight I had plans to be online, listen to podcasts, read a bunch of blog posts and web articles that I had been holding off from because of their size. Everything was going well until about 8:30 when the network connection dropped.

After 30 minutes of looking into all local settings and rebooting my laptop, I called the tech support for the hotel. Apparently I had been blocked for "Excessive Bandwidth" usage. The very strongly accented gentlemen told me I was watching a movie, I was not, I was writing a blog post.

During the 20+ minute tech support call I realized that iTunes downloads podcasts automatically. The Learning Rails podcasts have changed to video casts, which are much larger. Lo and behold, they have a new screen cast that has not been downloaded.

Before the connection came back online I changed my setting to not automatically download these, but it bothers me that I cannot download these even at some kind of throttled speed. If I'm OK with downloading a large amount of data, can't they just let me? I don't want to take down anyone else, I just want to be able to listen to the podcasts that are out there.

SCJP Training day 1

I was a little disappointed today in training. Day 1 We started with Introductions and what everyone knows. It appears that I'm the most experienced Java developer in the room. Unfortunately that means the class will go slower than I expected. I will learn some good features of Java and the agenda for Thursday and Friday look very promising, however I think I'll have to suffer through Tuesday and Wednesday to get there.

Here's a few notes from my day of class.

The teacher started the day with: "Code Monkeys is what this course is aimed at. There's no analyses, no UML, and it's not for a beginner programmer." I loved that he brought up code monkeys. Of course listening to his talk on the process and who this class is for, it sounded like the class was designed for a very large organization that had code monkeys. I'm not one of them. I fill the role of every layer that he talked about.

The teacher is SCJP certified, but not up to date. He worked for Sun for years. He's from England, but is now a US citizen. He still has the English accent. I haven't had any trouble understanding him, but he has some turns of the phrase that are very English. Instead of long underwear he called them wooly drawers (while discussing the use of &&) he talked about getting a 99 from an ice cream truck (apparently some kind of ice cream cone with a candy bar in it).

I ended up with 7 pages of notes from class today, but almost none of the notes were about the things being taught they were random thoughts and observations about the other people in the room.

The slow start to the class was at least interrupted by window cleaners dangling from ropes and pounding away on the windows. But by 10 AM they were gone.

The class is taught completely on Sun hardware. It's a Sun desktop with a Sun branded keyboard, mouse, and 17" CRT monitor. I miss my LCD monitor. I don't like the keyboard. The control key is only on the left, and I use my right hand more often than my left when pressing control, even if I'm not supposed to.

We are using NetBeans to write the Java code. And using the Common Desktop Environment (CDE). I have never seen either of these before so I had to play around with both of them for a bit to get started this morning. I like the 4 desktops in the CDE, it reminds me of what I played with on Linux machines in the past. Although finding applications seems to be impossible. To run NetBeans I expected to find an icon in some place for it, but the teacher had us type NetBeans at a command prompt to open it. Closing the command prompt also killed NetBeans, so I'm forced to leave open a terminal window that I'm not using for anything else.

The labs are ok. They have each had 3 levels, Level 1 is for the advanced developer and gives a description of what you need to do to accomplish the lab, level 3 is every character you need to type, Level 2 is in the middle. I have been successful accomplishing all the labs with level 1 so far.

I'm constantly amazed at the number of programing examples that use the number 42. Does everyone who writes a programming book or training think that they have some kind of inside joke with this? Hasn't everyone already read "The Hithchiker's Guide to the Galaxy"? If you haven't you should, at least the first book, I have never laughed out loud more when reading a book.

Not that I need a moleskin, but with the amount of notes that I took today, and the fact that the wire binding in the center of the book is annoying me, I'm considering looking into it. I have to find a Barnes & Noble or a Borders so I can check them out. The hardest part about getting it will be bringing it to work and defending having it after having given my boss such a hard time about carrying his diary (moleskin) with him constantly. At least my boss knows we were just kidding with him and giving him a hard time, I never thought he was carrying a diary.

Martin (the teacher) said that we will be writing tests for the code that we are working on. So far the tests have just been the "main" function running and writing output to the console. The correct output is in the lab book and I have to visually compare. I would expect that we get into using asserts, which are built into Java now, or we would include JUnit and start using it as our test framework, but for now, it's a very poor test system and nothing at all like XP.

Thursday, May 08, 2008

One record on two lines.

A real-life work problem cropped up the other day. One that needed a quick hack solution to fix the problem. We had a fixed length file, but all the records were broken between two lines.

The file load was going to be done with an SSIS package in SQL Server, but it doesn't nicely handle two line records. We had to combine the two rows into one.

One of the developers did this quickly in VB.Net 2005 because that's what he knows, but it got me thinking. How else could I solve this? What other language do I already know that I could use to fix this problem?

Ruby, Perl, Java, VB6, Can I do it with a macro in Ultra Edit?

Here's several solutions to the same problem. Read 2 lines, write 1, you can also think about it as, remove every other newline character.

VB.Net 2005
Imports System.IO

Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rdr As New StreamReader("C:\readfile.txt")
Dim wtr As New StreamWriter("C:\writefile.txt")
Dim IStr2 As String
Dim Istr3 As String

IStr1 = rdr.ReadLine

Do While Not IStr1 Is Nothing
IStr2 = rdr.ReadLine
Istr3 = String.Concat(IStr1, IStr2)
Istr3.Replace(Chr(10), "")
Istr3.Replace(Chr(13), "")
wtr.Write(Istr3)
IStr1 = rdr.ReadLine
Loop

rdr.Close()
wtr.Close()
End Sub
End Class


This works, other than the initial trouble of having to tell .NET that I actually wanted the program to have access to the file. That was a problem that it took me about 30 minutes to overcome.

Ruby
counter = 1
outfile = File.open('c:\writefile.txt', 'w')
open('c:\readfile.txt') do |readfile|
readfile.each do |line|
outfile.write line.chomp
# only add the newline for every other line, Don't add it on the last line in the file.
outfile.write "\n" if( counter % 2 == 0 && line != line.chomp)
counter += 1
end
end

outfile.close

I spent about 15 minutes writing the Ruby code for this, mostly because I felt like there should be a cleaner way to solve the problem. I had been using a fairly ugly check to either write the entire line or write the line chomped (without the newline). I decided to always write the line chomped and add my own newline when it was needed. It's the same number of lines with less checks and it looks cleaner.


Perl Version 5.0
open(INPUTFILE, "c:\\readfile.txt") || die "system can't open file for reading";
open(OUPUTFILE, ">c:\\outfile.txt") || die "system can't open file for writing";

my $count = 1;
while() { # reads a line into the default variable $_
if( $count % 2 ==1 ) {
chomp $_; # only chomp the odd number lines
}
print OUPUTFILE; # Writes the value from $_ to the OUTPUTFILE
$count++;
}
close(INPUTFILE);
close(OUPUTFILE);


I don't need enough hard core Perl functionality to stay up to date on the most recent version. However, I like to tweak files occasionally in Perl, just to try and keep it fresh enough in my mind that I could use it for something if I had to.


Ultra Edit.
Open the file.
Put the cursor in the first row.
Start Recording a macro. Perform the actions.
{end} {del} {down arrow}
Stop recording the macro

Play the macro repeating until end of file.

I can perform this operation with the macro faster in Ultra Edit than I could write even the simple programs that were written above. It's not always the best solution, but it helps to know your tools. Sometimes, knowing the strengths of your own tools can save you the hassle of writing something. For a one time operation this is acceptable, it's the things that need repeated that this doesn't work well for.

Java

import java.io.*;

public class converter {

public static void main(String[] args) {
try
{
PrintStream p = new PrintStream( new FileOutputStream("myfile.txt") );

FileInputStream fstream = new FileInputStream("c:\\readfile.txt");
BufferedReader d = new BufferedReader(new InputStreamReader(fstream));

String s = null;
long l = 1;
while ( (s = d.readLine()) != null ) {
if( l % 2 == 1 && l!= 1)
p.print("\n");
p.print( s.replace('\n', ' ') );
l++;
}

d.close();
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}


The Java method is a little longer, but works just as well.

This was a fun exercise. I love solving a problem and actually thinking about the problem. Different languages have different strengths that they bring to the table. In this instance Perl and Ruby are the easiest to write the code for. Java was probably the most difficult code to write because files are buried under more classes than in the other languages.

Slick Run Wins out over Launchy

I've read about Launchy several times in the past. Eveyrtime I've seen it I've thought, "why would I change, it doesn't do anything that slickrun does already". I had the "If it ain't broke, don't fix it" attitude.

However, as I have been setting up my tools on a new computer, I decided to give Launchy a try. Why? Because SlickRun only works when configured. It will run any and all of the programs that I want it to, when I configure a MagicWord for that program.

After the install the visual footprint of Launchy is a lot bigger than slick run, however, when typing a word, it gives me hints for what it thinks. I like that. It also hides completely, not even taking up space in my taskbar. I have more than enough things that take up task bar space and having one less is nice.


I've now been using it for a few days, and trying to stress both slickrun at work and launchy at home. Here's my thoughts on each.

SlickRun:
  • The floating command in the bottom corner of my window all the time is nice. It doesn't take up any space on my taskbar.
  • The date-time is visible whenever it does not have focus, which lets me remove the windows clock from the taskbar and keep a time visible always.
  • I can have multiple shortcuts for the same thing. I use edit and ue both to open Ultra Edit. Depending on which one I was thinking of at the time, they both work.
  • Commands that would work at a command prompt work in Slick run for example "javac c:\test\test.java" will compile the test.java file that folder.
  • Typing a folder name opens the folder "c:\rubycode" opens my rubycode folder.
  • A magic word can be for a program, a folder, or a website.
  • A magic word can chain other magic words together. I use one called morning, that I run first thing each morning, it opens outlook, instant messenger, a few things that I need to monitor daily at work and firefox. All that opens with me only having to type mor, because at that point the word is unique.
  • Typing 'hide' will minimize the floating command to the taskbar. I would prefer hiding it completely in those instances.
Launchy:
  • alt+enter shortcut to show application is great, I love that it's completely hidden and doesn't take up any space in the taskbar.
  • I would rather create a keyword in the application than have to create a shortcut with the keyword that I want. I don't want extra shortcuts running around anywhere on my computer, that's just more files I don't want to deal with.
  • I can potentially use batch files, but I like the chaining effect in SlickRun
  • The visual appeal of Launchy is great.
  • Web bookmarks are automatically indexed so whatever you have named them you can use to open those web pages. This is only useful to a limited number of bookmarks because I use Del.icio.us for my bookmarks.
  • A calculator plugin is included by default. sometimes I need to do a quick number check when figuring out payments or balancing something, I can type the numbers directly into Launchy and see the total. This is not an issue for me though because I have the calculator in the Google sidebar and calculator is a MagicWord in launchy so it is only a few more characters to get the same functionality.
I will leave Launchy at home for a while longer, and at home it may not be an issue, but on my work computer, where I need more exact control of things and I'm more of a power user of the tool, I will keep Slick Run, it serves my needs better, faster, and easier.

Monday, May 05, 2008

A stack - a visual representation

As I rolled up the unrolled toilet paper roll in the bathroom, thanks to my 2 year old, I thought, this is a lot like a stack; the first piece of toilet paper on in the center is the last piece off.