A Lazy Sequence Recent https://brehaut/feeds/everything 2018-04-25T03:19:57.399Z Andrew Brehaut andrew@brehaut.net String tension and pick thickness https://brehaut.net/blog/2018/string_tension_and_pick_thickness 2018-04-25T03:19:57.399Z <p> I rarely see people mentioning pick thickness when they are talking about string gauges with guitar<sup>1</sup>. One of the key features of string thickness, and its more general cousin tension, is how much effort is required to make the string resonate. One way this is manifested is in overall loudness. Another, and more interesting here, is the ratio of attack to sustain of the note. We experience attack as a bright high frequency tone at the start of the note. Increasing the ratio of attack to sustain therefore increases the brightness we hear, particularly when strumming. </p> <p> You can think of the attack as that initial blast of the note when the string is pulled far out its resting position by the pick, so it makes sense that how easily the pick can pull the string without giving way is directly related to how much attack is present. A more rigid pick will therefore generate more attack than a softer pick. The softer pick will give way to the string more easily. </p> <p> Based on this, and you can back it up with a bit of experimentation, if you change your string tension – by changing string gauges, the scale length of the guitar (e.g. moving from a Les Paul to a Strat), or tuning scheme – it’s worth experimenting with some different picks at the same time to find what works best. I know some players, such as my friend Stephen, who are happy just compensating with their playing style, but I’ve found I need the more material change as well. </p> <ol class="footnotes"> <li>As an example <a href="https://www.youtube.com/watch?v=9AYmYcAwAgY">That Pedal Show – String Gauge & Tone.</a></li> </ol> Don’t use <code>obsolete</code> attributes for internal code https://brehaut.net/blog/2018/obsolete_attributes_are_external 2018-04-24T01:06:23.091Z <p>The <code>obsolete</code> (or in some <code>deprecated</code> languages) attribute or decorator is a useful tool for a library to signal to its consumers that part of it’s API has been deprecated. </p> <p>Using it on internal&mdash;owned by the same team&mdash;code for a project should be avoided.</p> <p>Marking something as obsolete will generate a compiler warning (in a statically checked language at any rate), and committing code into trunk that generates warnings should be avoided. We only have two options with warnings: dealing with them, or ignoring them. Tolerating warnings is an instance of tolerating entropy in the code base. </p> <p>If a piece of code is not yet removed from the project it’s not yet obsolete, even if there is a better alternative available. We want to encourage active ownership of the cleanup code problems, rather than a passive hope that everyone else will do the job. </p> <p>This becomes challenging when the aspirationally obsolete code is pervasive and will take a long time to remove&mdash;maybe there are reasons why untangling it from an older piece of code will be difficult. How do you indicate to your colleagues that the old version should not be used without throwing a lot of new warnings into the product?</p> <p>Create tickets in the job tracker, and get buy in from the team to commit to eliminating the problem code piece by piece. No new warnings are introduce, the old code is actively being addressed.</p> <p>For larger teams, this can be supported by marking the code as obsolete, but annotate all the existing call-sites with a pragma to ignore that specific warning. This way, any new usages would become warnings, but existing usages would not. As a bonus, the process of adding these pragmas may be impetus to address lingering easy cases.</p> Leveraging <code>Pick</code> to simplify testing https://brehaut.net/blog/2018/simpler_testing_with_pick 2018-04-22T23:28:23.577Z <p> Sometimes you have to write a function that takes a parameter that is some massive type that is outside of your control. That can be a nuisance to test. The amount of infrastructure needed to work around this will depend upon the size and scope of your project, but for the smaller projects TypeScript has a helpful tool: the <code>Pick</code> type. </p> <p> <code>Pick&lt;T, K extends keyof T&gt;</code> is a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types">mapped type</a>. <code>Pick</code> produces a new type that is a subset of of <code>T</code>, with only the keys specified in <code>K</code>. </p> <p> As an example, say you wanted test a function that consumes a Node http <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/aa93526d48b171bcec787e806993332ffd9b3128/types/node/index.d.ts#L1089-L1119">IncomingMessage</a>. Producing a synthetic value of this type as written is going to require a lot of boilerplate. If you only need <code>method</code> and <code>url</code>, that’s a lot of overhead. Instead, if you specify your function as taking <code>Pick&lt;IncomingMessage, "method" | "url"&gt;</code> you can trivially mock up a series of plain JavaScript objects that fulfill that interface. </p> A minimal TypeScript dependency injector https://brehaut.net/blog/2018/minimal_typescript_dependancy_injector 2018-04-20T23:09:45.417Z <p> <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency injection</a> is a handy tool for building systems. For small projects I just want a small simple implementation of the ideas. This post is a quick look at the implementation I cooked up with TypeScript that covers everything I need for a number of the small systems I’ve been writing recently. </p> <p> Aside from the decoupling system components, I wanted this to make it trivial to ensure that components start up in the right order, and I wanted it to leverage the type checker and inferencer to ensure that the given system is complete. There’s no support for configuration files, or more complex component life cycles. </p> <p>Here’s the whole thing:</p> <pre><code class="brush:javascript;">export type Injector&lt;T&gt = &lt;K extends keyof T = keyof T&gt(key: K) =&gt Promise&lt;T[K]&gt; export type Injectable&lt;TComp, TDeps = {}&gt = (injector: Injector&lt;TDeps&gt) =&gt Promise&lt;TComp&gt; export type SystemDescription&lt;T&gt = { [P in keyof T]: Injectable&lt;T[P], T&gt; }; type Pending&lt;T&gt = { [P in keyof T]: Promise&lt;T[P]&gt }; export function startSystem&lt;T, K extends keyof T&gt(s: SystemDescription&lt;T&gt, primary: K): Promise&lt;T[K]&gt { const pending:Partial&lt;Pending&lt;T&gt&gt = {}; function getPending&lt;K extends keyof T = keyof T&gt(key: K): Promise&lt; ;T[K]&gt { if (!pending.hasOwnProperty(key)) { pending[key] = s[key] (getPending); } const p = pending[key]; return p!; } return getPending(primary); }</code></pre> <p> The description of all the types is a little tangled, but actually its pretty simple once you boil it all down. The first bit to look at is the <code>SystemDescription</code>. This is a mapping of names to <code>Injectable</code> functions. At some point this <code>SystemDescription</code> will be passed to <code>startSystem</code> and it will fire everything up. <code>startSystem</code> will return the component named by the paramater <code>primary</code>. </p> <p> <code>Injectable</code> functions simply take an <code>Injector</code> function, and return a <code>Promise</code> for a component. The <code>Injector</code> is simply a function that when given a key, will return a <code>Promise</code> for the matching component. Because of the way the types are described, the full set of keys is computed from the injectable dependencies (<code>TDeps</code>), and the keys of the <code>SystemDescription</code>. </p> <p> The real mechanism that makes this all work is promises. <code>Injectables</code> are typically async functions, and they await calls to the injector they are provided. Once all those components become available, the Injectable function is able to construct the component that was waiting for those dependencies and return it in a promise. The downside to this is that if you have a cycle in your system map where say A depends on B, B depends on C and C depends on A, the system will never start up, and you wont get any warnings. So don’t do that I guess. </p> <p> <code>startSystem</code> itself is pretty straight forward once you understand the basic notion of how <code>Injectable</code> and <code>Injector</code> work. <code>pending</code> is just a cache of all the promises created so far. The function <code>getPending</code> is action our concrete<code>Injector</code>. In order to kick everything off, <code>getPending</code> is simply called to request the primary component, and return it. </p> <p> As an example, imagine a program that has <code>ILogger</code>, <code>IConfig</code>, and <code>IWebApp</code> interfaces, and you wanted to stitch these together. Heres a hypthothetical example: </p> <pre><code class="brush: javascript;">function consoleLogging(): Injectable&lt;ILogging&gt { return async () =&gt new ConsoleLogger(); } function staticConfig(configPath: string): Injectable&lt;IConfig&gt { return async () =&gt new JsonFileConfig(configPath); } function webApp(): Injectable&lt;IWebServer, {config: IConfig, logging: ILogging}&gt { return async (injector) =&gt { const config = await injector("config"); const logging = await injector("logging"); return new WebApp(config, logging); }; } const systemDescription = { "config": staticConfig("defaults.json"), "logging": consoleLogging(), "web": webApp() }; async function main() { const server = await startSystem(systemDescription, "web"); server.listen(); }</code></pre> <p> This is obviously a very minimal example. In a real program, the Injectables may make decisions based on configuration or parameters. You may have define your system description as a type alias, and then populate the object programmatically. And I find it is pretty common to just have different system descriptions for different usecaes (running a tool as a web server, vs as a command line app, vs in testcases). </p> Classes for structure, plain objects for data https://brehaut.net/blog/2018/classes_for_structure_plain_objects_for_data 2018-04-19T08:58:21.352Z <p> I write a lot of Typescript at the moment, both professionally and in hobby projects. One idiom – picked up from Clojure – that I lean on quite a lot now is to use classes for structural portions of the codebase, and plain old JavaScript objects for the data that travels through it. It turns out TypeScript is a surprisingly good match for this approach. </p> <p> The structural parts are often a pretty close match with the stateful parts, but are also sometimes just components of the program that I want to be able to swap out implementations of (loggers, data respositories, web servers, etc). I use classes as its the easiest way to program to an interface with some encapsulation. I also find the priviledged position of the constructor useful: TypeScript’s readonly field support is quite good. Nearly every component of this is going to be exposed via a very simple dependancy injection library I wrote. I’ll cover that in another post later. </p> <p> The real meat of the program – working with data that flows through the system – I leave as simple as possible. TypeScript supports this with a combination of its structural typing and comprehensive support for defining types in terms of other types. At the simplest level this is just unions and intersections, but with <a href="https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#mapped-types">mapped types</a> and now the new <a href="https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#conditional-types">conditional types</a>, quite sophisticated compositions and transformations can be described. </p> <p> For example, I often use an interface to describe a record from a database table. It’s rare that I use that record as is. Instead individual queries will then use a type defined as the <a href="https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#partial-readonly-record-and-pick"><code>Pick</code></a> mapped type to select a subset of the fields, and then intersect that with another <code>Pick</code> type to represent the join and projection. </p> <p> This model of using plain data can simplify working with applications that need to frequently ship data between servers, the client, or web workers. There’s no need to marshall and unmarshall data at every boundary – a real win if you are trying to leverage web workers for performance in a client. For services that act as interstitial processors, they can consume wider records than they are aware of, but still deal with what they care about in a typesafe way<sup>1</sup>. </p> <ol class="footnotes"> <li> Caveat here that you have to validate the data conforms to your types in some way yourself. User defined type guards are useful here. </li> </ol>