Remap ESC key in Vim for better ergonomics

A couple months ago, I had a sharp, shooting pain in my left hand. It was right after I switched from an Apple keyboard to using a WASD mechanical keyboard.

After a couple weeks of pain, I realized I'd been reaching my left hand to the Escape key in Vim, probably hundreds of times per day! No wonder my hand was hurting.

I finally resolved to remapping Vim not to use the Esc key, in favor of using the consecutive letters jk in its place. Lo and behold, my pain went away. Hopefully it resolves yours, too!

To remap your Esc key like I have, add the following line to your ~/.vimrc:

inoremap jk <esc>

Naming conventions for modern JavaScript

If you're like me, you've struggled to come up with a reasonable scheme for naming things in JavaScript. I'd like to share the conventions I use, with the hope that you can put them to use in your project and never think about it again.

In my mind, there are three main types of JavaScript files:

  • Collections of functions
  • Single functions
  • Classes

Collections of functions

Let's say you have a couple utility functions called add and subtract, each exported from a single file:

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

When I have a group of functions like this, I name the file using drunkenCamelCase, (lowercase first letter) with a name that suggests the library's contents. This module I'd probably call math.js.

When I go to use one of the functions from another file, now I can refer to it like so:

import { subtract } from 'math';

console.log(subtract(5, 1));

Single functions

What if you have a single helper function you want to use from a few places in your codebase that you'd like to give its own file?

For instance, let's say you have a function that generates a fully-qualified URL from a URL path:

export default function(path) {
  return "http://www.guilded.co" + path;
}

In this case, I'd name the file using drunken camel case, but would name the file explicitly after the exported function. That way, when I go to import it from another file, I can refer to it thusly:

import urlFor from 'urlFor';

console.log(urlFor('/about.html'));

Classes

Now that ES6 has support for classes built into the language, there's a good chance you'll use them to represent the stateful objects in your codebase.

I like to make it clear that classes are distinct from functions, so I name them using CamelCase (capital first letter) notation:

class MyClass {
  // ...
}

When producing a new file for a class, export the class directly, omitting its name:

export default class {
  // ...
}

File names for classes should be CamelCased as well. So our MyClass class would be in MyClass.js.

If you use React, you probably know you're required to name React components in the same CamelCased format. If you use ES6 classes to construct your React components, this convention will come in handy.

Fixing a Ruby crash using Middleman 4.1x with Ruby 2.3.0

I went to update a Middleman project's gems today. After I did, I noticed middleman server exited with the following error:

Assertion failed: (!STR_EMBED_P(shared)), function str_new_frozen, file string.c, line 1075.

This is an internal Ruby error generated from within its C source. I found a discussion about the topic in the Ruby bug tracker, but that wasn't much help.

Once I modified my Gemfile to use Ruby 2.3.1 and re-bundled my gems, middleman server worked just fine.

If you're running into this problem, try upgrading to a more recent Ruby and running Middleman on it. There's a chance this bug has nothing to do with Middleman and could be due to another gem, but I figured I'd mention it here in case someone else is having the same problem.

How to bind React component event handlers in ES6

When creating React components using ES6 class notation, you'll need to bind event handlers passed as props to this, or you'll find that the handlers will be bound instead to the DOM element.

There are a few ways to do this. You can reassign the bound handler in the constructor:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

This works fine, but now you have .bind(this) littering your otherwise elegant JSX.

To remedy that, you can use the fat arrow prototype method syntax:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.onClick.bind(this)}>Click Me</button>
      </div>
    );
  }

  onClick = (event) => {
    alert("You clicked me!");
  }
}

Except... now you have two separate syntaxes for declaring methods, which could make your code less readable and more confusing.

I think the most elegant way is to use the new double-colon (::) notation, which is a shortcut for calling .bind(this) on a given handler:

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <button onClick={::this.onClick}>Click Me</button>
      </div>
    );
  }

  onClick(event) {
    alert("You clicked me!");
  }
}

Now your caller is binding the method to this without an ugly .bind(this) call, and the method body isn't unnecessarily decorated with fat arrow notation.

Fixing Postgres errors after an ungraceful shutdown on your Mac

Every so often, I'm forced to shut down my Mac by holding down the power button. When this happens, PostgreSQL often doesn't shut down properly, and when my computer starts again it doesn't start automatically.

It turns out this is because there's a stale pid file kicking around inside your PostgreSQL var folder. To fix it, simply delete the postmaster.pid file. PostgreSQL will start automatically thereafter.

rm /usr/local/var/postgres/postmaster.pid

Why doesn't React immediately mutate state when calling setState?

When setting the state on a React component within an event handler, you'll find that the state isn't updated if you dump the state to the console immediately after:

The React documentation warns:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

I learned today that setState accepts a callback in this scenario. So modifying handleChange to the following will result in the console receiving the updated state:

Things I wish I'd known at 20

I'm turning 31 in less than two weeks. In tech nerd terms, that means I'm basically an ancient relic. There are a few things I wish I'd been told, and other things I was told but wish I had listened to. If you're a young aspiring geek about to excitedly enter a career in technology, maybe I can save you some heartache in your twenties.

  1. Programming is hard, but (usually) it's not an emergency. Enjoy yourself and don't sweat the day-to-day.
  2. Ideas are worthless. Execution is everything.
  3. Learn how to solve problems, not how to use the latest tech. No one ever hired a builder because they were really good at hammers. They hired them to build a house.
  4. Avoid lifestyle inflation. Live like you're middle class, even if you make six figures. (American median income: $51,939)
  5. Save six months' worth of expenses in a savings account as fast as you can.
  6. Keep your recurring expenses as low as possible. This means things like rent, debt payments, utilities, and your gym membership.
  7. Stay out of debt. If you're in debt, eat dog food and work until you're out.
  8. Remember your colleague with the big house and nice car probably makes about the same you do. Also remember they're probably stuck in their job paying for them. Choose mobility.
  9. Don't buy a house unless it's a really, really good deal. Even then, probably don't.
  10. Commuting to an office eats more of your salary than you think.
  11. Fall in love. It keeps you out of bars, in bed early, and attentive to your work.
  12. Eat lots of vegetables. Allocate time to cook.
  13. Invest in ergonomics. Stand at work.
  14. Listen to others unconditionally.
  15. Learn basic yoga postures. Practice them daily.
  16. Take frequent breaks while working.
  17. Drink lots of water.
  18. Avoid alcohol. Especially chronic use, since it becomes difficult to notice its negative effects when you're always hungover.
  19. Track every penny you earn and every penny you spend.
  20. Buy a small, inexpensive, efficient car.
  21. Run your household like a business with shareholders.
  22. You're going to be old and sexually undesirable someday. You're likely more attractive now than you'll be at the end. Enjoy that.
  23. Give to others spontaneously.
  24. Don't let your salaried job get in the way of your own dreams.
  25. Don't let your dreams be diluted by the day-to-day challenges of your salaried job.
  26. Don't let Apple tell you the things you need to buy.
  27. Chat and email aren't actual work.
  28. Choose clients and employers based on how you get along, not on how much you get paid.
  29. Symbols of status matter, but the symbols aren't your car, house, or clothes.
  30. Enrich yourself with knowledge and art. They're inexpensive hobbies and you'll always be fulfilled.
  31. Your parents are wrong about a lot of things. But they're also right about some. Choose your own path, but respect their guidance.
  32. The world is in peril. But it's always been that way.
  33. Gratitude is effective therapy.
  34. The best time to start has already past. But the second best time is right now.

So you're really good at hammers

If you're about to hire a contractor to remodel your kitchen, you won't ask them if they're really good at hammering nails.

And if you hire a personal trainer, you're not going to be too interested in if they use the latest and greatest weight machines.

So why then, do software consultants often value themselves based on the tools they use? What value is it to your clients to know you have a theoretical knowledge of framework X, when framework Y is threatening its demise?

As your customer, I already know you can hammer nails. I want to know what kind of house you can build me. I want to know that, in the event nails suddenly become passé, you can deliver me a functional house using screws or bolts or glue.

More often than not, your hard skills don't matter. It's your meta-skill— your ability to learn new skills rapidly and under pressure—that is truly valuable.

Just like hard skills, meta-skills can be learned. Through conditioning, you can train your body and mind to be really good at learning. Here are some things that have worked for me.

  1. Spend an hour per day reading about the latest technologies in your discipline. Apply one of them to a side project. Ask your clients or employer if you can give a talk on one. If you think there's a new technology that could add value to your client's project, say so, and lobby to use it.

  2. Adopt a product-oriented mentality. Don't get caught in the weeds of implementation. Be sure to poke your head out to make sure what you're doing matches your product's overarching vision. Talk more and code less.

  3. Start with the solution in mind. If you're going to build a new feature, sketch it out first and ask for feedback. It's likely you're wrong in at least one of your assumptions. Better to make it wrong on a napkin than in code.

  4. Learn to distill everything in lists. Developers are communicators above all. If you are a capable analyst, you will excel no matter the toolset. Lists convey to your team and stakeholders an itemized vision of the future. They're easy to clarify and easy to change. And, they ultimately produce more value than the code that spawns from them.

  5. Don't be afraid of not doing it best way the first time. On a recent project, I was tasked with building a new user interface feature. I decided that, since React is eating the world of web interfaces, it was time we caught up with the times. My first release of the feature worked great for the user, but under the hood I neglected some of the best practices I would later learn. While we're still in the process of adopting those practices, my code is currently chugging along in production, adding value to the product. If we're to brave new frontiers, it's likely we'll end up backtracking along the way.

Technologies change, but your own meta-skill will keep you valuable for your entire life. Even if you're really good at hammers, make sure you know how to build a house.

Why I stopped drinking alcohol

Disclaimer: The following is my personal account of stopping drinking. If you're a happy drinker, I don't want to alienate you. I was once a happy drinker myself. I wrote this post to help sort out my own feelings about alcohol with the hope it could inspire others. I hope it's not mistaken for preachy evangelism!

There are books about how to be a better lover. Books about how to improve your physique, how to eat healthier, how to live longer, how to become more in touch with your spirituality, how to get more organized, how to be happier.

I've read most of them.

I've read most of them, and sometimes while reading them I had a drink in my hand.

I've spent a significant amount of time on self improvement without ever seeing the elephant in the room: My use of alcohol (and cannabis, for that matter) were decaying my potential more than any of my other behaviors were.

But alcohol gives you courage. Alcohol doesn't give me courage. In the end, it makes me a coward. I feel ashamed. By morning, I feel remorse. Courage is the ability to take action in spite of fear. Alcohol doesn't make me courageous. It makes me reckless.

But surely alcohol relaxes you. But it made me tense to begin with. Drinkers aren't more relaxed than non-drinkers. According to popular culture, non-drinkers are uptight. But I've met a lot of uptight drunks. And I sure don't feel relaxed on a Saturday morning in the throes of a hangover.

But how will you socialize? The same way I always have. I'll just be sober instead. I'll go to bars with my friends. I'll order virgin cocktails. I'll drink soda water. Nothing will have changed, except I'll be in control of my actions. And I'll wake up with a smile.

You don't drink? That must be boring. No, actually. Sobriety is pretty awesome. I've had more profound life experiences in my last few weeks of sobriety than in the previous months using alcohol. When I'm not shorting my pleasure circuit, I'm forced to seek pleasure in real-life experiences. Friendship. Adventure. Life.

The alleged benefits of drinking alcohol are illusory justifications for the continued ingestion of an addictive substance.

They're the same justifications a junkie uses to get his next fix of heroin or a smoker uses to accept his purchase of another pack.

Well, no different except that we're all okay with our alcohol addictions until catastrophe strikes.

But I don't want to wait for catastrophe.

I don't want to spend the best years of my life slightly numbed. I want to feel the full breadth of my human experience. I've spent so many of those special occasions---the ones we're supposed to remember forever, the ones we're supposed to cherish---inebriated.

Alcohol impairs my judgment, costs me money, wastes my time, sabotages my health, numbs my experience, constricts my mind, and makes me ugly. It does all of these things without offering tangible benefits.

Drinking alcohol prevents me from being the best version of myself.

So I stopped.

The freelancer's guide to retirement savings accounts

Do you have enough saved for retirement for your age?

When you're employed at a company, the details of retirement are largely "set-and-forget" if you want them to be. Your 401(k) deduction is made before you even get your paycheck and you can rest easy knowing your check next month will come reliably. But as freelancers, it's our responsibility to provide a fruitful retirement for ourselves.

Fortunately, there are still options for the self-employed among us who want to get a head start on saving for tomorrow.

Roth IRA

Roth IRA's are the secret sauce of retirement saving. With a Roth IRA, you can contribute up to $5,500 per year of after-tax ("take-home") money. But then, after age 59 1/2, you can make withdrawals from the account tax-free. This means that $10,000 invested in a Roth IRA will be $76,122.60 after 30 years of 7% growth, all available to you with no tax bill!

Want a great first small win on your way toward retirement savings excellence? Open a Roth IRA with Vanguard and contribute to the $5,500 limit each year.

Note that if your income exceeds $129,000 (if filing single), you are ineligible to contribute to a Roth IRA. Fortunately though, there exists a sneaky technique for converting a traditional IRA into a Roth called the Backdoor Roth IRA. Tax loopholes aren't just for corporate lobbyists anymore!

Traditional IRA

The traditional IRA is Roth's shy, modest cousin. With a traditional IRA, your tax incentives are swapped. You can contribute up to $5,500 per year, tax deductible in the year you contribute. But when you withdraw your funds after age 59 1/2, the gains will be subject to tax at your income tax rate.

The traditional IRA is a great choice if your income exceeds the $129,000 limit for a Roth IRA. It's also a good choice if you expect your retirement income to be lower than your current income. But if you're unsure and don't exceed the income limit for a Roth IRA, I'd stick with the Roth. It's likely the growth in your account will far exceed your contributions by the time you retire, so it's the more tax-advantaged choice.

Solo 401(k)

The Solo 401(k), or i401(k), is the best way to minimize your taxable income. With the i401(k), you can make employee contributions of up to $18,000 per year, plus an additional employer match of up to 25% of your employee's salary, up to a maximum of $53,000 per year. Plus, you can contribute up to 100% of your employee's salary.

Additionally, some i401(k) plans have a Roth option, meaning you can make an employee contribution of up to $18,000 after-tax dollars per year and make retirement withdrawals tax free.

Because your i401(k) contributions are distinct from your Roth IRA contributions, this means you can contribute up to $23,500 per year into accounts that grow tax free. That's huge.

The biggest caveat with an i401(k) is that you cannot plan to hire employees into your business—the plan isn't permitted in businesses with common-law employees.

When I found out about the i401(k) plan, my jaw dropped to the floor. So this is how people get rich!

Health Savings Account

Wait, what? I thought we were saving for retirement? We are, but there's a secret weapon. The Health Savings Account (HSA) is a special type of savings account available to U.S. taxpayers enrolled in a high-deductible health plan (HDHP). Like a traditional IRA or 401(k), funds contributed to an HSA are not subject to federal income tax upon deposit. Funds can be withdrawn at any time to pay for qualified medical expenses without a tax hit. HSA's can typically be invested in similar mutual funds as in an IRA.

Like it or not, we're going to have medical bills. According to Fidelity Investments, a 65-year-old couple retiring this year will need $240,000 to cover their future medical expenses. By regularly contributing to an HSA, you can take control of your retirement medical care while saving money on your IRS bill.

Note that in order to qualify for an HSA, you must have a high-deductible health plan. These plans typically don't cover routine medical expenses or preventative care. You'll want to weigh whether it makes sense to step down to an HDHP to qualify, or if you're saving enough using other retirement vehicles.

What Should You Do?

Because you're a freelancer with no employees and you want to maximize your tax deferral, I recommend using a Solo 401(k) and a Roth IRA. These accounts will grow tax-free, are relatively easy to set up, and allow contributing $23,500 in total contributions if you're filing single.

To open these accounts now, visit Vanguard:

Want to Learn More?

I've been fine-tuning my freelance business to build wealth and become financially independent, and I want to help you do the same! That's why I've been writing a book called The Freelancer's Guide to Money---a one-stop guide to making your freelance business work for your future.

From corporate structures to saving for retirement to budgeting and beyond, making your money work for you can be a complicated process. I want to show you how easy it can be to get control of your freelance business's money so you'll have enough money to retire with dignity.

Find Out More