java


I never really used a debugger until I did Java. Before that I did what was called “PHP Debugging” which is littering your code with print statements until you figure out what you need to know, then going back and making sure you deleted them! I sometimes would put a unique string like

print “QWE” . $myawesomevar

Or something like that, then going back and searching your code for QWE (just picked something that was easy to type!). But all that gets rather annoying. They might have nice debuggers for PHP now, I haven’t really done php in 4-5 years. I really didn’t understand the power of breakpoints until I did java and I thought that was pretty cool. Now that I do all ruby, I sort of miss eclipse (I didn’t actually think I’d ever say that…) since all I use right now is textmate and vi which don’t have the built debugger support that eclipse does. Some of the newer ruby editors might, I haven’t spent any research on them.

I found ruby-debug and it works great! You can set a breakpoint and then climb inside your application and peek around and see what is going on. I’ve done this in controllers and even in test mode.

If you use passenger, you can still use it but its a little tricky to setup. This blog post from duckpunching.com has some neat tips and a rake task to make it easier. Be sure to start the rdebug -c from the console after you have set a breakpoint and reloaded your page.

If you are using passenger, you can’t use the irb command inside of the ruby-debug console, but I found that most of the time just being able to poke around the variable space inside my app has been enough for me to understand what is going on.

There are quite a few commands available in the debug console, but these are the ones I’ve used:

help – view the list of commands
l list – this shows context around the current line the debugger is on
n next – moves to the next line
p print – print a variable
irb jump to console – I dont use this very often and it doesn’t work if you are using passenger
c cont – continue to end of breakpoint or end of page load, after I have seen what I want to see I do this to get out of the console

Resources

Anyways, hope some of you find it useful and happy debugging :)

Update: I wrote this in preparation for a short talk at AustinOnRails while giving the talk, the group had some suggestions:

put in a ~/.rdebugrc

set autoeval
set autolist

autolist – will run list command when you enter
autoeval – will eval each line, so instead of “eval @profile” to get it to print, it will automatically eval

doing m [object] can show methods in a nice table format. Thats cool, i have often gone to irb and did String.methods.sort but that is kinda hard to read.

Anyways, good stuff!

Call me crazy, but this is why I classify myself as a language geek. When I learn something fascinating, i wonder hmm how can I do that with X language? My last post I did an example of the Builder pattern as described in Effective Java by Joshua Bloch. The main motivation for me to use Builder is to have flexible parameter lists, without worrying about order of parameters (there are a few other reasons outlined in the book, but this is what I find cool).

Its too easy.

My class:

RUBY:
  1. class Address
  2.   attr_accessor :street, :street2, :city, :state, :zip, :address_type
  3.  
  4.   def initialize(&block)
  5.    
  6.     #set default values
  7.     self.city = "Chicago"
  8.     self.state = "IL"
  9.    
  10.     #set value from block
  11.     instance_eval &block if block_given?
  12.  
  13.   end
  14.  
  15. end

And the usage of it:

RUBY:
  1. def testDefaultValues
  2.     myaddress = Address.new
  3.     assert_equal("Chicago", myaddress.city)
  4.     assert_equal("IL", myaddress.state)
  5.   end
  6.  
  7.   def testStreetStateZip
  8.     myaddress = Address.new do
  9.       self.street = "this is the street"
  10.       self.zip = "11111"
  11.     end
  12.     assert_equal("Chicago", myaddress.city)
  13.     assert_equal("IL", myaddress.state)
  14.     assert_equal("this is the street", myaddress.street)
  15.     assert_equal("11111", myaddress.zip)
  16.   end

Wow, huh? Compare to

JAVA:
  1. public void testBuilderDefaults() {
  2. Address expected = new Address.Builder("Chicago", "IL").build();
  3. assertEquals("State is IL", "IL", expected.getState());
  4. assertEquals("City is Chicago", "Chicago", expected.getCity());
  5. }

then the optional params are chained to that:

JAVA:
  1. public void testBuilderStreetStateZip() {
  2.    Address expected = new Address.Builder("Chicago", "IL").street("this is an address").zip("11111").build();
  3.   assertEquals("this is an address", expected.getStreet());
  4.   assertEquals("11111", expected.getZip());
  5.   assertEquals("IL", expected.getState());
  6.   assertEquals("Chicago", expected.getCity());
  7. }

Full source for Ruby (though I was able to paste it all here!)
Address class in ruby | Address test in ruby

And for Java, if you want to compare ...
Address class in Java | Address test in java

Yes... sometimes its hard not to gloat. :-D

yeah yeah yeah, its not really "fair" to compare strongly typed languages... but as I said, my motivation is to have easy parameter lists without having to remember specific ordering of params for constructor or use multiple set methods.

I have been reading Effective Java by Joshua Bloch and learned something new so I wanted to try it out.

Making long parameter lists in your constructor is not fun and prone to errors. Previously I thought that best way to handle this situation was to make a bunch of setter methods. This can get kind of tedious and hard to follow when there are alot of parameters:

JAVA:
  1. Address myaddress = new Address("Chicago", "IL");
  2. myaddress.setZip("44422");

Using a Builder object:

JAVA:
  1. Address myaddress = new Address.Builder().city("Chicago").state("IL").zip("44422").build();

Using a builder class allows you to specify params in any order too!

Here is the source code for my Address class with Builder. The builder is implemented as a nested class since it will only be used by the Address class.

Address class with Builder

Test for Address class

The required parameters are set in the Builder constructor:

JAVA:
  1. public void testBuilderDefaults() {
  2. Address expected = new Address.Builder("Chicago", "IL").build();
  3. assertEquals("State is IL", "IL", expected.getState());
  4. assertEquals("City is Chicago", "Chicago", expected.getCity());
  5. }

then the optional params are chained to that:

JAVA:
  1. public void testBuilderStreetStateZip() {
  2.   Address expected = new Address.Builder("Chicago", "IL").street("this is an address").zip("11111").build();
  3. assertEquals("Address is this is an address", "this is an address", expected.getStreet());
  4. assertEquals("Zip is 11111", "11111", expected.getZip());
  5. assertEquals("State is IL", "IL", expected.getState());
  6. assertEquals("City is Chicago", "Chicago", expected.getCity());
  7. }

The book goes into more discussion that I haven't quite wrapped my head around yet, but this is interesting stuff .. even though it is java ;)

I was pretty excited to find UiHandler, it makes the organization of code so much cleaner!

I am putting in the full code for both, so you can see the beauty for yourself! Pay attention to the comments where i put the gotchas that got me at first! :)
Before:

JAVA:
  1. package com.rubygeek.sandbox.client;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import com.google.gwt.core.client.GWT;
  6. import com.google.gwt.event.dom.client.ClickEvent;
  7. import com.google.gwt.event.dom.client.ClickHandler;
  8. import com.google.gwt.uibinder.client.UiBinder;
  9. import com.google.gwt.uibinder.client.UiField;
  10. import com.google.gwt.user.client.Window;
  11. import com.google.gwt.user.client.ui.Button;
  12. import com.google.gwt.user.client.ui.CheckBox;
  13. import com.google.gwt.user.client.ui.Composite;
  14. import com.google.gwt.user.client.ui.Widget;
  15.  
  16.  
  17. public class LanguageList extends Composite {
  18.  
  19.   interface MyUiBinder extends UiBinder<Widget, LanguageList> {}
  20.   private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
  21.  
  22.   @UiField CheckBox rubyCheck;
  23.   @UiField CheckBox pythonCheck;
  24.   @UiField CheckBox javaCheck;
  25.   @UiField CheckBox phpCheck;
  26.   @UiField Button button;
  27.  
  28.   public LanguageList() {
  29. // bind XML file of same name of this class to this class
  30. initWidget(uiBinder.createAndBindUi(this));
  31.  
  32. final ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
  33. boxes.add(rubyCheck);
  34. boxes.add(pythonCheck);
  35. boxes.add(javaCheck);
  36. boxes.add(phpCheck);
  37.  
  38. // add button and handler to alert the values of checkboxes
  39. button.addClickHandler(new ClickHandler() {
  40. public void onClick(ClickEvent event) {
  41. String output = "";
  42. for(CheckBox box : boxes) {
  43. if (box.getValue()) {
  44. output += box.getFormValue() + ", ";
  45. }
  46. }
  47. Window.alert("You checked: "+ output);
  48. }
  49. });
  50.  
  51.   }
  52. }

After:

JAVA:
  1. package com.rubygeek.sandbox.client;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import com.google.gwt.core.client.GWT;
  6. import com.google.gwt.event.dom.client.ClickEvent;
  7. import com.google.gwt.uibinder.client.UiBinder;
  8. import com.google.gwt.uibinder.client.UiField;
  9. import com.google.gwt.uibinder.client.UiHandler;
  10. import com.google.gwt.user.client.Window;
  11. import com.google.gwt.user.client.ui.CheckBox;
  12. import com.google.gwt.user.client.ui.Composite;
  13. import com.google.gwt.user.client.ui.Widget;
  14.  
  15. public class LanguageList extends Composite {
  16.  
  17.   interface MyUiBinder extends UiBinder<Widget, LanguageList> {}
  18.   private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
  19.  
  20.   final ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
  21.  
  22.   @UiField CheckBox rubyCheck;
  23.   @UiField CheckBox pythonCheck;
  24.   @UiField CheckBox javaCheck;
  25.   @UiField CheckBox phpCheck;
  26.  
  27.   // add ClickEvent handler to button with ui:field="languageButton" in the UiBinder code    
  28.   // !!! note no ; at end of this annotation, and the name of function does not matter, its the annotation that ties it to the
  29.   // body of the method, also this does not go inside the class :) (i spend 40 mins figuring that out...)
  30.   @UiHandler("languageButton")
  31.   void doClick(ClickEvent event) {
  32.       String output = "";
  33.       for(CheckBox box : boxes) {
  34.           if (box.getValue()) {
  35.               output += box.getFormValue() + ", ";
  36.           }
  37.       }
  38.       Window.alert("You checked: "+ output);
  39.  }
  40.  
  41.   public LanguageList() {
  42.       // bind XML file of same name of this class to this class
  43.       initWidget(uiBinder.createAndBindUi(this));
  44.       
  45.       boxes.add(rubyCheck);
  46.       boxes.add(pythonCheck);
  47.       boxes.add(javaCheck);
  48.       boxes.add(phpCheck);
  49.   }
  50. }

See the constructure is further slimmed down!

Note: as of right now, you can only get this feature in Trunk. see here for how to download the source and use it More Info on release

One of the great new features coming out of GWT 2.0 is UiBinder, a way to make a declarative UI without making tons of objects. Reminding you of swing? Yeah, I didn't sign up to be a Swing developer. I was sort of disturbed when I started doing gwt and was writing tons of java to just do simple HTML things.

Full Source

JAVA:
  1. CheckBox rubyCheck = new CheckBox("Ruby");
  2. rubyCheck.setFormValue("ruby");
  3. boxes.add(rubyCheck);
  4.  
  5. CheckBox pythonCheck = new CheckBox("Python");
  6. pythonCheck.setFormValue("python");
  7. boxes.add(pythonCheck);
  8.  
  9. CheckBox javaCheck = new CheckBox("Java");
  10. javaCheck.setFormValue("java");
  11. boxes.add(javaCheck);
  12.  
  13. CheckBox phpCheck = new CheckBox("PHP");
  14. phpCheck.setFormValue("php");
  15. boxes.add(phpCheck);
  16.  
  17. // set up panel
  18. Panel panel = new VerticalPanel();
  19. panel.add(new Label("Choose a language:"));

Compare to the UiBinder code:

XML:
  1. <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
  2.     xmlns:g='urn:import:com.google.gwt.user.client.ui'>
  3.     <g:VerticalPanel>
  4.       <g:Label>Choose a language:</g:Label>
  5.       <g:CheckBox ui:field="rubyCheck" formValue="ruby">Ruby</g:CheckBox>
  6.       <g:CheckBox ui:field="pythonCheck" formValue="python">Python</g:CheckBox>
  7.       <g:CheckBox ui:field="javaCheck" formValue="java">Java</g:CheckBox>
  8.       <g:CheckBox ui:field="phpCheck" formValue="php">PHP</g:CheckBox>
  9.       <g:Button ui:field="button">Submit</g:Button>
  10.     </g:VerticalPanel>
  11. </ui:UiBinder>

It is somewhat like HTML, each item with attribute "ui:field=" is the reference to the object that gets created in Java. Here's the Java code that uses this:

Full Source

JAVA:
  1. public class LanguageList extends Composite {
  2.  
  3.   interface MyUiBinder extends UiBinder<Widget, LanguageList> {}
  4.   private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
  5.  
  6.   @UiField CheckBox rubyCheck;
  7.   @UiField CheckBox pythonCheck;
  8.   @UiField CheckBox javaCheck;
  9.   @UiField CheckBox phpCheck;
  10.   @UiField Button button;
  11.  
  12.   public LanguageList() {
  13.       // bind XML file of same name of this class to this class
  14.       initWidget(uiBinder.createAndBindUi(this));
  15.       
  16.       final ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
  17.       boxes.add(rubyCheck);
  18.       boxes.add(pythonCheck);
  19.       boxes.add(javaCheck);
  20.       boxes.add(phpCheck);
  21.   }

We still have to add them to the Array (which is use to display checked results) but doesn't that look so much better? And you are able to add the values of the checkboxes to the xml too.

When using UiBinder, make sure you add it as inherits to the xml for the module (i forgot at first and had errors with gwt trying to find UiBinder!)

I didn't do exactly one-to-one comparison between UiBinder and not, but i do have two complete gwt apps you can look at. I find it really helpful when learning something to look at complete apps rather than just snippits of code.

There is some documentation on Ui:Binder on Google Code, but at first I found it hard to follow since it doesn't say what files each piece goes in, it took me awhile to figure it out. Maybe its just me though. :)

Before UiBinder
After Ui Binder

Anyways, just a quick example that might help some people out there. I want to explore more about patterns in GWT and I'll write them up here.

Sometime ago a co-worker asked me what my github name was. I had forgotten..I hadn't used it in so long! He was surprised that I didn't have any open source code out there! I said, umm..i haven't written anything I think someone would want!

I tend to start projects, work a bit on them and leave them. I find something new and exciting. I get busy with school, work, and life. But I really want to make something that I can release as open source and work with people. At work, I am on a team of developers and its nice, when I am stuck or not sure if this thing is good idea, I can ask. In previous jobs, I was mostly the sole developer, or at least only one on my project.

How do I get better at programming? I've been thinking about this alot as I am trying to learn java (I have the syntax pretty well but there is more to a language than syntax). Well, its practice! practice and practice. Having someone review your code and get better because of it. I want to get better at Java. I want to make an android app. So I finally started one .. with someone!

I am part of this great group of ladies in DevChix. A group me and 3 others started sometime ago. I had the idea (and this has always been in the back of my mind when I started DevChix) to start a project with someone and commit to 2-4 hours a week. I posted to the list, found someone with some experience in android and also the same desires as me. We started a really simple app (a todo list, how original!) but its a start. I threw something together which was really a collection of all my started and not finished android apps rolled into one. I had listing of tasks, add tasks didn't work quite right. I uploaded what I had and Jessica checked it out and made it work. There is a long way to go ... but... hey we started it!

Our rough design:
http://wiki.devchix.com/index.php?title=Android_Project:_Daily_ToDo_List

Our project:
http://code.google.com/p/devchix/source/browse/

This is not a ground breaking thing but something I learned a few weeks ago. I've been learning java for the past few months and its a whole different world than php, perl or ruby. I learned how to use standard in from my professor a few week ago. Say you have a program like this, where you want to get some user input.

JAVA:
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class Example2 {
  6.  
  7.     /**
  8.      * @param args
  9.      */
  10.     public static void main(String[] args) {
  11.         Scanner input = new Scanner(System.in);
  12.         ArrayList<String> studentList = new ArrayList<String>();   
  13.        
  14.         System.out.println("Enter names separated by \n or space, Q to quit");
  15.         while(input.hasNext()) {
  16.             String userInput = input.next();   
  17.             if (userInput.equalsIgnoreCase("Q")) {
  18.                 break;
  19.             } else {
  20.                 studentList.add(userInput);
  21.             }
  22.            
  23.         }
  24.        
  25.         for (String name : studentList) {
  26.             System.out.println("Name is: " +name);
  27.         }
  28.     }
  29.  
  30. }

Modifying the program slightly, you can accept standard input like:

JAVA:
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class Example {
  6.  
  7.     /**
  8.      * @param args
  9.      */
  10.     public static void main(String[] args) {
  11.         Scanner input = new Scanner(System.in);
  12.         ArrayList<String> studentList = new ArrayList<String>();   
  13.        
  14.         while(input.hasNext()) {
  15.             String name = input.next()
  16.             studentList.add(name);
  17.            
  18.         }
  19.        
  20.         for (String name : studentList) {
  21.             System.out.println("Name is: " +name);
  22.         }
  23.     }
  24.  
  25. }

Then you can run the program on the command line like this:

$ java Example < sample_data.txt
Name is: Bob
Name is: Charles
Name is: Henry
Name is: Emery
Name is: Chad

Not too earth shattering but may help you make a simple program easier to test!

I've been doing a variety of things lately:

Playing with Android
I got the "Hello Android" beta book from Pragmatic Programmers -- I am trying to remember its beta but its sort of hard to follow. Be prepared to download the source code for the book and compare to what the book has to see what is missing, so you can get your thing to run. I am going to look at some other tutorials at the moment to get more familiar. Maybe the author assumes the reader knows more than me! Which is possible since I haven't done much java programming.

Wordpress 2.5.1 and EngineYard

The DevChix.com blog is a wordpress blog and hosted at DreamHost. We got a free slice for DevChix from the kind folks at EngineYard. They were nice enough to set it all up for us with wordpress and giving us a deploy.rb file ready to go! Their support is pretty fast too and I was able to get some help from the irc chat as well. The new wordpress has some neat features and looks nicer. I want to install a captcha though for blog comments, even with Akesmet I get tired of sorting through them! I was able to get all our plugins installed and seems good.

Playing with App Engine
I worked on this last week while on an airplane. I wasn't sure it would work offline -- but it did. Even the database...err..yeah whatever it is. I was able to add data ..but where is that data?

Django your mango
Yes, been checking it by doing the bundled tutorials. I haven't gotten back to it since my last post. Need to get back to it before I forget what I was doing. haha.

Git 'er done
Finally, I am going to learn git and try it on a project with a friend. I am hoping it proves useful since I often code on the go with no internet access. I sometimes have to do a poor mans cvs and save things as myfile1.rb myfile2.rb to try out things and then able able to "go back". Rock and roll.

Any one know, does there exist a TestSimple/More (from Perl) for Java like the module for Perl?

whats that you say? I wrote about TestMore in Perl and PHP Here and here also!

I did a quick scan with google didn't give me much hope. So I wrote this quickly on the train this morning, since I can't hardly stand to program in any language without a TestMore like implementation.. (I know there's JUnit, and I'ved used it before, but its alot of overhead.. I just needed some quick tests!)

Class: (not making any claim this is the best or greatest way, and not 100% TAP protocol)

JAVA:
  1. package com.myawesomesite.util;
  2.  
  3. public class TestSimple {
  4.  
  5.  private int testCount;
  6.  
  7.  public TestSimple() {
  8.   this.testCount = 0;
  9.  }
  10.  
  11.  public void ok(boolean truth, String message) {
  12.   this.testCount++;
  13.   System.out.println( (truth ? "ok " : "not ok ")
  14.                       + this.testCount + " - "
  15.                       + message);
  16.  }

Usage:

JAVA:
  1. package com.myawesomesite.java;
  2.  
  3. import com.myawesomesite.java.*;
  4. import com.myawesomesite.util.TestSimple;
  5.  
  6. public class TestAnimal {
  7.  
  8.  public static void main(String[] args) {
  9.   TestSimple test = new TestSimple();
  10.  
  11.   Dog bob = new Dog();
  12.  
  13.   bob.setColor("green");
  14.   bob.setCollarSize(10);
  15.  
  16.   test.ok(bob.getColor() == "green", "bob's color is green");
  17.   test.ok(bob.getCollarSize() == 10,"bob's collar size is 10");
  18.   test.ok(bob.getCollarSize() == 0,"bob's collar size 0");
  19.  
  20.  
  21.  }
  22.  
  23. }

output is:

ok 1 - bob's color is green
ok 2 - bob's collar size is 10
not ok 3 - bob's collar size is 0

In college, about 7 years ago (yikes) I learned Java near the end of my year. I loved it. I got an A in the class and was all set to get a java job after college. Uhh.. how AM I supposed to get 3 years experience?!?! ... so thats when I picked up PHP and went down the web programming path..

At my current job, a Perl job, they have a study group for the Java certification. I thought I'd join them, taking every advantage for learning that I can. I am not 100% sure I will take the test, but it will motivate me I think to get back into Java. I joke with my Java programmer friends "I need to relearn java, so I can convert all your java apps to ruby someday.. haha" .. I don't even know if i will like doing Java.

My husband made me throw out 80% of my computer books that were out of date! "GASP! what? throw out DOS for Dummies!?!?! VB 5????" ... I threw out some java books. A friend of mine said they although java has some new features in the past years the core library is probably still about the same. But really I don't have time to waste with old books, so I decided if I should EVER want to do Java.. I'll get some new ones.

I was looking over the books in the java category at bookpool - there are so many! Does anybody have any suggestions? I think I have a pretty firm grasp on objects, interfaces, etc all that stuff. I just need a reference book or something to get me re-familiarized with the language and learn some of the java idioms and conventions.