Refactoring to separate presentation from logic

June 10, 2009 at 5:41 pm (Ruby, Scala, Week 12) (, , , )

My plan today was to dig into my Swing code, get some tests wrapped around it, and eliminate the duplication that built up last night as I played around with styling. Company business intervened, so I spent most of the day on a project with Eric M. and Caleb working on translating a large set of data into YAML format (with occasional HTML where necessary). As we got started, I realized that my work was going to be extremely error-prone, tedious, and slow if I just copied and pasted things over, formatting as I went. So I hacked up a Ruby script to do the basic import to YAML, which I think saved a lot of time (and I feel much more comfortable with handing this to the client). We did still do a bit of manual work (every export we sampled from our word processing program had limitations), but it wasn’t too bad.

Eventually, I got back over to my Swing code and eliminated a lot of duplication. I’m working on extracting all view/presentation code away from the code that I need to test. I’m not, for instance, going to bother with a test to make sure that the background color is blue. Among other benefits, this will make it clear to me when I’m finished, as I go through and add tests. I read the chapter in Programming in Scala last night on pattern matching, and I’m seeing uses for it everywhere now. I’m going to be very careful to avoid switch statements where polymorphism is possible, but I’m starting to get more comfortable with Scala and find multiple solutions pretty quickly.

There’s been some talk recently on the JRuby mailing list about using Jemmy to write integration tests on Swing code, so I’m excited about its prospects as I delve into my GUI tests.

Permalink 1 Comment

Scheme presentation and more fun with Scala/Swing

June 7, 2009 at 9:50 pm (Scala, Scheme, Week 11) (, , , , )

I gave my lunch & learn presentation on Scheme Friday, and it went pretty well. I found that I had forgotten to correct one of my slide mistakes, but aside from that I felt good about it. I went through the basics of Scheme/Lisp syntax and talked through some examples, and then finished up with the prime factors kata in Scheme. It went almost twice as long as I’d expected, since we stopped several times to discuss and answer questions. I took suggestions on the kata as well, which also slowed things down, but I felt like it was a better way to teach the process of refactoring to an inner recursive function (in place of what would be a loop in an imperative language). Everyone seemed interested and I got some great advice afterwards. The biggest things were that I didn’t always stand up (sometimes camping out in a chair) and that I kind of half-heartedly slapped a name on the presentation (“Scheme for Rubyists”) with only a few references to Ruby (where I could have had comparable Ruby examples for all my Scheme code).

Here are my [corrected] slides, if you want to get the basic gist (unfortunately, the formatting doesn’t translate perfectly to ppt file format – I used OpenOffice): Scheme Presentation

Friday afternoon and this weekend, I got a basic working version of Tic-Tac-Toe using Swing in Scala. I still have plenty to do: just as before, with Java Swing, I was basically spiking to learn the framework, and so there are some GUI tests missing. For now, I’ve put in TODO’s for implementation code I don’t have tests for; tomorrow I’ll start commenting out those pieces of code and driving them test-first. I feel good about my board and player classes; Friday I implemented some in-memory caching to speed up the computer player’s board-scoring computation. I still need to do some thinking about the technical article part of my apprenticeship challenges. I’m leaning towards something on functional programming, perhaps a few refactorings from imperative code to functional.

Permalink 2 Comments

State machines and scala.swing

June 4, 2009 at 10:49 pm (Scala, Scheme, Week 11) (, , , , )

After some morning refactoring on my Scala Tic-Tac-Toe (including moving my computer player’s minimax algorithm to a completely functional style) and speed tweaks, I moved on to thinking about how to integrate a GUI. Micah’s told me it’s not a requirement, but I’d like to have another crack at GUI development – I was very slow thinking things through in Java. Micah and I had talked yesterday about the possibility of a state machine to hold the game state so that my other application logic didn’t need to concern itself with whose turn it was. I have mixed feelings about it: on the one hand, state is what I’m trying to avoid in my functional programming study, but on the other, it’s apparently a very widely applicable design pattern that I ought to learn anyway.

At any rate, I spent the morning and most of the afternoon looking into SMC, the state machine compiler. Apparently there are numerous different ones (all named SMC) floating around on the internet. I believe all of them started with Uncle Bob‘s idea, and the one I’m using does give him credit on the website. It’s really like stepping into a second new language (DSL) writing state tables for the state machine compiler. I’m sure that the benefits will outweigh the time I needed to spend reading the documentation.

At the end of the workday, I fooled around with Scala’s Swing library (a wrapper for Java Swing). There are still some Javadocs I needed to dig into to understand what I was doing, but I was able to pick up the syntax pretty quickly. I have to say, Scala really does seem to be Java++. The Java libraries are still super-easy to grab, and the syntax is similar enough that it feels closer than it did with JRuby. The advantages I do see to Java are a familiar syntax and proliferation of tools, especially IDE support for refactoring – Scala’s IntelliJ plugin is good and has a few refactorings, but it has plenty of room for growth.

I spent some time tonight going back over my slides for tomorrow’s Lunch & Learn (“Scheme for Rubyists”), going through the presentation once for my wife and our dogs. I found a couple of outright mistakes and several extra points I needed to make, so it was good practice. I also went through a kata in Scheme that I’ll do tomorrow for the group if we have time. Wish me luck!

Permalink Leave a Comment

Week 2, Monday

March 30, 2009 at 6:57 pm (Java, Week 2) (, , , , , , )

I feel like I’m getting close to completing the Tic-Tac-Toe game in Java. The functionality is there for Swing GUI and console modes, but I have a lot more to learn about GUI testing (simulating mousePressed and actionPerformed events) and testing threads (turns out I need to USE threads to test threads – duh).

But I’m feeling much more comfortable in Java. At Micah’s suggestion today, I took a lot of GUI-specific code (JLabel, JButton, etc.) out of my controller class and moved it into the view. This made a lot of sense since the implementation of the view should be easily swappable, without the controller worrying about it. I also refactored my old ConsoleDisplay class out to be more in line with my GUI code, so that both the console code and GUI code are just views, using the SAME controller/presenter. This was kind of a pain in that I had to add threading in the console code so that the GUI controller worked for it as well, but the big win here is that I can swap out views super-easily. It probably would have taken me another whole weekend without Micah’s help today, though.

We had an internal stand-up meeting, where everybody briefly talked about their current projects, side projects, learning experiences, blogs, kata, etc. It was short and to the point, but I think it’s a great idea for a team’s camaraderie – especially since two of the team members work at a client site. Paul just came out with a great blog post titled Material Consciousness in Software that’s well worth your time, and both Erics have blog posts in the works. Stay tuned!

Speaking of the culture here at 8th Light, I noticed very early on that everyone, without exception, shakes hands with everyone else as they arrive at work, and as they leave. It seemed very formal and quirky at first, but it’s really growing on me. So often, people show up to work with their team and barely grunt a “Morning” before diving into code. I definitely was guilty of that at my old job, and it seems like this is a good way to reinforce the team’s communication. Now that I write this down, it sounds like marketing mumbo-jumbo, but it’s a fact. I don’t know whether this is something that’s grown organically here or if the guys formulated the idea before its execution (or somewhere in between), but shaking hands feels like it solidifies a relationship each time, and at the same time heightens the importance of what you’re about to do (or have just done): software craftsmanship.

Permalink Leave a Comment

Week 1, Weekend

March 29, 2009 at 9:03 pm (Java, Week 1) (, , , )

I spent a lot of time this weekend trying to wrap my head around Java/Swing listeners and how to do TDD with this setup. Eventually I backed up a bit and dug into some more basic Java knowledge – reading from Learning Java by Patrick Niemeyer and Jonathan Knudsen. I just was a little overwhelmed with all I need to learn, and I wanted to focus things a bit more. And it turns out, after spending a good portion of the weekend looking at event listener code, I have a lot better grasp of it now. I was able to delete big chunks of my old GUI code and simplify some things. There are still LOTS of things I need to learn about testing this stuff; I think I might’ve painted myself into a corner with my console-based presenter, so that testing is difficult. Maybe there’s a way around it I’m not seeing, though. Basically, I have the core logic sending a request to a controller (for a move, the game type, or playing again), and the controller listening to the view layer for the answer. Right now there’s a lot of state-saving variables (boolean waitingForInput, stuff like that) that I know there has to be a way around.

At any rate, I’m going to spend some more time with the Java book over the coming week, so that I can get a better handle on things. I’ve been a bit spoiled in that I’ve worked with Ruby for the past couple of years, and have had all that time to absorb and read about the language. So much to learn! It’s so motivating when I come into work and literally everyone else knows so much more than I do (and are more disciplined). The advice that I’ve read from Chad Fowler (My Job Went to India) and many others to “Be the Worst” is really paying off.

I also realized that I never blogged about our Friday Lunch & Learn session – we had a Randori session, where we worked in five-minute pair programming sessions to build a small app. It was humbling to get back into Ruby, which I felt great about two weeks ago, and forget the syntax to set an instance variable in front of everybody (I was being Java-y). But it was excellent to see everybody in action and to hear people’s thought processes as we started the app, when the design was so sparse.

Permalink Leave a Comment

Week 1, Friday

March 27, 2009 at 5:28 pm (Java, Week 1) (, , , , , )

I spent some time last night experimenting with Swing and was able to get the Tic-Tac-Toe grid set up, with some listeners on the squares. Then this morning I wired up the GUI to my existing Java Code. I only had to make one major change, which was getting rid of the Dependency Inversion Principle violation I had in my display code. I just turned that into an abstract class and moved the existing, console-based code into a subclass, and then also derived a GUI display class from the abstract class.

That part was simple, but I really did a lot of monkey-hacking today to get the GUI working properly together with the existing game code. I think part of the problem was that I never really stopped the “spiking” I did last night to learn how to use Swing a little bit. I just kept right on trucking (in implementation code, without tests) until I had a working game. So I need to go back and retrofit some tests to most of the code I’ve written today, which I’m sure will mean rewriting some things. My mom got me Michael Feathers’ Working Effectively With Legacy Code for my birthday, so I may dig into that some to give me some ideas. My understanding is that the book describes legacy code as any code not under test, so I wrote a bunch of legacy code today [frown].

On a brighter note, I’m going to be working with one of the craftsmen on an internal project, most likely using Rails, so at least I’ll be familiar with the language for this one. I’m glad I’ll have a compelling reason to learn RSpec, and probably Cucumber and Selenium as well. These are the kinds of things that motivated me to want to work at 8th Light in the first place. As I told one of the craftsmen when I interviewed, it seems like all of the big names in the Ruby world use TDD/BDD, so I really was looking forward to writing code that way.

I took my first crack at estimating (our initial iteration meeting for the project was today), and only time will tell if I was being too optimistic or not. I certainly don’t think we’ll have too little to do, but as I said in a previous post, I think I’ll get better at estimating as I do it more often and measure actual velocity (stories completed per iteration) against estimates.

Since it’s the end of my first week here, I’ll just close with a general thought on TDD: it isn’t faster to write your first few lines of code in a new project. But if you have tests for those lines, then you know they work. The tests allow you to forget about them, and still be able to change other parts of the eventual system without fear of breaking old stuff. Because it’s got a test suite that you run and see that of the system’s requirements that you have encoded in tests, you’re passing. I’m looking forward to making this a habit and really having TDD become my default coding behavior.

Permalink 6 Comments

Week 1, Thursday

March 26, 2009 at 7:05 pm (Java, Week 1) (, , , , , , , )

I FINALLY got my head wrapped around the minimax algorithm today. I went more slowly and stepped away more often, and I finally have an unbeatable computer in Java. This took me a heck of a lot longer than it did in Ruby, but I think it was reasonable considering my limited Java knowledge, a new algorithm, and new knowledge about things to avoid.

My last step was kind of an interesting one: I rewrote (not refactored) part of the algorithm in a way that was easy for me to understand, very slowly and deliberately, and it came out right! Imagine that…

// before:
bestScore = Math.max(bestScore, -minimax(child, depth - 1, otherPlayer);

// after:
otherPlayerScore = minimax(child, depth - 1, otherPlayer);
maxOtherPlayerScore = Math.max(otherPlayerScore, maxOtherPlayerScore);
bestScore = -maxOtherPlayerScore;

If you take a minute or two to look through this, you’ll see that the two versions are not equivalent. Although I could break the second version down into one line, I don’t trust myself to be able to understand it as well later on, so I’m leaving it explicitly spelled out this way.

I demoed the game for Micah and indeed, it seemed to work correctly. Micah had me draw up a UML diagram of the code in its current state, with all the methods and dependencies that I knew about, and Micah pointed out violations of the SOLID principles for object-oriented class design. I’d read about them but needed a refresher and deeper understanding, so he walked me through each of the principles, asking me what they were and where I saw problems. I didn’t catch them all of, course, but I was glad I at least had a cursory introduction already. I made sure that I understood the kinds of situations in which a principle violation would bite me.

For those unfamilar with these, you can learn more on Ward Cunningham’s wiki (he’s the inventor of the wiki, among other distinctions):

I just read about these for the first time a few months ago (they’re detailed in Agile Software Development: Principles, Practices, and Patterns by Robert C. Martin (Micah’s dad, incidentally). I had more Dependency Inversion violations than anything (though certainly not as many as my Ruby version had), but there were some Open-Closed problems as well.

My next step, which seems realistic for an Agile/XP project, is to put a GUI on top of my Java code. I haven’t done anything to speak of with Swing, so I spent a couple of hours this afternoon investigating the API and figuring out sizing, colors, and other things I’m going to need to draw the board.

I have an Open-Closed violation or two around my GameDisplay class, which means that my design is going to have to change around that point in order to substitute the GUI for my command-line output. The good news is that I HAVE a display class in the first place; my Ruby display code was coupled to the rest of the game in several places.

Permalink Leave a Comment