melreams.com

Nerrrrd

Strategy pattern

Let’s talk about the strategy design pattern today. According to good old wikipedia, the strategy pattern “defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.” In other words, if you have an object most of its behaviour stays the same but there’s one piece that changes, you want to be able to change that one piece without messing with the rest of the object.

A concrete example would probably help :) Let’s say you’re working on a videogame with monsters that attack the player and you want your monsters to be more aggressive at night and less aggressive during the day. The rest of the monster code like movement and tracking health points or inventory stays the same, it’s just one part of the behaviour that you want to be able to change on the fly. The strategy pattern would let you swap in different “should I attack the player?” algorithms any time and the monster code wouldn’t have to change, it would just call a method on the strategy object it was given.

So how would you implement the strategy pattern? Pretty much the same way you’d implement the bridge pattern, actually. The bridge pattern is about organizing your code and the strategy pattern is about how it behaves (thank you stackoverflow), but the way you arrange your interfaces and objects that inherit from them is largely the same. One difference is that your context class (the one that uses the strategy for something) doesn’t have to change – you could have only one of those and still want to use the strategy pattern. Comparing the class diagrams for the two patterns helps show how similar they are.

Here’s a class diagram for the strategy pattern:

Diagram taken from wikipedia, by Bocsika - wikimedia, CC0
Diagram taken from wikipedia, by Bocsika – wikimedia, CC0

and here’s one for the bridge pattern to compare it to:

By Trashtoy - My own work, written with text editor., Public Domain
By Trashtoy – My own work, written with text editor., Public Domain

If you imagine there’s another ConcreteImplementor, the bridge pattern looks a lot like the strategy pattern. On it’s own I don’t find the bridge pattern diagram super helpful, but in comparison with the strategy pattern diagram it does help illustrate that there are more things that vary in the bridge pattern than in the strategy pattern.

Given that the patterns are so similar, why do we need both of them? Earlier I mentioned that the bridge pattern is about organizing your code and the strategy pattern is about how it behaves. That might sound like a minor difference, but misunderstandings are a huge, huge problem when you’re developing software. It really does help to make it as clear as you can when you’re talking about how you want to arrange your code and when you’re talking about how you want it to behave.

Simple stuff that will make your new team think you’re amazing

Unrelated image from pexels.com to make this post look nicer in social media shares and because Pallas Cats are the best.
Unrelated image from pexels.com to make this post look nicer in social media shares and because Pallas Cats are the best.

Even if you just graduated, there are some simple things you can do to make your new team think you’re amazing, and they don’t even involve any code. Ironically, a huge amount of the stuff that makes someone a really good programmer has nothing to do with sitting down with an editor and writing code. Being an exceptional programmer is as much about making your team more effective as it is about just writing good code yourself.

A big thing that can help your team get more done is to write absolutely everything down when you set up your development environment for the first time at a new job. Everybody means to do this but hardly anyone actually does. No judgement, my current job is the first one where I’ve done a good job of documenting environment setup and it’s my fourth job since graduating from college. If you can, it’s even better if you can write a simple script to set up stuff like environment variables. In some offices everyone gets to choose their own OS and scripts are only so useful, but even a script that only works for one OS at least gives other people something to work with.

Why is this important? Because you are far from the last developer your company is ever going to hire and the less time the people who come after you spend setting up their environments the more time they can spend learning the codebase and actually making themselves useful. It seems minor, but the hours it takes to set up an environment really add up over multiple hires. It’s also incredibly helpful if you’re allowed to work from home and need to setup your environment again on your personal computer or if you switch OSs or need to do a full reinstall or your computer dies and you need to setup a new one. Seriously, just documenting environment setup will make your team think you’re amazing and make everyone who comes after you more productive.

But if you want to do even more, it’s also awesome if you can document parts of the codebase as you learn them. No matter how much sense that code makes right now, you will forget it, and again, this is super helpful to everyone who comes after you.

If your team doesn’t have a place to store docs, see if you can start one. At my work we use google apps already, so it was really simple to create a google sites wiki that can only be viewed by people from our organization. If you don’t use google apps, pretty much any tech company is going to have a spare box you could spin up a wiki on. Whatever you do, just make sure there’s some sort of security – if you’re not going to put concrete details about your code in your docs, there’s not much point having them – and that you’re not using a free service that’s going to up and disappear out from under you one day. If nothing else, you can always put some text files on a shared drive and call it good :)

While you’re at it, it never hurts to document processes like how to deploy to staging and prod, how to fix common errors, where all of the log files for different services are, where those different services themselves are. Basically any time you have a question you have as a new developer, write the answer down where other people can find it. If you need to know, so will the next dev.

The less time your team spends re-learning code or hunting down a lot file, the more everyone gets done. That’s something you can help with no matter how new you are.

Talk of the day

If you share my obsession with software design (and maybe even if you don’t) you’ll enjoy this talk by Katrina Owen called Overkill. The basic idea of the talk is the use of a simple toy problem as an excuse for focused practice. I really like the idea of going back to basics as a path to mastery, that’s actually why I’ve been on my own back to basics kick on this blog.

If you like that talk, Katrina Owen co-authored an object oriented design book with Sandi Metz (who is also fantastic) called 99 Bottles of OOP. I haven’t read all of it myself yet, but I have watched (well, listened to) a few of Katrina’s and Sandi’s talks and really enjoyed them.

Trick yourself into getting stuff done

Unrelated image from pexels.com to make this post look nicer in social media shares.
Unrelated image from pexels.com to make this post look nicer in social media shares.

You know that feeling when you need to get something done and you just don’t want to? Considering this post was published on a Monday, I bet you do :)

When I don’t feel like doing something, I find it can really help to trick myself. That is, I do a tiny little piece of something that’s related to the thing I need to do but that I can tell myself isn’t the real work. For example, if I’m starting a new feature, I might tell myself I’m not really starting it yet, I’m just poking around in the existing code a little and seeing where I could put it if I actually was starting that feature. Or I might tell myself that I’m not really building that feature, I’m just stubbing out a class and writing a few comments about how I would build if it I were doing that, but I’m totally not, I’m just writing comments, nothing to see here ;)

Minus a certain amount of flailing around trying to figure out the best way to do something, this is basically my process when I’m building stuff:

Don’t do the thing, just poke around in the code a little.
Don’t do the thing, just make notes about what you find.
Don’t do the thing, just write down ways you could do the thing if you were going to (but you’re not).
Don’t do the thing, just stub out a class (if needed) where you would do the thing.
Don’t do the thing, just write some comments where you would do the thing.
Don’t do the thing, just stub out a method.
Don’t do the thing, just pseudocode one method.
Don’t do the thing, just fill in one method.
Don’t do the thing, just write down one thing you’ll need to test.
Don’t do the thing, just pseudocode one test.
Don’t do the thing, just fill in one test.

Honestly, that’s the core of software development. Software design and architecture are certainly important too, but I’m convinced the single most important part of actually building stuff is breaking down problems into manageable little pieces. If we had to think about the entire application all the time, we’d all end up under our desks weeping quietly. Only the ability to ignore the big picture for a while and focus on one tiny piece allows us to actually get anything done.

Of course just because “break the problem down into tiny pieces” sounds simple doesn’t mean it’s easy. It’s really common to get side-tracked trying to figure out how something unrelated works (I have the worst time leaving stuff alone even it’s probably not relevant to what I’m currently doing), or to spend far too much time trying to figure out what the best way to do something is (that one’s so common we have a word for it), and sometimes you just don’t know where to start or the problem has so many moving parts that you feel overwhelmed and quietly freak out a little.

On the upside, learning to break problems into manageable pieces gets easier with practice. For me it’s mostly a matter of reminding myself that I’ve done this plenty of times before and I’ll solve this problem too.

If you’re having trouble getting started, see if you can trick yourself into doing something. Remember you don’t have to solve the whole problem at once, you can start with a tiny piece of it.

How does variable scope work?

a black woman types on a laptop
Photo from create her stock

Scope is where a variable exists can be accessed in your code, and it’s surprisingly complicated.

The short version is that a variable that was declared inside a block only exists inside that block. Great, what’s a block? In Java, it’s anything between a set of curly brackets { }. Blocks can be nested, too. A method inside of a class can see the class’s variables, and a block inside of a method (like an if or a loop) can see the method’s variables. Nesting only works inwards, outer blocks can’t see inside inner blocks. Once a block finishes executing its variables cease to exist, so there’s really nothing for the outer block to see.

Java also makes things more complicated with scope modifiers: classes, methods, and variables can be public, private, or protected. Those modifiers only apply outside of methods, they don’t make sense for variables that are just going to vanish after the method executes. Public means the “thing” (class, method, or field/class variable) can be accessed from outside the class. Private and protected classes are sort of a weird special case, they only make sense if you have a nested class inside another one. Public things can be accessed from outside the class, private things can be accessed only from inside the class, and protected things can only be accessed by subclasses of the class where they were declared.

Just like each time a method is run it gets a fresh copy of all of its variables, each time a class is instantiated it gets a fresh copy of all of its variables too. Unless any of them were declared static, in case you didn’t already have enough to keep track of :) The difference between classes and objects created by instantiating those classes was a hard concept for me when I started programming, don’t feel bad if you’re confused. Classes aren’t things you can interact with, they’re just blueprints for things. Once you create an actual thing by instantiating a class, then you can call methods on it. Unless you made that method or variable static, then you can use it without actually having an instance of the class. Static variables are special, normally every instantiation of the class gets its own variables, but static variables are shared between all instances of the class.

Why would you want to have just one instance of a variable for all instances of a class you’ll ever have? If you have any constants in the class, they should be declared static (also final, which means, surprisingly enough, that you can never change it) to save memory. If the constant is only ever going to have one value, there’s no reason to waste memory by giving every instance of the class its own copy. You might also want to make something static if it’s a shared resource like a logger. You really only need one logger per class, so again you can save memory by sharing one logger instead of giving every instance its own copy.

So that’s all well and good, but why does scope work the way it does? Partially I think it’s for the convenience of the programmer :) How much would it suck if you could never reuse a variable name because all variables were visible anywhere? And how much of a hassle would it be to keep track of which variable you were using versus which one you meant if all of them were visible?

Aside from convenience, there is an actual reason for variable scope to work the way it does. It has to do with the way the computer keeps track of exactly which code is executing at any given time. To over simplify a bit, when a program is executed it gets two chunks of memory, the stack and the heap. The heap is where objects live, and the stack is where the computer keeps track of where it is in the program and what values all the variables have. When method a calls method b, the computer stores the state of method a on the stack, then creates a new state for method b with all of its variables and stores it on the stack too. When method b finishes, the computer keeps its return value (if it returned anything), to update method a’s state with, then it throws away the state for method b. That’s what I was talking about when I said that variables cease to exist when a block finishes executing – the computer throws out its only record of what values those variables had. You can read more about memory and execution in this article, which has some pictures to help visualize what’s going on.

What about static variables, if they live in the stack why don’t they disappear? My understanding is that they actually live in the heap (where stuff stays until you deliberately get rid of it), and what goes on the stack is just the address of where the static variable lives in the heap.

Scope might seem really simple if you’ve been programming for a little while, but let me throw a wrench into that idea: multi-threading. With multiple threads running the same code, it can be really difficult to figure out why on earth your variable suddenly has a value that makes no sense. Not that I’ve ever spent multiple days swearing at my computer for making no sense ;)

Chrome extension of the day

You know what sucks? Desperately trying to figure out how you broke your html layout, only to discover hours later that you had an invisible element or padding or a margin that was quietly ruining everything. Pesticide to the rescue! Pesticide is a very simple Chrome extension that does just one thing – it outlines all of your elements. That’s it.

I have a thing for simple tools that do one thing and do it well, and Pesticide is just that. No screwing around with settings, no trying to remember how to activate it, you just click the little bug icon beside your omnibox to turn it on and click it again to turn it off. Simple is just what you need when you’re fighting with your layout. Try it, you just might like it!

Things they don’t tell you in school about production code

Unrelated image from pexels.com to make this post look nicer in social media shares.
Unrelated image from pexels.com to make this post look nicer in social media shares.

One of many things school can’t really prepare you for is what it’s actually like to write production code. That’s not a knock on my education or anyone else’s, it’s just not possible to get the experience of writing production code without, you know, writing production code. That said, I’m going to try to explain it anyway :)

Like I said in When is it done?, when I was in college I thought “done” meant “compiles and seems to give the right answer for a couple of happy-path tests. Actually “done” in a meaningful sense is much more than that, and so is writing code that’s really for really real ready for production.

Having code that compiles and probably even works is all well and good, but how will you know how it’s performing or whether it’s working right in production? This is the kind of thing you don’t think about for school assignments, you just hand them in and then you’re done with them forever. Logging suddenly becomes a really big deal when you need to know whether your code is working right and if not, what you need to fix.

All the details of how to log, when to log, what you should log have filled many books, so I’ll just say that it takes practice to figure out how much logging is enough but not too much and that you should feel free to lean on your senior devs to help you with that. At the very least, everything you log should include some information about the user who was logged in at the time and the account/project they’re part of if that applies. Knowing that something happened isn’t terribly helpful if you don’t know anything about the context it happened in. If in doubt, err on the side of more information. You can always filter it out or just ignore it if you need to.

In addition to logs, monitoring is also really important. Most production servers have a health check, a way to figure out if the server is up and can access things like the database and other external services. Why external services? Because a server that can’t talk to the cache/social network/payment provider/etc isn’t good for very much. More things they don’t tell you in school :) Like logging, health checks take practice too. Comprehensive checks are great, but you may not want your server to say it’s down when an external service is responding slowly either.

Metrics are important too. Whether you use a third party analytics service or roll your own with Graphite and StatsD, it’s really useful to be able to see at a glance whether your app is behaving normally. At a minimum you probably want to know how many requests you’re getting per minute and how many errors, plus anything domain specific like how many level starts or level ends per minute, how many purchases, how many new signups, etc.

Yet another thing you probably didn’t do in school is code reviews. In school, it generally doesn’t matter if anyone else understands your code. At work, it’s important than someone else is able to fix your code if anything goes wrong while you’re on vacation or home sick or away at a conference or if you change jobs. Having one point of failure is always a bad idea whether you’re talking about servers or people who are the only person who really knows x.

For very similar reasons, documentation is important too. Aside from people getting sick or going on vacation at inconvenient times, documentation is really useful when you come back to a piece of code months later or when you’re working on something that somebody else wrote. It’s also great for helping new hires get up to speed. Just because it took months for you to learn the codebase doesn’t mean it has to be that hard for the next new hire.

Unit tests also become a lot more important when you’re working on production code. They’re not just for getting your teacher off your back, they’re a great safety net when you have to change things and want to make sure you didn’t break anything that used to work. In school you hardly ever return to previous assignments, but at work you change things over and over again and it becomes really helpful to have a way to make sure you didn’t break stuff that doesn’t involve manually checking everything. Also, the more you can automate tests for, the less you have to test manually.

I’m sure I’ve just scratched the surface of things that you didn’t learn in school about production code. Readers, what most surprised you about production code?