Archive for the 'Programming' Category

Productivity Tip

Wednesday, March 19th, 2008

Today, as I was playing with ideas after a big chunk of work, one interesting thought came, and it’s worth sharing. Everybody likes when the job is simple, straightforward and easy to do. Sometimes though times come when an assignment is … well, different.

I like to shoot these tasks first and, speaking in the context of PROgramming, like to make everything possible to never get back. If it implies writing a hundred of tests, that’s fine, just never again… you hear me? It’s not that I hate what I do, it’s that I, as a living being, hate stress.

Usually, I took the rest of the day off right after dealing with a complex or mundane to refresh the mind. It worked well, but took a lot of time and had a bitter taste of excuse to skip working hours. Today I invented something different for myself.

Here the summary of points that I (and hope you) usually keep in mind when working:

  • Focus on the task
  • Stop watching the clock
  • Keep a clear plan of attack with very small sub-tasks to cross them out as quickly as possible
  • Do whatever it takes to protect yourself from getting back (comprehensive tests suite, clear design etc)
  • Make a lot of comments to give you a hand if you still need to change something later

And now something new:

  • When the task is over, check in the sources, run all tests, and finish anything else that attaches you to the task, and then
  • Take a coffee break and detach yourself from it and the results as if somebody else did the job and you are left with an easy part (calling the module, using freshly designed database etc)
  • Start (not continue) working refreshed and, possibly, give you some easy and fun tasks to get the happy feeling of great job you always did

These are all simple steps, but I know no one who would follow them. I read many standard advices, like 50 minutes of work / 10 minutes of rest that are far from a silver bullet. They sound like a quick and dirty rule for those (or by those) who don’t really want to think WHY these breaks are important and, what’s more important, what to do during them.

With this last summary I feel I got closer to a better understanding of my own brain and how it works. Now I know how to reset that anxiety and stress to continue moving on without passively waiting for the same effect first.

Hope I induced some fresh ideas and insights. Feel free to share back.

Cheers!

JSP and Servlets Feel Bad on Return

Friday, February 22nd, 2008

For the last two weeks I’ve been writing a database editor application with JSP / Servlets. I’m a returning JSP / Servlet programmer with a 7+ year background, but with a 1 year Rails pause. Now that I finished the task, I can share my feelings. Sorry, Java world. It’s not your day.

My work started with reading through 400 pages of the Headstart with JSP / Servlets book just to refresh memories and get enough confidence to begin coding away. This fact speaks for itself. Even with the help of a top notch IDE it took 3 hours to configure the environment for a new project, install all necessary libraries, set paths etc, and I even didn’t try all these Struts, Springs, Hibernates and other complicated stuff. I knew it will be a pain and the whole perspective wetting my feet sounded scary and promised days of learning, lots of pitfalls, foruming, Googling and god knows what else. Hard things made simpler, and simple things made impossible, as someone said once about modern Java. Now throw a stone at me if I’m wrong.

To me, as a freelancing programmer, a waste of time (which is with capital ‘W’) equals to misery in slums. I never charge for my own preparations, learning and anything else that is not directly connected with a client or a project. With J2EE the preparations phase is much longer than expected. Then the developing phase comes, bug fixing (which shouldn’t be there in the first place, but with endless XML descriptors you never know when trouble calls your name), and all this time my clients are waiting. It’s nowhere near the Agile methodology if you ask me. It’s much more suited for RUP or aging enterprise level waterfall design. So, even if I don’t charge, every project has a deadline, and to be in time I have to deliberately stretch my estimates to incorporate the unexpected.

You may argue that I just need to learn it once and forever, apply some polish wax over time and revise every now and then. Not really, my answer would be. When freelancing, you need many tools in your kit and often you don’t get back to a technology until your next assignment. Returning to JSP and Servlets always gives me a shake in the knees.

The bottom line is I’m seriously considering to “forget” about it (after 7+ years of Java experience, to remind). It isn’t worth the time to me, it brings little satisfaction even though my clients are happy as a rule. To make it worse, it takes longer to get it right, multiple wheels are reinvented every time, testing is a headache when it comes to DB fixtures, page layouts aren’t present and an includes mess is everywhere, routing and filtering feels like a patch, not a native feature. Well, you got the idea…

For all of you who know me and value my advice, it’s time to move on. Pick the right book, pick the right coach, exercise your brain, evolve and thrive. Don’t be lazy or you risk to miss the right turn. The world is spinning even when you stand for years.

Personally, I found a very nice replacement — Rails — but don’t take it as an advert. I mentioned it only twice in this writing as it’s not the point. The point is the world is changing and there’s no reason to become dinosaurs that young!

Oh yes, and value your time. Cheers!

Rails: When an Uninitialized Constant Hits the Vent

Tuesday, January 29th, 2008

Last two weeks I was seeing the production server of one of my clients hit the same error over and over with no visible pattern. This second it works, the next it fails and leaves the Mongrel cluster in an undefined state somewhere between this world and hell.

The error I’m referring to is:

NameError (uninitialized constant MyModule::Utils::NetSession)
  ... backtrace follows ...

I need to repeat that it comes and goes under some non-obvious circumstances, and is hard to recreate. Fortunately, I found the solution and here’s what it was.

I have a directory hierarchy like below. I’m sure when you see it, it all becomes obvious and simple, but it wasn’t for me at that time as there were many files that I omitted below.

/lib
  /my_module
    klass1.rb
    ...
    utils.rb
  /utils
    net_session.rb

The piece of code in klass1 that failed looks as follows:

def new_session
  Utils::NetSession.new
end

Simple, heh.

Utils.rb is a helper module which is included into MyModule, but apparently loaded only when really necessary (it’s the only explanation why it didn’t fail all the time, as you will see). When it is loaded and included, the MyModule::Utils becomes defined, and Utils::NetSession resolution starts to fail. It happens as Rails begins looking for Utils name space from MyModule, finds MyModule::Utils and doesn’t find any NetSession there. That’s pretty much all to it.

The solutions are:

  • Either rename utils.rb (which I did in favor of utilities.rb), or
  • Use “::Utils::NetSession.new” (which is not safe as one day you can forget about the leading “::”, and get back to roots)

Hope this helps someone like me fighting the way through these extremely infrequent but painful Rails gotchas.

RSpec: Hierarchical Specifications

Tuesday, January 1st, 2008

RSpec is full of great features, but some of them either not very well documented or hidden to a naked eye. No wonder if you never discovered hierarchical specifications.

Traditionally, we write specifications like this:

describe AClass, "when doing this" do
    ...
end

describe AClass, "when doing that" do
    ...
end

Now imagine that you have some very similar specs with some common initialization:

describe AClass do
    before do
        ...
    end

    describe "when doing this" do
        before do
            ...
        end
        ...
    end

    describe "when doing that" do
        before do
            ...
        end
        ...
    end
end

You can see that you have common initializations for examples from both specifications and specific initializations for examples from each.

In the previous post I wrote that I prefer not to define helper methods outside the specification definition as they become global and tend to intersect with methods defined in other specs. So, what is the solution?

Assuming that you have a method “authenticate” that you need to call before every example in several specifications, you can define an upper-level specification “authenticated” and group other specs, like this:

describe AClass, "(authenticated)" do
    before do
        authenticate
    end

    describe "when doing this" do ... end
    describe "when doing that" do ... end

    def authenticate
        ...
    end
end

Now you have it all in a safe way!

RSpec: Three Things You May Not Know

Monday, December 31st, 2007

RSpec is fantastic. It’s so phenomenal that I can’t imagine my development without it anymore. It’s extremely easy to use, fun to write specifications and see how they turn green as you progress. But… at some point, when you have several hundreds of specs, using almost all documented features and excited to max, you may start facing serious problems. They aren’t easy to debug and may lead to a disappointment, unless you are prepared and armed with knowledge.

Load first, then execute. What I discovered was that RSpec loads all specifications upon startup and then executes them one-by-one. It means several things to us, the developers:

  • All constants you define in your specifications are global. You will get Ruby warnings on constant redefinitions, but it may not save you from unexpected glitches, when you expect one value, but get a completely different one.
  • All methods you define outside your specifications are global. It may affect your specifications in the same way as global constants — the functionality you expect from your helper methods may not be as expected. There are several solutions to this: 1) use modules with unique names to hold your helper methods and include them into your specifications, 2) use specifications hierarchy (my next post is about it) to group specifications that need helper methods.

Partials on Classes and Modules are BAD. It may sound bizarre, but they are. When you stub your Classes and Modules, you do it globally. Whatever you do in one specification or an example is visible in every following. Yes, right, NO ISOLATION. So, when you stub your model’s finders to return a mock, they do return this mock later in other specifications and examples that follow, even though you don’t expect it, and especially when you don’t expect it. It was a huge AHA moment for me.

RSpec loads (runs) specifications in recently-changed last order. It means that it runs specifications you changed last at the end. Now take a break and mull it over. Having everything above in mind, do you still think that you really have a green light? What if you ran you first specification (that you wrote first and never changed since then) after everything else? The only way to know is to try running every specification in your collection last, but of course, it’s not possible. The lack of complete isolation of one spec from another puts a big question mark after “is RSpec as useful as it seems”. My own answer is “yes”, but you need to know about all this to be on the safe side.

To summarize, here’s a quick NO-NO list of mine:

  • Never use Partials with Classes and Modules
  • Never define constants in or outside specifications
  • Never define methods outside specifications

I hope sincerely that this information helps you make your RSpec experience smooth as silk and you’ll avoid the road blocks I experienced during the last few weeks.

Happy Holidays!

BlogBridge: The best version we ever had…

Monday, December 24th, 2007

BlogBridge LogoAnd now, fans, put your hands together! Louder! Louder! I can’t hear you! Last Friday we released the best version of BlogBridge we ever had — BlogBridge 6.0.2. No more no less. It’s the consequential result of polishing, testing, stressing and doing other awful things you don’t want to know.

If you are using a standalone version, odds are you already was invited to upgrade. If it’s a weekly version, it must have upgraded itself automatically. If you never used BlogBridge, well… you are losing your time.

Ruby / Rails: Zen Testing with Autotest and XOSD

Thursday, November 29th, 2007

Lately I watched the Rest series of excellent Peepcode screencasts and fell in love with that nice marriage of Autotest and Growl they have on Mac.

If you don’t know what Autotest is, imagine the RSpec tester spinning in the background and watching the files you change. Once it sees something new, it runs corresponding specs and displays all usual “X examples, Y failures, Z pending” in its output. Then it looks for more changes and makes another specs run. Pretty useful.

The integration with Growl I referred to brings it to a next quality level — it lets you continue working and get the results of automated specs run as a Growl balloon. It looks like this: you do some changes in the editor, save a file, continue working and then, a couple of seconds later (when the testing is finished), a nice balloon appears reporting the status of the spec run against your new sources; with cool smiles and color.

We, Unix users, don’t have Growl, but we do have a secret weapon — XOSD — which is almost the same. The only difference is that it’s just a text-over-everything tool: no images, no background fills etc. However, for our purposes it works just fine.

I started by picking a Growl-Autotest integration script from wiki, then installed an xosd_cat console tool that talks to XOSD library (in Ubuntu you need xosd-bin package for this), and changed the script a bit to call this tool instead of Growl notifications.

Now I have very cute reports from the Autotest running in the background too.

Please download the “Autotest + XOSD” script and let me know what you think. Remember to put the “dot_autotest” from the archive into your home directory and rename it to “.autotest”.

Rails: Haml and Sass

Tuesday, October 30th, 2007

Haml logoHey fans of everything concise. My finding of today is Haml and Sass which is a quickly growing replacement for Rhtml (and plain HTML) and CSS. Just check the syntax sample on their main page and admit it, it’s much simpler and cleaner than plain (R)HTML. Everything has a meaning, everything cuts to chase.

Haml can be used with Ruby on Rails as a plug-in that transparently adds the support to your ActiveViews. You simply rename your views from .rhtml to .haml and start deleting redundant code. In case of CSS, you place your .sass in the stylesheets folder and they are automatically compiled on demand. One thing I haven’t figured out yet is whether they do every time, or once per change to save performance.

Haml and Sass are also used in the StaticMatic toolkit, which is exactly how I discovered them. The toolkit lets you put together static sites lighting fast. You simply write your pages in Haml, model your stylesheets in Sass, preview and do a final build. As the result of building you get a bunch of little cute HTML files and CSS stylesheets ready for upload to the site. If you, like me, still like static sites and want to save time on bringing them up and maintaining, it’s your choice.

Let me know what you think. A couple of lines is fine.

Rails: NetBeans IDE 6

Saturday, September 22nd, 2007

NetBeans 6Found the mention of that NetBeans 6 Beta supports Ruby on Rails and apparently is considered to be superior to Aptana, RadRails and others. I’m currently an Aptana user, which is Eclipse-based by the way, and pretty satisfied except for several things: code completion never works, popup documentation never works and the subversion integration is … a huge room for improvement.

At this very moment of writing I’m downloading the Beta 1 version of NetBeans 6 for a quick try. In fact the test run is scheduled for the morning, and I just wished you guys to know what’s going on. If everything is true what’s in the review I pointed out, and it all works even half as smooth as the guy describes, I leave for it without a bit of hesitation.

Let me know if you have any ideas on this.

CSS: min-height for IE

Sunday, September 9th, 2007

If you do any CSS coding for IE, you probably know that the beast arrogantly ignores the min-height property. Our best friends Firefox, Safari and Opera like it and so do we, CSS masters. For quite some time it was a burning question how to hack a stylesheet to make the ugly do what is required.

JavaScript Design PatternsThere were myriads of solutions with JavaScript, child selectors (that IE is far above of), and other wizardry. I was using them myself and they worked but so complex they were and hard to remember that I developed a habit to avoid min-heights — this powerful feature of CSS. Today I stumbled upon a small and elegant solution by Dustin Diaz, the author of a killer book on JavaScript Design Patterns. The solution itself looks as simple as this:

selector {   min-height:500px;   height:auto !important;   height:500px; }

Elegant and keeps everything together. It’s only a shame that it took me a couple of years to find it. Thanks Dustin!