Tuesday, March 23, 2010

Software Design Patterns

I'm reading, which is not something I do normally. But I'm reading Head First Design Patterns. Design patterns are templates for solving common problems in software. It's as if I came to you and said, "I have this amazing gadget I want manufactured!" And you might say, "Well Will, you should build a factory!" The pattern is "build a factory". That's a common way to get stuff manufactured. But you can't really make a factory that builds any factory I want, no, you have to apply the pattern yourself, it isn't pre-made.

The first pattern was the Strategy Pattern. This pattern lets you swap out and encapsulate algorithms easily. I might use this pattern if I'm making software for a GPS unit. When the unit ships, the company wants two algorithms availble to determine the route. 1) Shortest distance, 2) Fastest time. If I apply this pattern correctly, it'll be a piece of cake when they come back and ask me to implement a third "scenic route" algorithm. If I suck at applying this pattern, the logic for 1 & 2 will be all strewn about the code, it'll be a pain to sort it out, and adding a third will only make a bigger mess of things.

The next pattern is the Observer Pattern, which I really think of in my head as the Stalker Pattern. The Observer Pattern lets things know when another object changes state. For instance, let's say I have a stalker. The stalker is interested in knowing when I do stuff, so she starts to observe me (via binoculars). When I change state from dressed to clothed, she gets notified (and very excited). Later, she finds out that Justin Beiber lives a few doors down, and she stops observing me, so she no longer knows when I'm wet and naked and when I'm not. Stalker patterns happen in JavaScript ALL THE TIME. I use this pattern with great ease. Think about when a user clicks and drags some movie in his Netflix queue. Here' there's all kinds of code that observe the movie for a state change to "I'm being clicked and dragged!" and they do stuff like show  where you can drag it to, or maybe they update how the movie looks (transparent). The code stalks other code, and when the other code is out of the server, it sneaks in and sniffs its underwear drawer. Stalker code is creepy like that.

The reading is for work. I need to get better at what I do so I can better do what I do. I'm writing about it so that I know I've retained something and that I've processed it. If I can't apply it to code and the real world then I've done a crap job of learning and might as well not waste the time. I think most of the names suck, and the two sentence explanations are too abstract, but the book does a good job so far of working through what it means to use a patterns and where it does or does not apply. If I can be successful in this effort and subsequent ones that are along the same lines it'll be a big deal for me as a software guy, so thanks for listening.

No comments: