TypeScript and Redux

About halfway through last year, I started working with React and Redux. Our client app is extremely busy, full of data streaming in, going back out, and being passed around. Since I am the only full-time engineer and on a tight schedule, I moved to TypeScript in an effort to get something to look over my shoulder while I worked. The migration was not pleasant but the learning curve was practically non-existant and the benefits were immediately clear.

What was not clear immediately was how I could get the most of out TypeScript. TypeScript’s type inference is one of its greatest strenghts but it can bite you in the ass because it will allow you to treat everything as a generic any. This might be handy sometimes but in general, you do yourself a disservice when you choose to leave objects untyped when stricter options exist.

Nowhere is this more evident and troublesome than when dealing with the output of reducers and keys from the Redux store. Left alone, state keys mapped to props will behave as any. If there is one area of an app that I think strong types are crucial, it is the state that is shared throughout your app. In a perfect world, at a minimum, I want the following guarantees and behavior:

  • Each key of my state has known, predictable values
  • If the output of a reducer changes, state keys that depend on old output will become immediately apparent
  • If the shape of my state changes, invalid reliance upon old truths will become immediately apparent
  • The definition of my state’s shape should be centrally managed, I should not have to cast types in components

It took a little work and thought but I ended up with an approach that achieves all of this. It requires a little more boilerplate than you might find appealing but it is definitely worth the clarity, stability, and refactoring oversight that it provides.

Given the following:

// A reducer
function crucialObject(currentState = { firstKey: 'none', secondKey: 'none' }, action) {
  switch (action.type) {
    case 'FIRST_VALUE': {
      return { firstKey: 'new', secondKey: action.newValue };
    }
    case 'SECOND_VALUE': {
      return Object.assign({}, currentState, { secondKey: action.newValue });
    }
    default:
      return currentState;
  }
}

// A root reducer that will be fed to a store

const rootReducer = combineReducers({ crucialObject });

// A container/component with a mapStateToProps function that will be used with connect

const mapStateToProps = (state) => {
  return { crucialObject: state.crucialObject };
};

// And, in that same component, an expectation of what keys will exist on crucialObject
class MyClass extends Component<any, any> {
  render() {
    const myVal = this.props.crucialObject.firstKey;
  }
}

We want a healthy dependency between these pieces of code. If the reducer starts spitting out objects that don’t match what our component expects, we need to know! We can accomplish this by defining a few interfaces and then wiring them together carefully.

First, the reducer. We need to define the shape out of its output, which is simple enough.

interface CrucialObject {
  firstKey: string;
  secondKey: string;
}

function crucialObject(currentState = { firstKey: 'none', secondKey: 'none' }, action) : CrucialObject {
  // the rest is unchanged
}

Next, we want to tell subscribers of the store that if they call upon state.crucialObject, they will get a CrucialObject. We can do this with another interface. I tend to define this in the same file as my reducer.

interface CrucialValueReducer {
  crucialObject: CrucialObject
}

We need to define all of the keys and values that exist on our root reducer. Easy again! In the same file where I define rootReducer, I also define a State interface. This interface extends the interfaces that are provided by my reducer files.

interface State extends CrucialValueReducer {};

// we don't need to do anything with this here, but I find it is good practice to keep these two together since a change to one will require a change to the other
const rootReducer = combineReducers({ crucialObject });

Next, in my component, I need to tell the compiler what it should expect of the state parameter in mapStateToProps.

const mapStateToProps = (state: State) => {
  return { crucialObject: state.crucialObject };
};

This is a great change. Now, the compiler knows that State contains the combined interfaces of all of my reducers. If I change the name of my state key, remove it entirely, or change its output, mapStateToProps will bark at me and I will have to fix them. A good example would be to start with this:

const mapStateToProps = (state: State) => {
  return { safeToProceed: state.crucialObject.secondKey === 'new' };
};

If, in my reducer, I get rid of secondKey, the function that the above code is invalid. Awesome!

We have two things left. First, we want to guarantee that mapStateToProps returns an object with the complete shape that our component needs. This is no problem with, you guessed it, another interface.

interface ComponentStateProps {
  crucialView: CrucialObject;
}

const mapStateToProps = (state: State) : ComponentStateProps => {
  return { crucialObject: state.crucialObject };
};

This is crucial. If we omit it, we might make a change that the compiler sees as valid that our component is not expecting. As written, we’re in good shape. If we do the code below, though, the output of our state will not match the promise we will momentarily make to our component.

interface ComponentStateProps {
  crucialView: CrucialObject;
}

// The compiler will catch this because our object does not match the return signature
const mapStateToProps = (state: State) : ComponentStateProps => {
  return { crucialObject: state.crucialObject.firstKey };
};

Finally, we can reuse the ComponentStateProps so references within the body of the component can be matched to our interface.

class MyClass extends Component<ComponentStateProps, any> {
  // The body is unchanged, but if we call upon `this.props`, we'll see the injected state keys.
  // If we changed our State Props interface, dependencies in here will become immediately clear
}

And there we have it: dependencies are clearly defined and will be hightlighted by the compiler if broken. If we need to add another reducer, we can continue extending our State interface:

interface State extends CrucialValueReducer, CurrentUserReducer {};

We are now covered from multiple angles.

  • By identifying an object as a State, I know what data is available.
  • By matching the output of mapStateToProps to my component’s input, I can be confident that the state will move safely from Redux to the view

I find it weird that in all my reading about TypeScript and Redux, I could find dozens of examples of adding types fo reducer inputs but almost nothing about outputs and the sanctity of state. Maybe there’s a simpler way of handling it? If so, I’d love to know. Regardless, TypeScript is a joy to work with and this helps get more out of it in a busy app. This is one case where you have to give it a few hints up front, but then it will keep its eyes open for you forever.

A Tale of Two Libraries

Work has kept me busy this year, but the past few months were slightly more of a challenge than usual when I was thrust into the world of front-end development. All of our front-end engineers were gone, updates were needed, I like learning new things, so that was that. We have two React apps at work, one slighly older that uses Flux, another a bit newer using Redux. They were each configured by different people and demonstrated many different ways of doing things. After a few weeks of writing production code and quite a few frustrated IMs to friends, I reached a point where I was feeling good about my time with JS, React, and front-end development as a whole.

This is not a story about that, though.

At some point after I reached that “maybe-I-don’t-totally-suck-at-this” phase, I started helping a friend with a project that needed a front-end app. It seemed like it would be a good fit for React, so I though this would be a nice opportunity to start with a fresh project and see the best practices of people out in the JavaScript community.

I had it in my head that configuring Webpack, React, Redux, etc,… from scratch was a pain in the ass. Since the setup portion was the area that I felt least confident, I thought I would do some research and find the best React starter repo and use that as a template. After all, a popular project would probably reflect the current state of the art and include all kinds of helpful things that I and my former co-workers might not have known about!

I did some research. I wanted something that already had React 15 and the modern versions of React-Router and Redux. I wanted it to preferably already have a test framework setup. It had to use webpack, naturally, have SASS support, and hot reloading. These requirements didn’t seem too demanding but findind the right library proved a little tough. There’s a lot of old stuff out there, a lot of of libraries using old versions or missing pieces. Finally, I settled on an extremely active React starter project that had all the right versions, the right config, the right number of Github stars, the right number of contributors and people responding to issues. Sweet! I cloned, I copied into a new repo, I got to work.

Things were weird right away. The sprawl was insane. Unreal. Every conceivable tactic to split this project into extra files had been employed. Each route was split into pieces, some routes had dedicated components, others had dedicated containers, others… those are just routes, you have to find the rest of those pieces. The webpack config was split and split and split. Always quick to assume that I’m just a primitive Ruby engineer who doesn’t understand the ways of these sophisticated front-end professionals, I put my head down, refactored it a bit to make it more sensible to me, and pushed through.

It worked for a little while. Sure, every time I had to add a new route or component, I felt like I was jumping through flaming hoops that were also screaming at me and dancing around and covered in spikes, but… I just had to adapt to their modular approach! This was a “fractal” file organization, broken up by features. (Forget the fact that today’s unshared, feature-specific code and assets are tomorrow’s reusable time-saver and this reeked over pre-optimization.) I spent more and more time. I wrote some cool code. Things started coming together.

Somewhere along the line, I simplified the routes, components, and containers to look more like one of my apps at work. It felt less sophisticated but no matter how much I read, I couldn’t find any evidence that anyone else was actually using this library’s approach to file organization. Oh yeah, also, my huge production apps at work looked nothing like this and they were doing fine. Oh, and no repo that I had ever looked at was organized like this. I again considered that maybe there was something wrong with this library’s approach.

It came time to do some styling, so I asked Lauren (my wife, she’s good at that – she also taught me JavaScript in the first place) if she could help us out. I got node and everything installed on her laptop, and we realized… where do we put stylesheets? Where do we put assets? How do we require librarires? We had to add a webpack loader, where did the config go?

Those flaming hoops that we had to jump through to make things work? There were no hoops at this point, just fire. We had to find a way to just jump through the fire and make things work.

After a lot of stress, we got everything working. The app was styled, everything looked good!

Finally – finally! – things seemed pretty stable. I thought everything could be left alone for a little while.

But then I read about this cool new library: webpack-dashboard. It made my webpack config look all… pretty, ‘n stuff! I wanted to use it. I started following the documentation aaaaand…

Everything broke. Everything fucking broke. I could not figure out where to even start making the simple changes required to make this thing work.

That was the end! Fuck this shit! I decided to find another library to use as a baseline for the project. I’d rip my code out, configure the stuff I didn’t want to configure before, and know that I had something predictable.

A few weeks after I started the new project, create-react-app was released. It was super barebones – no Redux, no Router, no tests, no SASS – but fuck it! I’d figure out the rest!

I cloned it, I ejected (cause I’m a control freak who likes to see more of his dependencies), and guess what jumped out at me immediately?

It was so. fucking. simple. There were so few files. It was so predictable. There were a few clearly configurable options, but it was all totally declarative, easy to expand, easy to reason about. I quickly wired up everything I needed, ported over my code, and had it working. Since then, there have probably been a dozen little tweaks I had to make to my webpack or test config and it never fucking surprises me or breaks. I keep an eye on the project’s repo to see what changes they’re making and if I see something I like, I follow their lead.

WHAT’S MY FUCKING POINT, THEN?

I’ve got a few.

My first point is that complicated code is not necessarily healthy code. Libraries that aim to be all things to all people run the risk of becoming amalgamations of many organizations’ infrastructures, not examples of how any one organization would ever handle their infrastructure! The first React starter library I used was more of a tech demo (“LOOK AT ALL THE CRAZY SHIT YOU CAN DO WITH REACT!”) than a reasonable approach to project organization.

My second point is that even if you are an outsider to a community, a little scepticism can be healthy. I try to approach languages and frameworks openly, with the belief that their practices evolved naturally and their patterns must work for them or else they wouldn’t have made it that far. This is especially true when it comes to something like JavaScript, where there is a rapidly evolving, complex ecosystem full of brilliant people. Who am I to tell them how to do things? I am not an experienced front-end professional like these people! Yeah, well, those are nice ideas and all but they betray the fact that I am not new to code, organizing projects, or the patterns and practices that lead to maintainable, reasonable production-ready code. You, reader (JK nobody reads this), might be in a similar situation, and to you I say: trust yourself. Don’t immediately shit on other ways of doing things but if something strikes you as weird – too engineered, too sprawling, oddly-named, whatever – you’re probably right. You don’t have to be a fucking JavaScript expert to see that.

Finally, remember that at the end of the day, doing things “right” by the standards of a community (of fucking strangers, who gives a shit?) should be secondary to feel productive and shipping. Don’t feel obligated to change tech or put up with patterns that just do not seem to be sticking if it’s getting in the way of your work. I should have punted on the first library right away.

And that’s that. I’ve been happy as a clam since then, coding and shipping. My project is getting pretty intense and I’m eyeing TypeScript as a way to make things more reliable. I branched and started the conversion but noticed a lot of weirdness around the different approaches to obtaining type defs, so once I spend some time configuring my project for global typings and… WAIT A MINUTE. NOT THIS AGAIN. I’M WAITING FOR 2.0.

Extremism and Inclusion in the Metal Underground

A well-known-in-the-underground, extremely liberal band called Caïna were kicked from a German music event for covering the band Death in June in the past. You can read their statement about it here.

This situation is sad for many reasons. Among them, it’s a reminder that many people view others in very black and white, static terms, where reflection, discussion, and growth are impossible once any connection to “shady” ideas or people have been made. They see Death in June’s Douglas P as someone who, despite owning his mistakes as the actions of a young person trying to find his way in the 80s, will be forever tainted. Worse still, they see someone like Caïna’s Andy Curtis-Brignell as equally untouchable for agreeing that Douglas could grow up and should not be punished for mistakes he is trying to move past. These are the same people who reject reformed skinheads from participating or object to bands containing minorities have been photographed wearing shirts that they find questionable.

Call me crazy, but I think that the most powerful advocates for social change in metal are people with connections to things that make us uncomfortable. I have more than a few friends who had terrible opinions when they were young but grew out of them. The keys to this transformation: the opportunity to relate to people with different backgrounds and shared interests. The time and place to realize that their attitudes just don’t make sense.

Nothing erodes racist attitudes like finding common ground and building connections with different types of people. People who go through these transformations understand how others end up where they were. Their inclusion in the underground makes the statement that it’s possible to change. Their presence is crucial, even if what they contribute in the fight against extremism happens slowly and without any deliberate actions. The wholesale rejection of individuals who at some point engaged in actions we find questionable makes it harder, sometimes impossible, to reach those who need common ground the most. This goes for folks who grow out of terrible perspectives and those of us who are willing to accept change in others.

But back to Caïna and this specific event, Andy is exactly the type of person we need more of in the underground. Very few black metal artists are willing to make strong statements against discrimination – he is one of those few. He probably also has a surprising number of listeners who disagree with his views, which means that his music can often present opportunities for communication between people who would otherwise have trouble finding common ground. To prohibit his music and his fans from participating in an event because he chooses to believe that people can change, that art can unite, is a sad, sad decision with profound implications.

I think about this whole thing and wonder if there is someone somewhere who actually does have right-leaning tendencies and will take this as one more reason to feel persecuted and isolated. They’ll say that this is more “SJW PC nonsense,” they’ll be more willing to side with actual skinheads when they are kicked off of a show for actually being shitheads, they’ll make shittier friends, and they’ll fall deeper into this pit. I’m not saying that this one incident is the start of a slippery slope – I don’t see how it could be – but it contributes to a worldview that is best fought through inclusion and dialogue, not exclusion and shame.

Instance Variables, Methods, and the Public API

A post the other day on /r/ruby asked about the reasoning behind the recommendation that instance variables be accessed through methods instead of directly throughout code where they are in scope. Most of the responses dealt the fact that this helps make your code more maintainable, which is true, but I think there’s a more significant reason for this: it adds data to your class’s public interface, so it encourages healthy design habits and forces some introspection.

In a carefully designed class, changes to interface are taken seriously. Before you add, remove, or change it, you should ask some questions, the most important (in my opinion) of which are, “Is this method reasonable, given the stated purpose of this class?” and “Is this a method something that users can trust to be there and work properly in future releases of this library?” When you expose an instance variable as a method, you implicitly respond to both of those statements in the affirmative, so think carefully about whether those questions are also true of that instance variable!

When you find yourself in the position that you have an instance variable that shouldn’t be exposed as part of the public API, consider that you might have a class with too much responsibility or an instance variable that you don’t need. Unneeded instance variables often come from doing this:

def my_process
  get_foo
  use_foo_here
  use_foo_again
  return_value
end

def get_foo
  @foo = ObjectLookup.find_by(quality: 'foo')
end

def use_foo_here
  @bar = @foo + 10
end

def use_foo_again
  @baz = @bar + 20
end

def return_value
  @bar > 40 ? @bar : @foo
end

…when something like this is healthier in every way:

def my_process
  foo = get_foo
  bar = plus_10(foo)
  baz = plus_20(bar)
  return_value(foo, baz)
end


def get_foo
  ObjectLookup.find_by(quality: 'foo')
end

def plus_10(obj)
  obj + 10
end

def plus_20(obj)
  obj + 20
end

def return_value(starting, ending)
  ending > 40 ? ending : starting
end

Yes, there are times whenyou want to reuse an expensive query multiple times internally within an object and exposing it to the public API would be inappropriate. That’s fine, just mark that method private. But that should be your last result, not an excuse for extra data. Changes to the public API are an opportunity to question your approach and improve the quality of your code, so face them head on!

Now with 100% Less WordPress

Since 2011, this blog has been powered by WordPress. As of today, it’s entirely static and generated by Jekyll. Isn’t it funny how things have changed?

WordPress is a very cool product. It does so many things so well and has managed to dominate such a huge portion of the web that it demands respect. I can sum up my feelings about it pretty easily:

  • The templates and plugins system is great, mostly.
  • The basic WYSIWYG editor is fantastic until you discover Markdown.
  • It’s easy to update your installation and your plugins, except when it’s not.
  • Update recommendations help keep you safe, as long as you check frequently.

In other words, its strong points are really strong but its weak points – its risky plugins, the horror that is troubleshooting when something breaks, the need to constantly be on top of security as a result of its huge API – are pretty big for someone who just wants a place to talk shit every few weeks or months.

Sometime last year, we launched an official site for Neo4j.rb, Neo4jrb.io, and decided to host through Github.io and use Middleman. It’s been wonderful. My big takeaways from a year-ish of working with a statically generated blog:

  • Local dev and Git deployment > remote Admin page. It makes writing as convenient as coding.
  • Vim and Markdown > WYSIWYG editor. It makes writing as fast as coding.
  • We essentially don’t have to worry about security.
  • Modifying HTML and CSS > modifying themes.

It was kind of a no-brainer. I wanted something to help me write more often and this seemed like a good excuse, so I took the plunge. Even though Github.io is free, I decided to self-host because I like having an SFTP server and space to experiment. A search revealed a WordPress plugin to migrate content straight to Jekyll, so that made the platform decision easy. Ultimately, migration was simple enough:

  • Basic new server setup: nginx, users, updates, etc,…
  • Export old content using this plugin
  • Install rbenv, Ruby, Jekyll and related gems
  • Install git and configure post-receive hook, mosty descrived here
  • Tweaks to migrated new blog: styling, fixing some things the migration didn’t get right, install/configure jekyll-archives

It took most of a day, when said and done, but none of it was what I would describe as “hard.” There are still some styling tweaks to make but I’m happy with it, overall. The real hard part comes next: actually writing more often.

subscribe via RSS