Mel Reams

Nerrrrd

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?

Why is javascript called javascript?

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.

Or more specifically, why is javascript called javascript when it has basically nothing in common with java?

First, let’s have a little context. Javascript originally ran only in the browser and made webpages interactive. Java was primarily a server-side language but could run in the browser in the form of applets (they’re very rarely used now, don’t worry if you’ve never heard of them). Javascript is also dynamically typed (you can put anything you want in a variable and the interpreter figures it out (or not) at runtime), uses prototypal inheritance (you create new objects using an existing object as a prototype), and has had closures (first-class functions that ‘remember’ the state of the variables they had access to when they were declared) from the beginning. Java, on the other hand, is statically typed (thou shalt not put a double in a variable that you declared as an int), uses class-based inheritance (you create objects using a blueprint called a class and only classes can extend other classes), and only just got closures (called lambdas in java) in 2014 when java 8 came out.

About the only thing java and javascript have in common is that they both use c-style syntax (curly brackets and periods, basically). So given all that background information about how little java and javascript have in common, why on earth is javascript named javascript?

Back in the 90s when javascript came out, java was the shiny new thing everyone was excited about, and the theory I’ve always heard about the name was that it was a marketing ploy intended to make people think javascript actually did have something to do with java and was therefore cool. According to this interview with Brendan Eich, the inventor of javascript, javascript actually was intended to sorta, kinda, have a little bit of a relationship with java: “the idea was to make it a complementary scripting language to go with Java, with the compiled language.” And according to this press release, javascript’s design was: “complementary to and integrated with Java” It turns out javascript actually can interact with applets, too.

These days javascript has nothing to do with java, and honestly it may never have had much to do with it, but just because you’ve heard the “purely a marketing ploy” theory over and over doesn’t make it the whole truth. Now, who can tell me how the moral of the story applies to programming? ;)

App + tweak of the day

One of the Android apps I use most often – to be fair, that’s because you set it up once and leave it alone – is Twilight. It’s basically f.lux for Android. Technically f.lux for Android is f.lux for Android, but it only works for some phones and requires root.

f.lux (and Twilight) if you haven’t already heard of it, automatically changes the colour balance of your screen to a warmer, more restful shade when the sun goes down. It’s supposed to help you sleep, which I honestly couldn’t say if it actually does, but I personally like it because it feels more restful to my eyes.

That’s great if you’re running Android, Windows, or Mac, but what if you have an iOS device? Well, if you’re willing to jailbreak it you can get f.lux, but if you can’t or don’t want to, you can use this trick to dim your screen. It’s not the same, but it’s certainly better than nothing.

One last thing to note: because Twilight is a screen overlay, Android won’t let you install anything while it’s running, even if it’s not currently changing the colour of your screen. That totally makes sense from a security standpoint, but I wish it would display an error message instead of just silently refusing to do as it’s told. If, for example, you happened to spend an afternoon cursing at your phone because it mysteriously refused to let you install a test build so you could do some debugging, that would be why. Turn off Twilight and magically things will start working again :)

Should you get a certification?

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.

A question I’ve seen a lot on java programming forums is “Should I get a certification?” Like every other programming question ever, the answer is “it depends.” Don’t worry, I’m going to explain what it depends on and how you can figure out whether or not it makes sense for you to get a certification.

First of all, I want to admit up front that I’m skeptical about programmer certifications. I’ve seen excellent programmers with certifications and I’ve seen far from excellent programmers with certifications, so I don’t believe having a cert tells me very much about whether you can code. That said, it’s not going to hurt you to have a certification on your resume, so if you have access to funding for retraining or anything, go for it!

What I believe most people really want to know when they ask if they should get a certification is “Will it help me get a job?” The answer depends on what companies in your area want, but fortunately, that’s really easy to figure out. Research! Hey, I didn’t say it was going to be fun :) What companies want is not some big secret, it’s going to be directly in the job descriptions they post. The trick here is not to look at two or three postings from companies you’re already interested in and call it a day. You’ll get a much more complete picture of the qualifications that companies in your area want if you look at a wide range of jobs both at your current level and above it – you’re not planning to be a junior forever, are you?

Another way you can research is by going to user groups and meetups and asking around. People who already work in the industry are going to be able to tell you things that aren’t in job descriptions, like “the last person company x hired who didn’t have a certification was the boss’s niece” or “company y’s job description mentioned certifications were a nice to have but they were actually perfectly happy with my example code”

Speaking of interviews, they can be a reason to get a certification even if local companies don’t specifically ask for them. If having a certification would make you feel more confident  and you can get one for a reasonable price, go for it. The more prepared you feel going into an interview the better you’ll do answering questions, which a cert can help with even if you never get asked about it directly.

Whether you should get a certification also depends on what kinds of credentials you already have. If you have a programming related degree or diploma, I wouldn’t worry about getting certified unless local companies really want certified employees. If you’re trying to switch careers, a cert could really help and is likely to be a lot cheaper than going back to college or university.

It’s a little bit of a tangent, but something certs can legitimately be really helpful with is telling you what to learn. It’s totally overwhelming to do a couple of tutorials online and learn just enough to freak out about how much more you have to learn. Certifications can narrow that down by giving you a nice tidy list of stuff you should know. Fortunately, you don’t have to actually get the cert for that, you can just read the list of topics the exam covers and learn them on your own. Then you can prove you know them by building something that uses those concepts and/or writing about them. As a bonus, nothing convinces an interviewer you can code like showing them your code.

Should you get a certification? Will it help you get a job? You can find out yourself by reading job postings and going to user groups and asking around.

Link of the day: Queues Don’t Fix Overload

I really enjoyed this post about how Queues Don’t Fix Overload, it does a great job of explaining why bolting something onto your application without digging into the root cause of your problems will just make things worse in the long run.

Bonus link: I found that post in the Programming Beyond Practices newsletter by Gregory Brown, which I also recommend. Have a look at the archives, there’s some good stuff in there.

There’s always something else to learn

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.

Not long ago I read this blog post Why Learning to Code is So Damn Hard, which makes a really interesting point about the “desert of despair” between beginning to learn to code and having the skills to build a complete project on your own. The desert of despair, according to the post (which I agree with) is a combination of lack of resources for learners who are between beginner and expert, and having learned enough to know how much you still have to learn. Many aspiring coders get lost in the desert of despair and never find their way out.

I also read Amy Hoy’s post 5 Things I Wish Somebody Told Me Before I Founded My SaaS. One of the points I found the most interesting was that there’s always another inflection point. By inflection point, she means “those knife-edges you tip toe along, when things could go either way, when you are, say… trying to grow your team but lack the time/revenue to do it, but growing your team would help increase the time/revenue to the point where you could grow your team. Ouch. To me, that’s the prototypical inflection point.”

Where this ties back to the other post is where Amy says “Over the last 8 years running this biz, I have said so many times: “We just have to get through this $INFLECTIONPOINT and then things will get easier.”” Doesn’t that remind you of programming?

If I can just learn enough to get my code to compile then things will be easier.
If I can just learn enough to add a feature to an existing project then things will be easier.
If I can just learn enough to start a project on my own, then things will be easier.
If I can just learn enough to break my code down into good methods, then things will be easier.
If I can just learn enough to break my code down into good classes, then things will be easier.
If I can just learn enough to break my code down into good layers, then things will be easier.
If I can just learn enough design patterns, then things will be easier.
If I can just learn this new framework, then things will be easier.
If I can just learn this new style of programming, then things will be easier.
If I can just build enough different projects, then things will be easier.
If I can just learn enough…

There’s always going to be something else to learn, it’s never going to become easy and stay that way. Things do get easier once you find your way out of the desert of despair, but initially learning to code just leads to worrying about whether your code is good leads to worrying about design and architecture and scalability and reliability and security and those are seriously hard problems.

Despite how it may sound, I’m actually not trying to say that coding will suck forever and you should just give up. I’m saying that it’s normal to feel like you still suck at this even after years of working as a programmer. You don’t actually suck, it’s just normal to feel that way. What’s really happening is you’ve levelled up. When you do that you see the problems that used to give you trouble as too simple to count and focus on the stuff you aren’t good at yet, which can easily make you think you suck.

The thing I struggle with is design. I’ve been at this for ten years now and I’m still never sure if I’ll regret the design I’ve come up with the next time we add a feature to the system. Plenty of times I’ve come up with something that seemed like a good idea at the time, only to find out that it had serious flaws when I came back and changed it later.

It’s tough sometimes but on the upside, you will never ever run out of things to learn as a programmer :)

WordPress Appliance - Powered by TurnKey Linux