All posts tagged “programming

Adding a custom Spree payment Gateway outside a Rails Engine

Adding a new Payment Gateway to Spree through a Rails Engine is pretty straight forward as you can hook in your new gateway after the initial payment gateway array has been created. This is how the spree_gateway gem does it:

If you want to do the same thing for your own project contained gateway it’s a little different. If you try to just directly edit the payment_methods array in an initializer it will get wiped out when the Spree core engine sets the initial bogus and simple methods. I got around the problem by hooking my gateway in using the after_initialize method. Here I’m hooking in after SpreeGateway:

Accessing values in your plist file from your iPhone/iPad app

Recently I’ve been coding some iPhone and iPad apps with multiple targets, all sharing the same codebase. Previously I had been using Preprocessor Macros to get the job done, but that soon turns messy and hard to maintain. I’ve since moved to just storing target specific values in each apps related plist file. Retrieving a value is as simple as:

Why Code Quality Matters

Recently the discussion of code quality has come up with a couple of different people. With the main question:

“If the app does what it’s supposed to do, why does code quality matter?”

In one instance an application that was bringing in over a £1m in revenues a month had one of the worst code bases a friend had ever seen. And I totally agree that there is no correlation between code quality and the earnings/growth potential of an application. Then a few days ago I was reading the brilliant Zed Shaw article “Products For People Who Make Products For People” which completely crystalised why code quality is important:

“… the frontend product is what brings your revenue stream in, but your backend operations quality is what keeps your costs down as you grow. If your backend costs get out of control because of technical debt then you won’t make a profit, or someone who can keep them down will just copy you and wipe you out with less.”

Perfect! That’s it exactly. Code quality matters as that’s what allows you to grow the system beyond your v1. If you never plan/or want to get past v1, then perhaps you can get away with being a lot more lieniet in your “quality”. I know that’s what I do, if it’s a quick app then normally I have only the most basic of tests and cut corners where I wouldn’t normally. Maybe in a sense, code quality is a reflection of technical debt. The lower the quality, the higher the debt and sooner or later you’re going to have to pay that back (Unless you’re fortunate enough to close up shop before that time comes). I’ve worked on projects where the technical debt is so high that you’re paralysed and just can’t do anything. Simple changes become huge problems as you’ve been painted into a corner, and the fear of breaking something is so huge that new feature requests are shied away from.

If you want/expect to be able to grow your business then keep the bar high. Code quality matters a hell of a lot.

Broken Window Policy of Programming

There comes a point in every software projects life where everything just feels wrong. No one wants to touch the code as it stinks and everyone working on the project just feels demotivated and would rather just go home then have to do anything more on it. On projects like this, when it comes to adding new features or bits of code, because everything else is such a mess, the changes are just hacked in rather than being properly thought out and coded up well.

We’ve all been there and the frustrating thing is that our opinion of the project, from good to bad, seems to happens over night. If you sit down and think back, you can probably pick out all the things that were just shoved in that eventually led to the project becoming a mess, but at the time we never chose to do anything about. It’s almost always a case of deferring better solutions or a round of refactoring to some point in the future. “I’ll knock this up now and come back to it later.”. The problem is that later never comes. This is the essence of technical debt. You may only go into debt by a fraction, but do it a few times and eventually all those fractions add up. Until one day when you go to check your balance, you find yourself swimming in the middle of the ocean with no land in sight.

Implementing a broken window policy can go a huge way towards keeping a project healthy. If there is a broken window (bad code) fix it as-soon-as-possible. It doesn’t have to be that instant (although if you can, you should), but fix it. Part of the policy also means trying not to break windows yourself. Write the best code you can, as often as you can. Set the benchmark of quality for the rest of the team, even if they don’t follow suit. The danger is that many people are very “me too” about things. “Well if such-and-such can do it like this, then so can I *hack* *hack* *hack*”.

Of course we all write crap from time to time. TBH most of the stuff I write is crap. But I honestly feel more motivated to work on code that’s been loved and looked after, rather than something that’s hanging together by a thread.

Essential reading for developers

I’ve been meaning to write up a list of what books I think every developer, aspiring or seasoned should read. So let’s cut to the chase, and in no particular order:

Code Complete
If there was ever a bible for coding, this is it. It’s even Bible sized. A nice size to chuck at those annoying developers who just have no clue.

Clean Code
I would consider this book the “Ten Commandments” of coding and compliments Code Complete very very very well. If Code Complete teaches you how to be a Christian, then Clean Code teaches you how to be Jesus.

Refactoring to Patterns
What I love about this book is that it you learn the fundamentals of refactoring at the same time as design patterns. The GoF Design Patterns book is quite heavy going. The examples aren’t well laid out and can be confusing especially if you’re not familiar with SmallTalk The examples in refactoring to patterns all take pretty familiar real world bits of code and walk you through the process of refactoring them into sensible patterns.

Three books? Is that it? Yup. In my mind those are the only three books that are essential reading, no matter what form of development you do. If you even remotely care about coding, then go to Amazon now and buy these books. Read them and take a good long hard look at your own code. If on the other hand you feel “You can’t be bothered” to read, learn and improve, then why are you doing something you don’t love or care about? You’re in the wrong industry if you’re not prepared to take time, all the time, to learn new things. Once you’ve read those, then you’re ready to move onto more specialised books. Here are some of my other favourite development books from over the years:

The Productive Programmer
The Art of Agile Development
Practices of an Agile Developer
Joel on Software
Unix Power Tools
Programming Perl
Essential Java
Well Grounded Rubyist
Design Patterns in Ruby
CSS Mastery
Prioritizing Web Usability

Don’t use PHPMyAdmin. SSH tunnel instead.

If you’re still using phpMyAdmin to admin your remote database, then you’re doing it wrong. Don’t expose your database to the outside world like this, instead use a SSH tunnel. In your terminal simply create the tunnel:

Then in your MySQL interface of choice just connect to 127.0.0.1 port 8888 and voila, you’ll be connected to your remote database.

Apps like Querious even let you setup the connection internally without having to tunnel through in Terminal.

Law of Demeter and the delegate method

The Law of Demeter, or Principle of Least Knowledge is a fairly simple design pattern, which, simply put means that an object should only talk to it’s immediate “friends”

The law states that a method M of and object O may only invoke the methods of the following kind:

1. a method on O itself
2. any parameters passed to M
3. any objects instantiated within M
4. any direct components of O

The classic example coined by David Bock used a Paperboy (one object) delivering a paper, then extracting money from a Customer’s (another object) Wallet (and another):

In the “real world” the Paperboy would ask the customer for the money who would then take it out for them, rather then the Paperboy reaching into the customer’s back pocket and getting it for themself.

Really we want something as follows:

This may all seem trivial and a waste of time, but what happens if some Customers want to pay by cheque? Those decisions should have an impact on the Paperboy, otherwise we end up with:

Where as it makes more sense for the change to be contained within the Customer:

So what does this have to do with Rails and the delegate method? The delegate method adds a quick and simple way of following the Law of Demeter without having to do very much at all.

This setup means to get an Order’s payment we would have to say:

But if we simply change our objects as such:

Now all we have to say is:

So at any time, the details of how a payment  is to be decided can be contained with the Customer. This is of course a simplistic example, but hopefully explains how you chould be using this handy feature.

From TextMate to Vim

I’ve finally done it. After months and months of on-off usage of Vim, I’m now finally using it 100% of the time. It’s been a long and hard road getting here, but let me tell you, it’s been well worth it. I now feel like I absolutely fly through my code. I’ve read many a time, people saying that watching someone using Vim is like watching something mystical, and I can see why. Looking at how I edit code in Vim now, makes me feel clumsy when I think back to using other editors like TextMate. Don’t get me wrong, TextMate is a wonderful editor, but there is just something about the speed and finesse of editing in Vim which I have just fallen in love with.

I wrote about trying MacVim before and how I just felt it lacked the spit and polish that TextMate does. But now, I can’t remember why I originally felt that way. There’s a simple elegance to the Vim, yet with this awesome power available to you. Switching wasn’t easy in the slightest. I would load Vim up for an hour, tinker around, get frustrated and go back to Textmate. Then a month later I’d try again, learn a new command, last two hours and go back to TextMate. A few more months and hours turned into a full day, then the full day turned into a couple of days, and then I never looked back.

One of the keys to hitting the ground running is having a good config. I originally used jferris‘s vimfiles but moved to scrooloose’s files not long ago. It practically has every plugin you could ever need to make life in Vim sublime.

Some other handy references I’ve used along the way have been vimtutor, the Vim Recipies Cookbook, the Vim Tips Wiki. To aid my own memory of useful commands I’ve even started my own Vim tumblr.

Vlad 2.0 Not Finding Tasks in deploy.rb

When I restalled all my gems on Snow Leopard, vlad refused to find any of the tasks I had defined in my deploy.rb. I thought this was a SL issue but turned out a week before it’s release Vlad had been updated to version 2 which used a new plugin system. Looking for vlad rake tasks returned an error:

To solve the problem just required an install of the new vlad-git gem.

Now all my tasks were appearing properly. Vlad 2 always brought around a few changes in it’s deploy.rb and use. Here is my deploy.rb for reference:

Now invoking Vlad for my staging environment works as such:

The Code Shall Set You Free

I was recently asked why I don’t comment my code. It’s a fair enough question. There was a time when commenting your code was the done thing. I was once a great believer in commenting code as much as possible and would bash those that didn’t, but now I vary rarely comment my code at all. In my current project of over 1,500 LOC, there are only a handful of comments. Many people will argue this is irresponsible. Well how is anyone supposed to pick up and understand my code, if it’s not commented?

The code should comment itself.

That just sounds silly. It’s like saying a car should drive itself. But it can be done. A lot of this change of heart about comments has come from my commitment to becoming a better developer and spending countless hours reading about the practice of great development, which is something I’ve written about in the past. I’m a big believer that most of the time if you need to comment a piece of code, then it’s either bad code or too complicated. Of course that’s not true 100% of the time, but for the other 99% it really is. There are cases where things need to be explained and especially warned of, but a lot of the time, commenting is just an easy escape from having to do “proper” coding. It took me years and years to get a basic understanding of proper OO and I’ve still got a long way to go to reaching Journeyman levels of understanding, but I would always create large objects with huge and complex methods, when really what I needed were more concise classes with more responsibility for what they should be able to do. It’s not object orientated when you’re focus is on the method and not the class.

A simple example of commented code:

Most comments can be done away with. If we split out functionality into more concise bits, then just reading the code should explain what’s happening better:

This isn’t a great example as once again the validation of whether the food can/will be eaten should move into it’s own method or class ever. If we’re follow Uncle Bob’s SOLID principles, the above examples breaks the OCP (Open Closed Principle) where entities should be open to extension and closed to modification. If more validation rules were needed, then that would require the code to be modified.

rake spec fixtures failing

For some reason my rspec fixtures were not loading into my development database when doing spec:db:fixtures:load. An extra parameter to db:fixtures:load is all that’s needed.

Fixed by:

So you want to be a developer?

I’m so glad that I’m not just getting started as a web developer these days. Facebook is the main example I give to people when talking to about this. It has set the standard for what and how people think a web app should behave. Move forward or backwards through photos and they are dynamically loaded without refreshing the page. Send someone a message and a modal box appears with autocomplete on the textboxes. You can browse the site, chat to friends and do all sorts of stuff without ever having to experience a page refresh. I even remember when they added AJAX to their photo albums. I mentally flipped as it made the site so much more usable. I showed it to someone going “Look! Look! There’s no page refresh.” while they just shrugged and went “I don’t see what you mean.”, D’oh… exactly! The sort of stuff no one even realises is happening. But I’m sure they’ll feel the difference if they use functionality on your site that’s similar to something Facebook does, but which requires a refresh where as Facebook doesn’t. Even I feel the pain of moving forward and backwards through photos on Flickr. After the third or fourth page refresh, I just give up.

When I got started, web stuff was so new and so simple that in hindsight it was amazing what you could get away with. You could just fly by the seat of your pants. I know I did. The first piece of web development I ever did was back in the mid nineties two days before my first interview. I wrote a Java servlet that simply took a single text parameter and queried a MySQL database using JDBC. I showed it at the interview and got a job as a web developer using Perl. I didn’t even know the Perl but still got the job. All I had to do, day-in, day-out was write HTML and scripts that responded to clicked links or submitted forms. Submit, refresh and display the result, job done, I can go home now. Creating a site wasn’t hard, almost anyone could do it and almost everyone was at the time. Life was simple and it was pretty much a level playing field. Now though, it is a totally different ball game. You’ll need good knowledge of at least a couple of languages, HTML, CSS (Yes we need it to work across all the major browsers), SQL, Javascript + a framework like jQuery + how to use AJAX.

There is just so much that you need to know that if you’re not doing this in your spare time, how are you supposed to ever compete with the kids nearly half your age who can already do this stuff with their eyes closed. Even me, who does this stuff every day as a job has to learn more and more if I even want a chance of staying relevant and employable. I love learning, so it doesn’t bother me. Programming still turns me on and it has to if you ever want to make a go of doing this for a living. Sometimes you can be in the fortunate position of working for a company that really loves this stuff, so you can learn and grow, but I suspect the majority of IT related jobs are done in companies where IT is a second thought to their overall business goal. Where managers prefer to say “no” to your ideas rather then say “ZOMG we could totally awesomely AJAX dis bitch up!!!11!”. And the learning doesn’t just stop at work related subjects. There’s a lot to be said about learning new languages and techniques totally unrelated to your work. Not only for the mental stimulus but also how they can teach you to approach a subject in a new way. I admit this is perhaps one area where I don’t spend enough time, but I’m trying. So go forth and learn. Be totally fucking awesome.

RSpec + Autotest + Growl + Doom Guy

I spent this morning playing around with autotest, but was getting really flaky results with the Growl notifications. I tried about four different autotest configs, but none of them seemed to consistently worked. I remembered that the Growl notifications at Thursday’s Coding Dojo worked pretty well, so after some digging around I found the config on their github. After a tiny tweaking I was even able to get it to work with Przemysław Kowalczyk’s Doom Guy. I’ve packaged it all up and put it on Github. Enjoy.

doomguy-growl-autotest

Goodbye Grails

It finally came time to un-subscribe from all the Grails feeds I used to read. As I’ll no longer be doing any Grails it makes little sense to really keep up with what’s going on in the Grails world. Grails has a lot going for it, but even after over a year of doing it, it just never felt as smooth or dreamy as Rails always has. It managed to replicate some of the core that made Rails so wonderful to begin with and did a good job of it most of the time. Perhaps if I had more experience of the Spring and Hibernate core I could have got more out of the Framework, which is fine and that is on my head, but in the end it just got more and more frustrating as features available in Rails were just impossible at the time in Grails. I’m not saying that Grails is lacking, as at the end of the day, there’s nothing you can do in Rails that you can’t replicate in Grails.

In hindsight I was perhaps the wrong audience. Groovy/Grails is the perfect Java answer to Rails. I chose it to stay consistant with our other apps, so that everything ran on the same JVM and was all containted within the same application server. There were no constraints on the technologies that had to be used. Consistancy, perhaps, was the wrong reason to choose it. Maybe I should have chosen it if I had more knowledge of Spring and Hibernate. Maybe I should have chosen it if I had to to run in the same server and on the JVM. Who knows. I wish the Grails team all the best. Who knows, I may end up coming back to it one day. Stranger things have happened.