I’ve recently been thinking of what differentiates a good from a bad programmer. Often people have used words like “elegant” and “simple” as ways of describing attributes of a good programmer. Though surely we can come up with a physical analog to draw a better comparison. Personally, I’ve found the analog to be cooking because it’s easy to tell a bad (or junior) cook from a good one.

Previously I was training in the military as a cook, so I’ve taken several courses that taught various skills such as organization, discipline and of course; how to work in a kitchen. Much of the kitchen work heavily revolves around how one treats their workspace. Of course this is important to ensure that the kitchen is safe and that there is no contamination, which can lead to extremely disgruntled clients. While my profession has drastically changed, I still take those lessons from my culinary experience and apply it to my own kitchen.

When it comes to my own kitchen I’ve noticed a pretty big disparity between how my partner and I prepare our meals, that being while she’s really good at creating the end product, the side-effects of her cooking are rather… messy. Anyone can be a good cook, it just takes a bit of discipline and the desire to keep your space as clean as possible. This of course includes things like having a sink full of hot, soapy water so that in between steps you can clean the tools you just used.

So you’re probably wondering what does any of this have to do with programming? Well if we compare how a good and bad programmer works, it’s quite similar to working in a kitchen. We all start with a clean slate and start combining the pieces to create the end product, though the good programmer will continue to return to their code and find ways to improve upon it. This can be anything from modularizing code, to simply taking a piece of code and making it simpler to follow.

A bad programmer on the other hand will leave their solutions because “it works” and they’ll get back to it eventually. The problem with this is your workspace gets more and more cluttered, increasing your chances of having your code contaminate other parts of the codebase and before you know it, your system is sick. Now you’re stuck with a semi-working system that they cannot understand because of all the short-cuts and bad decisions that were made but never taken care of.

Now, I do believe that like a bad cook, a bad programmer can be taught the proper way to build things. Just like trades people need to spend several thousand hours as an apprentice, developers also need to do this. Without the correct mentorship we are never given the guidance we need to grow into a good developer. Well, perhaps that isn’t entirely true, you’ll still have the chance to grow though it will take a bit longer and you may also build up some bad habits.

 

So it’s been about 3 years since I made the switch over to Macs, and I’ve been pretty happy with it. I have shell that doesn’t suck and all the goodness that comes with a UNIX-like operating system. The one thing that’s always bothered me a bit is the lack of good tiling window management. About 6 months ago I played with xmonad for a bit and really loved it, even to the point where I tried using it in XQuartz on Mac (which turned out to be a terrible experience).

I’ve somewhat managed to get away with it by using emacs for the most of my editing. While not of the same calibre as a TWM like xmonad, it gives me that frameless experience I like. The one disadvantage is the lack of a shell I could use (if there’s something better than eshell, OH PLEASE TELL ME!) so I’ve typically had emacs using 80% of my screen, and an iTerm window using the other 20%… or something. It’s been alright, though I hate having to switch out of one application into another run something then switch back, etc etc. This is where I decided to take the plunge and give tmux a shot.

For those who don’t know about it, tmux stands for “Terminal Multiplexer” and allows you to have multiple terminal sessions running, sort of like Spaces or Virtual Desktops except entirely text based. They also allow you to disconnect from a session while not actually killing the processes, which is useful for things like running something on a server (upgrading stuff, or running a really long query where timeouts may be an issue). The connecting/disconnecting part has been a pretty awesome life-saver for myself where I have a tendency to lose context and kill or close the wrong application which is most often my editor.

Along with the session management there’s the window or pane aspect as well, which I really just use as a tiling manager. It’s not as advanced as xmonad, but I’m spending more time in a single application (iTerm) where it’s drastically easier to switch between my applications.

Of course everything isn’t perfect! I still haven’t figured out how to get stuff from emacs into my clipboard, which kinda sucks though aside from some sort of minor issues like this, I’ve been pretty satisfied.

 

I’ve been using a certain Podcast application for a while, and I have it configured in such a way that it will only do updates on wifi and at 9:30 in the morning.  I have a tendency to only be connected to 3G so this leads to some pretty frustrating experiences.  Primarily, I’m getting notifications that updates couldn’t happen then I’m directed to a screen with no way of actioning on these problems.  Alright, so the software isn’t that great… but it’s sadly the best for what I need.

Though, I feel this software could be vastly improved if only the developer took a few steps to gracefully handle things such as connectivity (let’s admit it, lack of connectivity isn’t an exceptional case, it’s an expectation).  Add in configuration such as “Only download over WiFi” well now you’re going to need to elegantly handle how an update is performed.

In my app, STO on the Go I needed to perform daily updates though there’s a good chance that when the scheduled task hits the user may not have an internet connection (or only want to download updates over WiFi).  Awesomely, Android is a really loud system.  It’s yelling things **all** the time about various status changes, one of these being connectivity status changes.  I figured I would tie into this.

Tying into these services is extremely straightforward, first we need to tell our manifest that we want to listen in on some BroadcastIntents:

<receiver android:name=".receiver.ScheduleUpdateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

So now our <pre>ScheduleUpdateReceiver</pre> will get called each time the state of connectivity changes on the device. Keep in mind, you are going to need to keep the code as lean as possible until you are absolutely sure you need to do some heavy lifting! Nothing is more frustrating than an app that appears to be doing nothing but kills your battery.

Now it’s time for our service to actually do some stuff, this is where we will be asking a few questions.

 

public void onReceive(Context context, Intent intent) {
	ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	String doUpdateOnNextWifiConnection = context.getString(R.string.doUpdateOnNextWifiConnection);
	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

	if(!prefs.getBoolean(context.getString(R.string.performDownloadsInBackground), true)) {
		// User configuration -- No background Updating
		Log.d(DEBUG_TAG, "Updates are not permitted to run. Aborting");
		return;
	}

	boolean hasActiveWifiConnection = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();

	// Check to see if the intent that was fired was created by Android itself
	if(intent.getAction() != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
		// Did the last check fail due to lack of connectivity?
		boolean performUpdateOnNextWifiConnection = prefs.getBoolean(doUpdateOnNextWifiConnection, false);
		if(performUpdateOnNextWifiConnection && hasActiveWifiConnection) {
			runUpdate(context);
			// Alright, our update has run, time to reset our state so we don't attempt to download
			// another update next time the device gets an internet connection.
			prefs.edit().putBoolean(doUpdateOnNextWifiConnection, false).commit();
		} else {
			Log.d(DEBUG_TAG, "Update for connection to wireless access point will be ignored");
		}
	} else {
		// This is our scheduled update
		boolean canDownloadWithMobileData = prefs.getBoolean(context.getString(R.string.usenetworktype), true);
		boolean hasMobileDataConnection = (telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED);
		if((canDownloadWithMobileData && hasMobileDataConnection) || hasActiveWifiConnection) {
			runUpdate(context);
		} else {
			// So, we either don't have an internet connection or the user wasn't connected to WiFi when the scheduled
			// update was supposed to happen.
			// I chose to store this information in the shared preferences because it's pretty easy to do.  This could get
			// a little bit out of hand if you have more complex rules than what I have here.
			Log.d(DEBUG_TAG, "Cannot do a download over data and we don't have a wifi connection. On the next wifi connection, we'll do the download then");
			prefs.edit().putBoolean(doUpdateOnNextWifiConnection, true).commit();
		}
	}
}

So now we are able to handle the sort of special cases and deal with them almost immediately after a user has acquired a usable connection to the internet.

 

I gave myself a personal goal around mid to late November; to finish an STO Android app with the dataset that Phil Casgrain had given me access to.  The app is now available on the Android market as STO on the Go though it’s almost impossible to find using the search.

I’m selling the app for $1.00 though there is a good chance it will be getting an increase in the next version, which will have at least maps and favourites features.

 

As I mentioned earlier I decided to start playing around with Clojure on my Windows box. This was an excellent way to get a quick introduction to the language, although there were aspects of the Windows platform that made going any further than toying around somewhat pointless. Although, this could simply be my bias towards Unix style systems.

When I decided to set up clojure on my Ubuntu installation, it felt like there was a huge wall in my way that made absolutely no sense. This was really because I had made a few mistakes when installing my editor of choice (emacs) from apt. That being, I had installed various emacs plugins such as swank and slime which caused some really frustrating problems to arise when running swank-clojure. I found in the end, the easiest thing to do is get a full install of emacs going, without any extra bells and whistles; that’s what the ELPA is for, and it does a damn good job at it.

Once my emacs was back to a good state, I was able to get the clojure-jack-in function to work the way I was expecting it to. Finally I was able to get hacking! On the windows box, I was (and still am) doing a text adventure game from the Land of Lisp book. I’ve found this to be an excellent way of stepping into the language, especially since the book assumes you are using common lisp. This has lead to a fair amount of research into finding out clojure equivalents to CL macros. Meanwhile, on my Ubuntu machine I’m working on a project that I’m hoping will make one part of my life a bit easier.

I’ve found that when it comes to doing tasks, such as groceries, it can often be a pain. My partner and I use our phones for entering our grocery list and each time it’s excruciating. These keyboards are annoying to use, our Nexus ones have those poorly placed heat sensitive buttons that your thumbs always manage to hit, and the program we are using doesn’t learn very well. So I’ve decided that the first step in making this better would be to have an application that makes at least entering the data easier. I’ve decided that I’m going to implement this tool using Clojure, because I’ve found I’m loving the way you do things in the language (it feels more mathematical). I also feel that since I’m extremely green with the language that I’ll be required to keep things simple (I still cannot get [& args] working for whatever reason!).

In an attempt to keep things simple, I’m avoiding the database… well that’s a lie. I’m avoiding the Relational database. I’ve always found that when I use a tool like Rails I tend to over-complicate my models for whatever stupid reason and it just leads to me abandoning the project.  I’m also interested in playing with document stores (in my case MongoDB) since I love to use hashes/JSON.  It just so happens that there is a library called congomongo which is pretty easy to setup and start playing with MongoDB. Once I’m done getting this part of the application working, my next plan is to play with the Noir microframework (similar to Sinatra or Flask) to implement my web app.  If I decide to continue working on this, it probably won’t scale all that well, but at least it’s simple enough to not overwhelm me at first.

 

A while back a friend of mine suggested I should get into programming some clojure. I figured I would, but wanted to get my environment working. This included all of the setup for emacs to get slime, swank, leiningen, etc working, which I still cannot really get working.

I was looking around for something that would at least get me knocking out some clojure code before I commit any efforts to actually getting my environment working on. I discovered this awesome prebuilt package called Clojure Box. I don’t really know what is all there, but at least it got me up and running with clojure so I can play around in the REPL while learning the language.

I am a bit bummed that the tool is windows only, but it’s not a big deal for now since all I’ve really been doing is writing snippets in buffers I’m probably going to throw away.

As for learning the language I’m starting to follow this introduction to clojure guide I found. It *really* covers the basics, but every time I try to jump too far ahead in new languages I just get lost and confused anyway.

 

As part of my day job at Shopify I’ve been implementing a new front end using the language CoffeeScript. Originally, the front-end was regular JavaScript, but since Rails 3.1 will be supporting CS we might as well start using it.

As a whole, the language isn’t that bad. I do appreciate many of the helpers it provides for enumerating hashes and arrays, and bindings (aka fat arrow) are awesome. It’s made writing some complex client code that relys on context far easier, especially since the new features like .bind aren’t available on most (if any) mobile devices (although this is easily fixed with something like 5 lines of code).

My main complaints about CS are with some of the edge cases it has. For example, I needed to have a bound anonymous function within a setTimeout. In JS I would typically perform something similar to:

setTimeout(
  // May be a little bit off here, but I think that's how to do ECMA5 binds
  function(){ this.doSomething(); }.bind(this),
  150);

The above is fairly straight forward, and the language doing anything I’d consider unexpected. Though if we were to do the same thing in CS, I’d expect it to be something like this:

setTimeout( => @doSomething(), 150)

This actually doesn’t work, the coffee compiler will complain. It’s somewhat understandable, there some weird stuff going on here and it’s difficult to parse. A solution I often used was this:

setTimeout( (=> @doSomething()), 150)

Now I have all these extra brackets that I shouldn’t need, and it’s frustrating because I’m trying to use th language the way it seems to have been designed. Now this had been bothering me for some time now, and decided to twitter rage/complain about it. This did get some attention from someone who runs the CS twitter account who gave me some suggestions. Those of which I found to be somewhat hacks, or wouldn’t work in my case.

One solution was to have (in my case) the fetch method bound to the products instead of having a fat arrow function declaration. Now, since the actual model that products Points to is a Spine model, I really don’t feel like going in and hacking something (that already works the way I want/expect) for such a minor (but annoying) problem with CS. Another solution was to essentially create a function that is in essence setTimeout but reversed, so it’s something like:

delay = (delay, function) ->
  setTimeout(function, delay)

Which I’m also not super keen on, once again it’s going through a bunch of extra steps to fix an inherent problem with the language itself. Now I often do mix up the arguments used in setTimeout, and I would love to see that get fixed/added in the future.

I mentioned the problem I was having to one of our awesome (and way smarter than me) interns about it and he actually came up with an almost perfect solution.

setTimeout( =>
  @doSomething()
,150)

Aside from that preceding comma and needing to remember to un-indent, it’s not a big deal and I like that I’m not having to go in and hack apart Javascript to fix minor issues.

Although I do seem to be a bit bitter about my experience with CoffeeScript, I do have to say that I like what the language is bringing to the table, I just hope it gets some improvements for CS 2.0 or something. Perhaps having some kind of explicit scope declaration (like begin end or curly brackets), would help out a fair amount. Though, I think I can keep dreaming for having curly brackets, there seems to be some kind of aversion towards them.

 

I’m really curious to know why initializing objects, primarily Hashes (maps, dictionaries, key-value lookups, whatever you want to call them) are such a pain to initialize.

In your typical Java scenario this is how you initialize your Hash:

HashMap hashyMcHash = new HashMap();
hashyMcHash.put("foo", "bar");
hashyMcHash.put("car", "jar");
hashyMcHash.put("arr", "rawr");
// And... so on

Meanwhile, most sane languages allow you to do crazy things like this:

hashyMcHash = {foo: "bar", car: "jar", arr: "rawr"};

Now, in languages like Python, Ruby, JavaScript those are just parts of the language and you kinda get them for free, so I can understand something like that not being available in Java. Now, lets look at another statically typed language that I think took a fair compromise between how to initialize a Hash.

NSDictionary hashyMcHash = [[NSDictionary alloc] initWithObjectsAndKeys: @"foo", @"bar", @"car", @"jar", @"arr", @"rawr", nil];

To me this seems like a pretty fair compromise for initializing our Hashes since it allows me to state what some default values in it will be in code that is fairly readable. I have an idea of how one could do it in Java, though don’t know if it exists or not.

// Constructor would probably look like this:
// HashMap(K[] keys, V[] values)
HashMap hashyMcHash =
                new HashMap(
                    ["foo", "car", "arr"],
                    ["bar", "jar", "rawr"],
                );

If this does exist, please let me know because I’d really love something like this. If it doesn’t… why?

 

So let’s say you have an application where you need to store the users password. Perhaps it’s a configuration setting that they need to use to log into some service you use or have created. The easiest (and most insecure) way to store the password would be to use the SharedPreferences for your application.

So in our preference XML we have an EditTextPreference which will be used to store the password. Though, we need to do a few things first otherwise the password will be plainly visible and there is the chance that the password might get saved in the auto-complete for the keyboard (SwiftKey is particularly bad for this).

For sake of argument, lets say our preferences xml is called “preferences.xml” and the key for the password is “password”.

What you will need to do is the following

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MyPreferenceActivity extends PreferenceActivity implements OnPreferenceClickListener {
    private Preference passwordPref;

    public void onCreate(Bundle icicle){
        super.onCreate(icicle);
        addPreferences(R.xml.preferences);

        passwordPref = findPreference("password");
        passwordPref.setOnPreferenceClickListener(this);
    }

    public boolean onPreferenceClick(Preference preference){
        if(preference.getKey().equals("password")){
            EditTextPreference pref = (EditTextPreference) preference;
            EditText field = pref.getEditText();
            // This informs the keyboard not to show up the autocomplete.
            // Ensure that you have set this input type, otherwise users
            // may complain that your application is saving their passwords.
            field.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            // This gives us the masking that you see in your password fields
            field.setTransformationMethod(new PasswordTransformationMethod());
        }
        // We still return false so that the system will handle everything else.
        // We just needed to ensure that if this preference is the password pref
        // that it's properly protected from prying eyes.
        return false;
    }
}

And there you have it. With this in place, entering password with the on-screen keyboard won’t show any text or save it.

As I mentioned earlier, this doesn’t save the passwords safely to the device. On a normal device this isn’t that much of a concern, though you should probably inform your user that the passwords are not encrypted. This issue becomes a bit more serious if there is malicious software on a device that is also rooted, since the naughty app could scrape through all the data directories looking for usernames and passwords stored in preference files.

 

For an application I’m working on I needed to create a slider that would allow the user to easily create custom colours. While trying to look around on the internet The most common response was the following:

There is no “slider” component in the BlackBerry API — you’ll have to invent it.

Or this:

The GaugeField can be used for user interaction. With the field focused, the user can press Alt and roll the trackball to change the slider value. Alternatively, the user can press the menu key and choose Change option, which will bring up a dialog with instructions for changing the value.

I’m sorry, but the first solution is kinda bullshit, and the second one sounds like a good way to get a bunch of support tickets from your users saying that your application doesn’t work or is broken or something. Shit I don’t want to deal with.

Anyway, I decided to go out and create a SliderField for the BlackBerry which you can go ahead and use. Currently it displays the slider dongle/widget in blue if it’s inactive or red if the field is in focus. Ugly as old hell, but it’s pretty easy to replace that with something prettier looking.

package com.zeebu.colorgo.field;

/**
* This is released under the public domain, but feel free to give credit to Chris Saunders if you want.
*/

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.XYRect;

public class SliderField extends Field {

    private static final int MAX_SLIDER_SKIP = 20;
    private static final int BASE_SLIDER_SKIP = 1;
    private static final int NAVIGATION_TIME = 300;

    private int sliderWidgetColor;
    private int scaleColorAtMin = Color.BLACK;
    private int scaleColorAtMax = Color.LIGHTBLUE;

    private int fieldWidth;
    private int fieldHeight;

    private int min;
    private int max;
    private int currentValue;
    private long lastNavigationTime = 0;
    private int sliderSkip = BASE_SLIDER_SKIP;

    private int[] xPts;
    private int[] yPts;
    private int[] colors;

    public SliderField(int min, int max, int sliderWidth, int sliderWidgetHeight) {
        super();
        this.fieldWidth = sliderWidth;
        this.fieldHeight = sliderWidgetHeight;
        this.min = min;
        this.max = max;
        this.currentValue = (max — min) / 2;

        xPts = new int[] {0, 0, fieldWidth, fieldWidth};
        yPts = new int[] {fieldHeight / 4, (fieldHeight * 3) / 4, (fieldHeight * 3) / 4, fieldHeight / 4, };
        colors =  new int[4];
        updateColorsArray();
    }

    protected void layout(int width, int height) {
        setExtent(fieldWidth, fieldHeight);
    }

    public boolean isFocusable() {
        return true;
    }

    public void drawFocus(Graphics g, boolean on) {}

    protected boolean navigationMovement(int dx, int dy, int status, int time) {
        if(System.currentTimeMillis() — lastNavigationTime < NAVIGATION_TIME) {
            sliderSkip *= 2;
            if(sliderSkip > MAX_SLIDER_SKIP) {
                sliderSkip = MAX_SLIDER_SKIP;
            }
        } else {
            sliderSkip = BASE_SLIDER_SKIP;
        }
        lastNavigationTime = System.currentTimeMillis();

        if(dx > 0) {
            currentValue += sliderSkip;
            currentValue = (currentValue > max) ? max : currentValue;
        } else if(dx < 0) {
            currentValue -= sliderSkip;
            currentValue = (currentValue < min) ? min : currentValue;
        } else {
            return super.navigationMovement(dx, dy, status, time);
        }
        invalidate();
        fieldChangeNotify(0);
        return true;
    }

    public boolean touchEvent(TouchEvent event) {
        int message = event.getEvent();
        int touchX = event.getX(1);
        int touchY = event.getY(1);
        if(message == TouchEvent.DOWN || message == TouchEvent.MOVE) {
            currentValue = determineCurrentValue(touchX);
            invalidate();
            fieldChangeNotify(0);
            return true;
        }
        return false;
    }

    protected int determineCurrentValue(int positionInField) {
        float ratio = (float) positionInField / (float) fieldWidth;
        return (int) (ratio * max);
    }

    protected int determineWidgetXPositionOnSlider() {
        float ratio = (float) currentValue / (float) max;
        ratio = (ratio < 0.0) ? 0.0f : ratio;
        ratio = (ratio > 1.0) ? 1.0f : ratio;
        return (int) (ratio * fieldWidth);
    }

    protected void paint(Graphics graphics) {

        graphics.drawShadedFilledPath(xPts, yPts, null, colors, null);

        int cX = determineWidgetXPositionOnSlider();
        int cY = fieldHeight / 2;
        int pX = cX + (cY);
        int pY = cY;
        int qX = cX;
        int qY = cY + (cY);
        int startAngle = 0;
        int endAngle = 0;

        graphics.setColor(Color.BLUE);
        if(isFocus()) {
            graphics.setColor(Color.RED);
        }
        graphics.fillEllipse(cX, cY, pX, pY, qX, qY, startAngle, endAngle);

    }

    public int getCurrentValue() {
        return currentValue;
    }

    public void setScaleColorAtMin(int scaleColorAtMin) {
        this.scaleColorAtMin = scaleColorAtMin;
        updateColorsArray();
    }

    public void setScaleColorAtMax(int scaleColorAtMax) {
        this.scaleColorAtMax = scaleColorAtMax;
        updateColorsArray();
    }

    public void updateColorsArray() {
        for(int i = 0; i < colors.length; ++i) {
            if(i < colors.length / 2) {
                colors[i] = scaleColorAtMin;
            } else {
                colors[i] = scaleColorAtMax;
            }
        }
        invalidate();
    }

}

Here is a little preview of the sliders:
SliderFields in Action!!!

© 2011 Christopher Saunders Suffusion theme by Sayontan Sinha