Showing posts with label typescript. Show all posts
Showing posts with label typescript. Show all posts

Monday, January 24, 2022

Setting up a test bench for TypeScript compiled client code with Node.js (why are things like this?)

My first computer was an Apple ][c owned by my parents. In that environment, booting the machine with no disk in the drive would load a working development environment in the form of an Applesoft BASIC REPL.

Sometimes, when I spend an hour configuring a development environment for testing a web application, I miss those days.

I've uploaded a bare-bones testbench to GitHub for playing with TypeScript code compiled to run in a browser client. To do so, I set up the following dependencies:

  • typescript
  • webpack (collects JavaScript into one file)
  • ts-loader (lets webpack drive TypeScript compilation)
  • webpack-cli (command-line tools to drive webpack)
  • webpack-dev-server (server to watch system changes)

Once these were installed, I had to set up with a tsconfig.json file for TypeScript and a webpack.config.js file for webpack. It took a little while to pull all the pieces together, but the nice thing is that now they're set up and I don't have to do it again.

Why are things like this?

When I look back on how programming was when I started vs. now, I get nostalgic from time-to-time about how things were simpler. We just turned the computer on and coded it! What happened?

More flexibility means more complexity

The computer I coded on when I was six did exactly one thing at a time. Meanwhile, as I type this, I have my testbench open in another window, documentation for npm in a second window, my blog statistics open in a third window... Modern computers are simply more flexible, and there does exist a strong correlation between flexibility and complexity.

In a real sense, the art of software engineering isn't creating features, it's denying options. The most featureful computer is a machine exposing a REPL. You can do anything it can do! You just have to write the code! But we've built an entire global industry around paring down the set of possible things a computer could do to the subset people actually want to do (and in so doing, surfacing those features behind a few buttons at the cost of pushing every other feature of the machine deeper into a tree of options). An Apple ][c with no disk in it "knew" I wanted to program something in BASIC when I turned it on; a modern computer has no "idea" what the user wants.

Since building a tiny web server with TypeScript and Node.js is as likely to be what I want to do as checking my bank account, there is necessarily more complexity to make it happen.

Embedded development isn't like desktop development

Since I'm working on "just some browser stuff," it's easy to fall into the trap of thinking that what I'm doing is simple. Browsers are easy to code; pop open one text file and start writing.

That's true... If you want to code in HTML and JavaScript. But add TypeScript to the mix and, oops, I'm not doing "native" coding anymore. Now I need an infrastructure to deal with the impedance mismatch between the fact that the browser only understands JavaScript and HTML and the fact that the only context I'm willing to code in bare JavaScript anymore is if a child's life is on the line (and even then, it'd better be a child I like).

Looked at in this way, writing web comtent in TypeScript isn't even just compiled; it's more like embedded development: we are writing code in a language not directly supported by the embedding target (the browser) and we need to update the target's view of the code when it changes (recompile and put the data where the browser can see it). In that sense, writing web content with TypeScript looks a lot more like writing code against a microcontroller (albeit a fancy microcontroller run in a virtual machine on my desktop) than writing a BASIC program. Some complexity is to be expected. 100% of the dependencies I installed were to support automatic recompilation and hosting of changes to the code without having to stop and re-start a server.

The real problem is discoverability

At the end of the day, none of these problems would be problems if I already knew what I was doing. This testbench isn't the first one people have written (nor will it be the last). But currently, a search on GitHub for typescript node testbench only returns my code repository!

A view of the GitHub search interface, showing typescript-node-testbench as the only search result for "typescript node testbench"
This can't be true.

I can hope that someone sees this blog post and that the existence of my project somehow gets into StackOverflow or Google search results, but ultimately, this is the real complexity of modern programming: when you want to do something relatively simple, how do you get started? In the '80s, I could start by powering on the computer. How do I start now? typescript node getting started returns several more results, but none quite what I'd want (most of them add more complexity than I need; many are descriptions of how to solve the problem, not workable starter code).

This problem isn't trivial to solve; computing moves fast these days. Several of the technologies I'm using for this project didn't exist ten years ago. But putting starter frameworks in a place people can find them (and perhaps, even, creating a language where people can describe what they want) still feels like a problem in need of a better solution.

We've made incredibly flexible machines, and our ability to talk about them hasn't caught up to the inherent complexity of that flexibility.

Monday, January 3, 2022

Making a turn-based game: Don't prematurely optimize, and different types of turns, and code available on GitHub :)

One of the things I wanted to add to Swătch was the ability to play different types of games. In addition to the initial game of "choose the shade of a color based on its name," I wanted to have the following:

  • Given a shade and several options, pick the correct name
  • "Trick" mode: each player makes up a name for a displayed color shade. Then, they're shown the names provided by other players in addition to the correct name. Choose which name was the correct name (players also get points for tricking the other players into choosing their name).

Supporting this atop boardgame.io proved extremely possible, with just a bit of work.

But first, a digression...

Don't prematurely optimize!

To support the "choose name based on shade" mode, I needed to extend the JSON file listing the set of all colors to include references to several nearby colors in the dataset. There are several clever approaches to this, but I chose the simplest one: for every color, find the distance to every other color and assign the N nearest as nearby colors. This is an O(n2) algorithm; pretty inefficient.

But since it was easy to code, I ran it anyway. On a 1,500 line input, it took about 0.1 seconds.

Friends, computers are fast nowadays. For heavy-lifting computation, don't burn time on being clever when you can use the sledgehammer of modern clock speeds.

Different types of rounds

Boardgame.io provides a fairly robust framework for distinct game turns, as well as describing what moves are valid in different stages of play. The framework also supports hidden state (both global and player-specific) for each player. Originally, I constructed the game with just a single type of turn, the guess-the-shade-from-the-name turn. To support multiple different types of turns, I made the following changes:

  1. Added a Round interface, which described a round of play by providing the following methods:
    • initState: Prep the public and private state for the round (set to initial, empty values)
    • onBegin: Begin the round, choose hidden values (such as what color to guess), set up player state.
    • scoreRound: Calculate and update scores and assign "best" (and possibly "second best") answers for later display.
    • buildPreviousRound: Every round, upon conclusion, bundles its results into a previousRound data structure used to describe how the round went to the players. This is the method that turns the round state into that structure.
    • moves: A map from the valid moves in this round to the code to execute them
    • getPlayerState: Accessor for the per-player state for this round.
    • getPublicState: Accessor for the public state for this round
    • getLastRoundState: Accessor for the previous-round state for this round
  2. With the interface in place, I moved around the existing Context state to carry different types of context depending on the current round (and reworked the client-side code to pull from those new contexts and show a specific view based on what the current round was).
  3. Now, I could refactor the existing turn logic into a GuessShadeRound implementation and generalize the boardgame.io-provided onBegin and onEnd methods to select a round to play (with only one option currently available) and score the round when everyone had taken a turn. At this point, the refactor could be tested.
  4. I built out a Rounds.ts file to consolidate the separate round implementations.
  5. With all of that out of the way, I could write three more Rounds:
    • GuessNameRound, which shows a shade and asks players to select the right name for the shade.
    • A pair of sibling rounds: MakeUpNameRound and GuessMadeUpNameRound. These are special-cased: instead of the turn ending when MakeUpNameRound completes, it transitions directly into the GuessMadeUpNameRound and calls that round's initState to prep up the round for it.

This is all tough to follow from description alone, which is why I've made all the code available on GitHub to see. Feel free to run it locally and give it a try!

Monday, December 6, 2021

Making a turn-based game: Getting started with boardgame.io

For my game, I went looking for a framework that would handle some of the boring parts and free me up to focus on the game mechanics and logic. It didn't actually take much hunting to stumble upon boardgame.io, which I was surprised to discover handled just about everything I wanted.

In this post, I'll talk a bit about my choice of engine and the steps I took to get started.

Architecture

The boardgame.io framework has several features I appreciate:

Language and libraries

  • Designed to run on NodeJS, which I'm already familiar with
  • Includes React components
  • Includes TypeScript type bindings

Features

  • State synchronization between server and clients
  • Client-side prediction of next move on public state, to speed up the experience
  • Automated client information hiding
  • Game state machine library
  • Debugging UI
  • Integration with a couple of backing stores
  • Rudimentary multi-game server and client lobby

The framework was designed with Heroku in mind, but I was able to get it working on a shared DreamHost server. For the remainder of this post, I'll go into that process (which involved a lot of dead-ends, but eventually worked!).

Getting started with a boardgame.io project

For this project, I set up a pretty standard Node project:

  • installed nvm using the wget directions
  • nvm install 12.22.7 to sync with version required by DreamHost for compatibility with Passenger Phusion
  • configured the project to use TypeScript
  • Started setting up the boardgame.io tic-tac-toe tutorial

By the end of this stage, I had the following files set up:

tsconfig.json ``` { "compilerOptions": { /* Language and Environment / "target": "es6", / Set the JavaScript language version for emitted JavaScript and include compatible library declarations. / "lib": ["es2015"], / Specify a set of bundled library declaration files that describe the target runtime environment. */

/* Modules */
"module": "commonjs",                                /* Specify what module code is generated. */
"rootDir": "src",                                    /* Specify the root folder within your source files. */
"moduleResolution": "node",                          /* Specify how TypeScript looks up a file from a given module specifier. */

/* Emit */
"outDir": "build",                                   /* Specify an output folder for all emitted files. */

/* Interop Constraints */
"esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": false,           /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true,                                      /* Enable all strict type-checking options. */

/* Completeness */
 "skipLibCheck": true                                /* Skip type checking all .d.ts files. */

} } ```

tslint.json


{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "no-console": false
    },
    "rulesDirectory": []
}

One note about the boardgame.io tutorials: they'll mention using parcel-bundler, but it's deprecated for parcel.

Next on the list was to set up React.

  • npm install react (which gave me v17.0.2)
  • npm i --save-dev @types/react
  • add "jsx": "react" to compilerOptions in tsconfig.json
  • npm install react-dom
  • add dom to lib in compilerOptions
  • add "include": ["./src/*"] as a peer to compilerOptions (note: src/* is not the same and will result in failure to find modules)

This gets us halfway to a working solution, but to serve from DreamHost, we'll need to have a JavaScript program that Node.JS can run and a program (likely one JS file) that can be vended to the client. Configuring that is the next step.

Monday, November 22, 2021

When not to use classes in JavaScript

... all the time.

Do you want to be more specific?

Okay, yes, I probably should.

JavaScript is secretly a very simple language with some ill-thought-out features layered on top of it. The most famous one is probably the class architecture, which started as "duck-typed" (objects can have arbitrary fields assigned to them), prototype-based (an object is only a specific kind of object because it happens to have a previously-very-visible-but-now-hidden-the-visible-field-is-deprecated-forget-I-mentioned-it-__proto__-what-is-that-even "Prototype" property that adds fields beyond the ones living directly in the object), and mutable (an object can become a different type of object by calling Object.setPrototypeOf(instance, newPrototype), which on modern browsers will stab your performance directly in the jibblies but will also change an object to another type of object). Instances of classes are very convenient—Who doesn't love getting an object and just calling myObject.doSomeStuff(args)?—and they can really help you organize your code.

Here's why you should use them less.

They require special serialization and deserialization

Since you're using JavaScript, you're probably in a web browser or talking to a web browser (note: if you are using JavaScript and not in those circumstances, I'm sending you a digital hug and I highly encourage you to explore the wide, beautiful world of programming languages that aren't a hacked-together shambling mass built atop a Netscape demo from 1995 with name and syntax specifically chosen to capitalize on the popularity of a totally-unrelated language to the Scheme that birthed it). This means that sooner or later, you're shipping data over the network to or from the server. If your data can be represented as 'POJOs' (plain ol' JavaScript objects), the entire process of converting the data to or from network format is a single pair of library calls in modern JavaScript runtimes, JSON.stringify and JSON.parse. You'll likely still need to validate the parsed data is the right format, since the Web is a hellworld full of active attackers (such as your own server code compiled to the wrong version), but you're 90% of the way there.

But if your objects are class instances? Oh dear. I'm sorry you did that to yourself. Don't forget to define a toJSON method to explicitly select what fields you want serialized, and keep it up-to-date as the class changes. If you don't, you'll get the object's "enumerable properties" (what those are is left as an exercise for the reader). And on the deserialization side, don't forget to specify a reviver function that takes pieces of your parsed JSON, pattern-matches them against the original instances, and uses the class constructor to change the object to an instance. Be careful: reviver is looking at sub-trees and you're at risk if some sub-trees with the same properties should be different classes; I recommend synchronizing the toJSON for those classes to add a 'tag' field that can be inspected to pop the POJO back into an object instance. And don't forget to synchronize all that serialization and deserialization logic with the server's representation of the data, or uh-oh!

... or you could do none of that, and just have the in-memory object representation track more closely to the on-wire model by not using classes.

They add overhead

Every instance of an object is carrying around some indication of what its prototype is. That's not a lot of data on a large object, but on a small object (such as an RGB "Color" specifier or a three-number 3D coordinate), the "what kind of thing am I" field is over 10% of the data stored in the object. And since JavaScript is so dynamic, there are very few optimizations the runtime can practically do to strip out that data. Unless your code frequently has to pass colors or 3D coordinates in the same information channel and doesn't know which (which we might consider a code smell), all those extra "Hey I'm a color here are my methods" tags are wasted space.

They're a pain in the ass to unit test

What you want to do in unit tests is confirm your functions manipulate state correctly. Because class use encourages state hiding, it makes it trickier to write unit tests... Do you want to test your private or protected methods? "No," says the purist, "you should test your public API." Okay, but the public API is relying internally on some couple dozen private functions, so now I'm writing big, jangly dependency-heavy tests to get around the fact that I can't just call myInstance.privateMethod directly and test its output. And if I'm using a mocking library, I'm now mocking stuff up in MyClass.prototype, and sometimes I'm working around private methods by adding a makeTestable public method of some kind... It's all a bit of a mess. JavaScript's class model has no escape hatches for letting test logic sneak a peek into the permission space of a class, and it's frustrating.

Inheritance and instanceof are traps

One reason people sometimes turn to classes is inheritance. The "Shape" that could be a "Circle" or "Rectangle" is the most classic example. Tricky thing is, it's also one of the more corner-case examples (are you doing GUI programming?); many inheritance hierarchies aren't nearly so clean, and JavaScript handles the classic "diamond of death" problem (where one class inherits from two other classes that inherit from the same base class) by... Not allowing multiple inheritance. Inheritance also somewhat clashes with the mutable-class "feature" of the language... You can change the type of an object by editing its prototype, but you can't edit the prototype chain to, for example, swap one instance's grandparent with some other class (if you try to do so by editing prototype relationships, congratulations... You've now mutated every class in your runtime).

When you have to dynamically determine if an unknown object is an instance of some class, you can use the built-in instanceof operator. This walks the prototype chain for the object to see if the specified class shows up anywhere as a parent. This works great until you get into anything complicated involving libraries and modules. Suddenly, you discover that your ThreeDCoordinate isn't a ThreeDCoordinate because it was built with ThreeDLib version 2.7, but you're using npm and the code you're running right now is in a library you added which is depending on version 2.9 of ThreeDLib, and no, the 2.9 and 2.7 ThreeDCoordinate classes aren't the same class even though they are 100% the same code.

So what should we do instead?

JavaScript is actually perfectly capable of supporting a functional pattern riding atop POJO data. In this model, we rarely use classes; we just build objects by calling functions that instantiate them and manipulate those objects as "bags of data referenced by field." In fact, the language's "duck-typed" nature makes this simpler than in other languages: we don't have to be overly-cautious about type. I don't need my inputs to getDistance(coord1, coord2) to really be ThreeDCoordinate objects; if they have x,y, and z fields that are numbers, I can act on them.

With POJOs manipulated by functions, I don't need special handling for serialization, my objects are much smaller (and I can't modify a prototype chain so I can't incur the expense of doing a very slow operation in a modern browser), and I can get inheritance by either extending objects (taking one object and adding fields to it... Not great, because this also incurs browser overhead) or composing objects (making a new object that has a field containing the "parent" object).

There are some possible downsides to this approach. One is the lack of enforced discipline in only having some methods available on some objects means you'll have to be more careful with your code to keep your inputs straight (it's easier to pass the wrong object to the wrong handler function if you're not referencing the methods via myObject.method()). Another is functions divorced from the data they care about can tend to end up wordy; it's no longer myCoordinate.translateX(value), it's ThreeDCoordTranslateX(coord, value). The latter is actually a namespace problem, not a class problem; modern JavaScript offers some good tooling around namespacing functions (either via modules or the "poor man's module," a class full of static functions (one weird tip; Google hates it)).

One additional downside is the lack of private members. To be honest, while I find these conceptually useful I don't find I need the language itself enforcing discipline around them these days. My experience is that the question "how private is private" is wuzzier than I want it to be. The object model enforces it as "data only visible inside the methods of the class," and I find myself needing to "jail-break" that abstraction (for testing or "friend-class" reasons) too often. For functions, I can get privacy by scoping them to the module level. For data, if the API is sufficiently complex that private data matters, I put creation and maintenance of the object behind constructor and mutator functions and only change the data through those functions.

A TypeScript plug

It's definitely worth noting that I don't program much in plain JavaScript these days. The language enables a lot of shoot-your-own-leg-off opportunities regarding its near-total lack of static type enforcement.

To implement the approach I'm describing here, what I really do these days is build my types of objects as interfaces and use interface inheritance to indicate when one object can be treated as a subset of another object. I construct objects in functions declared to return a particular interface-conforming object and write functions that take in a particular interface-conforming object. The compiler will do the work at compile time to let me know if I'm trying to pass the wrong type to the wrong function. In the relatively rare cases that I'm handling multiple types of object on the same channel, I can use tag fields (or the structure of the data) and type guards to turn mystery-typed objects into an understood type.

The zeroth rule is there are no rules

I've been hard on classes, but this walk has been a bit tongue-and-cheek. In reality, classes are an integral part of JavaScript, they aren't going anywhere, and it's okay to use them. I wanted to get us out of the mindset that they're the only way to solve problems, so I've asked you to imagine a world where we should never be using them.

I actually use them often, but I have some specific rules of thumb on when to use and when to avoid them:

1. If you have a big type family and inheritance is cheaper than special-casing

If you're dealing with a family of a dozen or more related types, where most of them share implementation but a few do have special handling needs (i.e. the traditional "shapes are circles and rectangles" problem), you may very well be better off using classes than an elaborate family of handler functions and special-case logic for switching on particular instances of the type family. In my experience, big bags of things mapping to tangible objects will fit this description.

2. Don't use them to describe data on the wire

It's hardly ever worth it to do the heavyweight serialization / deserialization of mapping data on the wire to class instances. If your data is going on the wire, keep it simple. Note that point 1 and point 2 come into conflict sometimes. There is no universal answer here; you'll be making tradeoffs one way or the other if you class-up your big type family that also serializes onto the wire. At least if you go that road, you can make implement toJSON on every class and a reviver that understands the whole class family part of the process.

3. Don't use instanceof

At this point in my career, I consider instanceof harmful; it actively conflicts with the ability to use different versions of a library in the same codebase, and fails in silent and confusing ways. It also bakes knowledge of the class hierarchy into possibly-unrelated code. Try not to do it.