Friday, October 28, 2016

Write your Try-Catch-Finally Statement First

In Clean Code, Uncle Bob give the following advice:

Write your Try-Catch-Finally Statement First

Why?
"... it is good practice to start with a try-catch-finally statement when you are writing code that could throw exceptions. This helps you define what the user of that code should expect, no matter what goes wrong with the code that is executed in the try."
I like this because by following this advice, you'll have to start by writing unit tests that handle exceptions for code where exceptions are expected to be thrown. And then you'll have to write the exception handling code which will force you to think about how you may want to handle the error case. In Uncle Bob's words, you'll have to "define what the user of that code should expect".

This is useful from a development efficiency standpoint because if you expect an error, then by writing the test case for when that error is thrown, you can write the code for the Try block with confidence. You know that even if something goes wrong, it will be handled and the current function will execute to its completion.

If you don't do this, then you'll write a unit test case for code that might just blow up your program and crash spectacularly. Then what? You're finally forced to heed the advice of writing the Try-Catch-Finally statement and realize that maybe you should've done that first.

Monday, October 24, 2016

Abstraction Layers

An important skill that I think every developer should have if they want to write cleaner code is to understand what abstraction layers are and when abstraction layers are being mixed in code. 

What do I mean by abstraction layers?
"In computing, an abstraction layer or abstraction level is a way of hiding the implementation details of a particular set of functionality, allowing the separation of concerns to facilitate interoperability and platform independence." (Wikipedia)
Computers don't define abstraction layers for you. Programmers do. When you're dealing with an interface of some sort - whether it's a function or some web API, whatever details that exist behind that interface is essentially a different layer or level of abstraction because those details are hidden from you. One layer (in this case, the layer that your program resides in) is concerned with the what and the other layer (the one that's behind an API) is concerned with the how.

Programmers defines those interfaces that separate abstraction layers. They decide what the public sees. Not only that, but internally they must also decide what every part of the system sees - how the individual units interact with each other - and carve out the layers of abstraction that exist within the system. Those decisions are really important. Good abstractions are easy to understand. Bad abstractions are confusing. This is why using clear and descriptive names are important for writing a maintainable program.

This post isn't about how to pick good abstractions using techniques like writing descriptive names, however. It's about why it's so important to be able to recognize when abstraction layers are being mixed. Why? Because in any program, even if the names are sound, it's still a mess if the names of things that belong in different abstraction layers are mixed!

What do I mean by mixed abstraction layers?

Abstraction layers separate the what from the how. When the what and the how are mixed, abstraction layers are mixed. You see this most often in "god" functions. They do everything. Everything exists on the same plane.

Why is this a problem?

As someone reading the program, you're forced to wrangle with details that you may not care about. Here's a good real world example: say you're looking for a recipe for a grill cheese sandwich. You go on the site, and it's about 200 pages long. It doesn't just tell you the ingredients for a grill cheese sandwich, it tells you how those ingredients can be obtained, the history behind each ingredient, the health effects of consuming each ingredient. Shit you don't really care about if all you're trying to do is to make a damn sandwich!

I just need to know that I need sliced cheddar cheese. Not how it's made or how it's sliced (if I care about either of those things I'll dig deeper myself) what the history is (which is completely irrelevant to my concern). Point is, I don't need to see all of that information at once. It's overwhelming.


Thursday, October 13, 2016

The Law of Demeter

This is a well known software design guideline that helps you write code that is:
  • More readable
  • More testable
  • Less coupled 
It also goes by the following three definitions, ranging from least formal to most formal:

Definition 1

Don't talk to strangers. Only talk to your (immediate) friends. 

Your best friends are Bob, Jane, and Josh. You need help? Talk to them. Don't talk to their friends or their cousins. 

Definition 2

Use only one dot. 

No: SomeObject.doOneThing().doAnotherThing().andAnotherThing()
Yes: SomeObject.doManyThings()

Uncle Bob calls the first NO example a train wreck. Avoid train wrecks. 

Definition 3

Method F of object C may only call methods of objects that are:
  1. C
  2. Ceated by C
  3. Parameters of F
  4. Created by F

Effects of Least Knowledge on Testing, Coupling, Readability


We don't need code samples to consider the implications of this on our code. What all three definitions have in common is that by following them, you're minimizing an objects knowledge of other objects. If you're forced to only talk to your immediate friends, you don't need to know about their friends. If you're only using one dot, you're only ever dealing with the interface of one other object. This is why the Law of Demeter is also known as the Principle of Least Knowledge. 

There's a strong correlation between the amount of knowledge an object has about other objects and the difficulty of testing that object. Think about it. The more things an objects interacts with, the more you have to set up in order to test that objects behaviors. 

When an object has little knowledge about other objects, code also tends to be less coupled. An object with no dependencies and with nothing that depends on it is an object with no coupling. It depends on nothing and nothing depends on it. Systems, however, aren't usually built using a number of completely isolated parts that don't communicate with one another. But the more we can limit the communication between different parts, the less likely any change in one part of that system will affect the rest. 

If you're looking at a code base that adheres to LOD, there's a good chance you'll find it very readable because the less objects know about other objects, the less you have to know when you're trying to understand that object. If you're dealing with a train wreck, to really understand what's happening you have to follow multiple dots and that requires more effort and to change the behavior will require you to understand the interfaces of two or more objects. Again, more mental effort.

Saturday, October 1, 2016

Very bad things you should NEVER do to your window glass at home

Bad Thing #1: Taping shit to the window glass.

Getting adhesives off glass is time-consuming and you risk damaging the glass each time you do it. I once complained to my dad about having too much sunlight in my bedroom (my windows face east) and his solution was to coat them with multiple sheets of thin, light-colored decorative wallpaper. It sort of helped, but it made my room feel like a solitary confinement cell. If you also have too much light in your bedroom, don't ask my dad for advice - get blinds.

If you avoid doing Bad Thing #1 in life, then the rest of this post won't apply to you. However, if you're interested in learning about how much badly you can fuck up your windows following your single biggest mistake, keep reading.

Bad Thing #2: Using a canister stove as a blow torch to loosen the adhesive stuck to your glass.

I finally got sick of looking at the ugly wallpaper in my room today and decided that I was going to spend an hour removing it. I wanted my windows wallpaper free. An hour later, I was hunched over on the edge of my bed in my room with a tiny metal scraper resting in my right hand. At that point, I've already tried a number of liquid solvents to soften and loosen up the wallpaper: water, water with vinegar, windex, and even peanut butter (trust me, it's a thing). None of it worked. The wallpaper was dried, thin, flaky and married to the glass. 

Feeling frustrated, I turned to fire because heat is known to break sticky bonds. I started out small with a stove lighter to heat up tiny spots on the glass with the most stubborn wallpaper. This worked really well and got me excited. However, the lighter kept going out and the process was painfully slow because the flame was so small. So how do I add more heat and do it across a greater surface area without adding more lighters? Well, one popular option is a heat gun. I've seen my girlfriends dad use it on a sticky label once and it was very effective. Unfortunately, I don't own one and I didn't feel like going out to buy one. What's the closest thing I have to a heat gun? A blow dryer. So I plugged in my girlfriends blow dryer and started blasting the glass with it. Five minutes later, I realized the blow dryer wasn't generating enough heat so that wasn't much help. 

I need more then hot air. I need fire. And that's when I thought, "What if I had a blow torch"? Well, I don't. But I do have a canister stove that my girlfriend and I bought for a camping trip that I can probably use as a blow torch. So I unpacked my canister stove, lit it up, and held it up to the glass. It was working! The stuff was coming off fast (and turning into ash in the process). I was like, this is amaz - *CRACK*. Shit, that was my glass. F************.

Turns out there's this thing known as "thermal stress break" that can happen to glass surfaces. Basically, glass expands when heated and shrinks when cooled. When there's a change in heat and that change is not transferred uniformly across a glass surface (in this case, it was a lot of heat concentrated in a single area), one part of the surface will attempt to expand and that creates stress between the heated area and the rest of the glass known as thermal stress. There's a limit to how much thermal stress a piece of glass can withstand before there's a thermal stress break and my glass clearly had a thermal stress break.

Did I stop there? I wish I did. 

Bad Thing #3: Ignoring physics by pouring boiling water onto the glass.

Yup, it got worse. I didn't want to use the canister again because it just generated too much heat in a concentrated area. I did some more research and came across a few articles of people using boiling water to successfully remove wallpaper from their walls. Interesting. At this point I knew that using heat works really well - but only up to a point when it comes to glass. I didn't know what that point was but I soon found out that it was far lower than boiling point.

First, I learned how to remove a double-hung window sash so that I could remove my uncracked top window and use it in my boiling water attempt. After I got it down, I brought the sash into my bathroom and set it down with the glass horizontal to the floor while my water was boiling. Once my water finished boiling, I brought it into the bathroom in a pot and then slowly poured it over the glass and ...



That's it. No more ideas. Time to get new window sashes and blinds.