Posts

Ways to modularize your Ruby code

In this post, I'll recommend several ways to properly organize code in Ruby projects. I'll also explain my reasoning and how I arrived at each solution. Much of this builds on the excellent work of others in the Ruby community, and I've linked to these other writeups as appropriate in case you want to know more. This subject is of particular interest to anyone who is packaging a gem library, but it should be handy to anyone who wishes to organize code within any Ruby project. Namespacing with modules Let's say you've got an isolated piece of functionality that doesn't depend on anything else, such as a simple key (random string) generator. You intend to always call it with its full namespace, so you don't get it mixed up with similarly named functions. To make something that you can call using Rigatoni::KeyGenerator.generate_key(n) , you'd use the following code. module Rigatoni module KeyGenerator def self.generate_key(key_length = 5) puts ...

JavaScript: Checking for undeclared and undefined variables

Up until now, the JavaScript I've written has typically been in pursuit of a bigger goal. This means that I worked around language quirks on the spot and moved on. I never stopped to consider the nitty gritty details of the language for commitment to long-term memory, because I wanted to get a working end product. Recently, someone asked me about the best way to check for undefined JavaScript variables. I found myself at a loss, which was alarming to me since doing these kinds of checks is immensely important, practical, and a frequent fact of everyday programming no matter what programming language you're using. The fact of the matter is that most of the time, I know where my variables are coming from. Something like this would work: var x; if (x) x.some_method(); else alert("we can't use x"); In the vast majority of cases where I had to perform a null check, I knew that the variable was declared somewhere because it was of my own maki...

The status quo

Sometimes there are good but non-obvious reasons for keeping the status quo. Competing interests may have, over time, been balanced and counter-balanced to form a functioning ecosystem. And as with any ecosystem, reducing the functioning whole into its constituent parts in the foolish pursuit of extracting isolated benefits is an intractable problem. Other times, the status quo represents a deeply flawed system, fundamentally broken at the core. Such a system is characterized by people in power whose actions are driven primarily by the overriding interest in preserving their own favorable position, to the recurring detriment of the less favored. The tough part is looking at a situation and making the call as to which one of these models applies. In some cases, the status quo may be made up of both a well-balanced system with benefits to all, as well as a rotten portion entrenched for no good reason but the preservation of the holders of power. Fixing what's broken is a separate pro...

Slowing down as an immersive experience

Through my entire time as a student, I never used Cliffs Notes or SparkNotes in place of assigned reading. I made it a point to read every book I was supposed to, down to the last word. The trouble for me was that everyone else who resorted to these "study guides" knew enough about the real books to do well in their classes. From the perspective of efficiently using my time to reach the objective of a good-enough, basic understanding for writing essays, discussing the books in class, and impressing teachers, I lost out. I remember one book in particular. Crime and Punishment really broke a lot of people, many of whom were like me and had, up until then, insisted on reading the book and not the summary booklet. But I was determined. I was hellbent on savoring that book and milking it for all it was worth — calculus, biology, and economics be damned. As expected, I ended up with the same general recollection of the book's contents as the more reasonable folks who resort...

JavaScript: Variables in regular expressions

Often, you want to look for a particular pattern within a string. Let's say you know that you want to look for the string "revenue" inside a given string. function match_string_for_revenue(string_for_searching) { return string_for_searching.match(/revenue/gi); } var our_string = "We are looking for ReVeNuE."; alert( match_string_for_revenue(our_string) ); You can store the pattern as a regular expression in its own JavaScript variable, which makes your code more readable and its intention better known. function match_string_for_revenue(string_for_searching) { var pattern_to_look_for = /revenue/gi; return string_for_searching.match(pattern_to_look_for); } var our_string = "We are looking for ReVeNuE."; alert( match_string_for_revenue(our_string) ); But what if you want to generalize this matching and be able to search for any given pattern? Can you make it vary based on a parameter given, instead of keeping it in the code? /* NOT GOING TO WO...

The costs of configurable settings in your web application

By and large, the received wisdom when it comes to configurability and flexible settings for web applications is that more is better. Making something configurable frees up the engineer from having to make mundane (but necessary) changes that can be left to other people. It's desirable to change the state of software without having to rebuild or redeploy the code. There are a lot of obvious benefits to making software configurable, and these benefits are plain to all. What I'm going to focus on here are the costs of configurability, based on my experience and observations over five years of writing web applications full-time. These costs apply to other kinds of software beyond the realm of web applications. I just choose to limit the scope of discussion to web apps because these costs manifest themselves the most when there's a fast development cycle and rapid iteration. The following is intended to be a comprehensive, itemized breakdown of the costs of making an applicati...

The reasoning behind Lumberjack

So why, in 2009, in a world of RIA frameworks, web-based applications, and a wide variety of blogging engines to choose from, would I write a desktop application in Java targeted exclusively for one company's proprietary blog platform? First of all, it was tempting to write this as an Adobe AIR application. It would have fit my requirement that it be cross-platform and run as a desktop application, but I've never written anything with Adobe development tools before. Given the limited time I had on weekends to work on it, I wanted to get something written as quickly as possible rather than spending all my time learning a new platform. With Java, I could just hit the ground running, and it was just a matter of referencing the Swing-specific documentation. It boiled down to what was expedient and familiar because it would allow me to build something quickly. With respect to the issue of making this application web-based, the main point is that I didn't want to start up a br...

Introducing Lumberjack, a desktop client for Google Blogger

Earlier this year, I mentioned that I was working on a desktop application, a client for Google Blogger, written in Java with the Swing GUI toolkit. I recently found some time to work on the enhancements that I said I wanted to do during my last update, and I'm ready to release the application to the world. Get a ready-to-run file at the Lumberjack download page . Just download the JAR file, save it, and run it; it will work as long as you have a Java runtime installed. If you're running Windows, Mac OS X, or Linux, you probably do. If you have trouble logging in, you may have to solve a Google CAPTCHA first. You should only have to do it once. If you're a developer, you'll find the source code at the Lumberjack GitHub repository . Simply run ant to build the application. (Yes, I put a lot of effort into getting this one-step build working.) Patches, questions, and suggestions are most welcome. Just leave a comment on this post.

Idealism and retreat

When I'm by myself, when it's quiet with no distractions pulling me in a million directions, I automatically start to dream and envision great things. All of my scattered realizations and fleeting memories somehow just coalesce to give me more clarity about myself and what I'd like to do. It's as if a master blueprint is forming in my mind. It's not a time for questions about implementation or feasibility, but for consideration of what should be done simply because it's the right thing to do. There's no cacophony pressing from without, clamoring that it can't be done or that it's not worth the time, effort, or attention.

Organic thankfulness

I've always had trouble keeping my sentimental cycles synchronized with what the calendar officially sanctions. This year is no different. I got into a very thankful mood early — well before Thanksgiving Day rolled around. Days before Thanksgiving proper, I was working on writing the bulk of my post-wedding "Thank You" cards. True to my high ideals and impractically grand ambitions, I didn't want to just write a generic, canned response to everyone; I wanted each card to be sincere and personalized for each recipient. For I follow the golden rule: "Do unto others as you would have them do unto you." If I am deeply insulted and take personal offense whenever someone sends me a generic message disguised as a customized one, why would I inflict the same on others? Faced with the task of writing so many customized notes to so many people, it was hard to even get started — but good old engineering experience soon kicked in. Whenever I find it hard to get started ...

Automated summaries and excerpts

Image
You've seen them around the web: they're the blocks of text appearing under the headlines, giving you a little more information on what the linked article is about. If the headline didn't tell you enough, the summary or excerpt is supposed to serve as a sort of fall-back mechanism to tell you a little bit more. The websites of such longtime print titans such as The New York Times , The Economist , and The Wall Street Journal tend to have good summaries beneath their headlines. They know how summaries should be written — by hand. They are, after all, the professional producers of such content and have a vested interest in getting that content viewed. Those who are a few steps removed from the production of such content, on the other hand, make it readily apparent that they just don't care. Two of the most surprising offenders are Google and Apple — ironically, two media darlings who appear regularly in feature articles. A quick jaunt over to Google Finance gives us an ...

Finely tuned collective effort

As someone who is rabidly individualistic, working with other people isn't something that's hard-wired into me. For this, I've been chided by friends and family members who hold collective effort up as a sacred cow. They cannot possibly fathom why anyone would question the merits of working together. I remember reading (probably in the Harvard Business Review) that this teamwork mindset is prevalent especially among my generation, which grew up playing team sports and doing group projects in school. Contrast this with the modus operandi of previous generations of workers, who were much more individualistic: put your nose to the grindstone, pull your weight in the organization, and let your merits stand on their own. In this sense, I am very much a traditionalist. But I've been through some fiery projects in school and during my consulting days working with clients. Massive requirements and short deadlines have a way of focusing the mind and forcing the casting aside of ...

Enough with civility: confronting line cutters and queue jumpers

Last Saturday, Sophia and I went to Disneyland to celebrate my birthday and to spend some time together, since our work schedules haven't really overlapped favorably in recent weeks. We were in line for the Matterhorn , and as decent, upstanding Disneyland patrons, we took our places at the back of the snaking line. It was a long line, but it was what one would expect for a Saturday at Disneyland. It was moving at a good clip — faster than the 405 near Santa Monica during rush hour, anyway. About halfway through, a suspicious looking Asian guy wearing sunglasses sidled up next to me from out of nowhere. For a good three seconds, he stood there without saying a word. I thought that he was expecting to be recognized, but upon closer inspection I could recall no previous association with him. When he finally said something, he said, "Hey man, you mind if I get behind you? The line is really long and I don't want to wait in the back." Flabbergasted at the audacity of th...

Vision and chaos

Among the key elements of my father's network of enterprises are the fixer-upper houses which he rents out. As soon as my brother and I were old enough to be of use on these construction sites, Dad would take us along. I hated the messiness of the building process. The floor would typically be littered with drywall chunks. Shattered roof tiles sat in piles on the front yard, and sawdust was sprinkled over everything. When it was all done, though, with everything cleaned up, I felt accomplished for having been a part of bringing about the final outcome. It was more than easy to forget the messy process that brought about the end result: forgetting was automatic. It actually took me conscious effort to remember what it took to get there. While I was in the thick of it, it was discouraging to see the mess in front of me, because it just didn't seem possible that everything could be made right again. All I saw was a seemingly intractable mess. My father, on the other hand, never se...

My automobile's cooling system and its plastic parts

I've learned a lot about my car's cooling system over the past couple of weeks. There's nothing like the prospect of a melted engine to focus the mind. Typically, I would be content to leave it to the mechanic, but the cooling system has many moving parts, and I'm the one who sees firsthand all the symptoms when driving it in various situations. At the very least, anyone in my position would have to take careful note of which circumstances triggered certain events. Such diagnostic tips can help the mechanic narrow things down so that he won't charge you as much for diagnosing the problem. Ideally, we'd also prefer that he fix everything that's wrong with a component as vital as the cooling system. I've had to watch the reading on the temperature sensor, for one. The key is to never let the needle hit the red zone at the top of the temperature gauge. If it does, your engine's head gasket and other crucial parts are in critical danger of melting, dis...

Feisty Ford Focus

People who drive small cars sure have colorful personalities. Yesterday, on the way to work, I saw a Ford Focus with a license plate frame that said, "Don't laugh. It's paid for." It was refreshing to see someone being flashy about their financial responsibility — a quality which is rarely flaunted.

Lessons from refactoring

I enjoy the process of refactoring software — especially software that was written by other people. It forces me to understand things inside and out (which is a tough point to arrive at when all you do on that code is the occasional drive-by bug fix). On top of that, since the desired functionality is known already, it's all redesigning of the data model and writing code. There are fewer product-level questions that come up. The specification is pretty much set. For this particular project, though, I have the unique challenge of making the new design pass muster with multiple parties. People are picky and they always have something to say, so I took special care this time to anticipate any objections and address them so they'd get a better sense of my thought process. I've still had to make changes — and I make them gladly — but I've found that having to explain each decision I'm making generally serves to clarify my thought process. It certainly helps to have some ...

Blogger client as a Java Swing desktop application

Ever since I started using Blogger, I've been looking for a decent, no-nonsense desktop client to write my posts. I personally find it to be a lot of hassle to load up a big, heavy web browser and log in to Blogger to make my posts. (To be fair, Drivel was quite excellent in the past, but doesn't look like it's maintained anymore.) After a little poking around at Google's API documentation, I am pleased to announce that I'm writing this post from a desktop application of my own making. It's a Java desktop application using Swing, so it will run on Windows, Mac OS X, Linux, and any other major desktop platform with a Java runtime. So far, I can select from a list of blogs, write in post titles (to be friendly to those search engines), write post content, and submit new posts. It's really basic, but it's quite a milestone and a major motivator for me to at least have gotten this far. Soon to come on the feature front, I'm aiming for loading old posts ...

The trouble with budget surpluses

The trouble with a government (or any big organization) running a budget surplus and sitting on a big pile of cash is that people start asking questions like, "Why don't we do something with that money, especially since there's so much to fix?" At that scale, having some cash ready for a rainy day is not an excuse that people are able to handle, especially when the quoted figure is in the billions of dollars. Surpluses may seem like a lot of money, although when divided on a per-person basis, they seldom amount to much at all. In this deficit-infested time, it's easy to rail against profligacy in our budgets. I'm not trying to engage in what-ifs here. I'm suggesting a way we can avoid this same problem in the future. We've been told that it's wise to save up for the future, to have some cash on hand just in case — folk wisdom that was reinforced by the big collapses this year. We also know that it's hard for most people to hear about a surplus ...

Small business owners: don't be a jerk

My girlfriend Sophia is an assistant manager at Abercrombie and Fitch , and is thus bombarded with more than her fair share of rude customers. One story she told me this week was about a woman who went ballistic after asking to try on one of the mannequins' jackets and being told no. Now, people are just crazy, and Sophia has told me many stories like this before. What was so different this time? Well, the crazy lady played the business owner card: if it were her store, she would have gladly taken the jackets off the display mannequins. This know-it-all "business owner" then proceeded to hound Sophia for her full name and pressed her for her employee ID so she could file a formal complaint, and refused to go through the normal channels. It is precisely this self-serving arrogance and provincial, narrow-minded ignorance that keeps small business owners from being taken seriously. As a former small business owner myself, I know that the burden is heavy: you've got to ...