Josh On DesignArt, Design, and Usability for Software EngineersMon Oct 20 2014 17:25:05 GMT+0000 (UTC)\nElectron 0.4 beta 3I am unhappy to announce the release of Electron 0.4 beta 3. <p> What's that? <b>unhappy</b>?! Well...... </p> <p> I haven't done a release quite some time. Part of this delay is from a complete refactoring of the user interface; but another big chunk of time comes from trying to build Electron with Atom Shell. </p> <p> <a href='https://github.com/atom/atom-shell'>AtomShell</a> is a tool that bundles WebKit/Chromium and NodeJS into a single app bundle. This means developers can download a single app with an icon instead of running Electron from the command line. It might even let us put it into the various app stores some day. </p> <p> Unfortunately, the switch to AtomShell hasn't been as smooth as I would like. The Mac version builds okay but I have yet to get Windows to work. There seems to be some conflict between the version of Node that the native serial port module uses and the version of Node inside of AtomShell. While I'm sure these are solvable problems I don't want to hold back the rest of Electron. It's still useful even if you have to launch it from the command line. So... </p> <p> </p> <h3 id="id38659">Electron 0.4 beta 3</h3> <p> You can download a Mac .app bundle <a href='http://joshondesign.com/p/apps/electron/builds/0.4_b3/'>from here</a>, or <a href='https://github.com/joshmarinacci/ElectronIDE'>check out the source</a> and run <code>node electron</code> to start it from the command line. The new file browser works as do the various dialogs. Compiler output shows up in the debug panel. You can upload through the serial port but the serial port console is still disabled (due to other bugs I'm still working through). </p> <p> Undoubtedly many things are still broken during the transition from the old UI to the new. Please, please, please <a href='https://github.com/joshmarinacci/ElectronIDE/issues'>file issues on github</a>. I'll get to them ASAP. </p> <p> Thanks, Josh </p> http://joshondesign.com/2014/10/20/electron04b3\nPhoton, a commandline shell in less than 300 lines of JavaScriptI have a problem. Sometimes I get something into my head and it sticks there, taunting me, until I do something about it. Much like the stupid song stuck in your brain, you must play the song to be released from it's grasp. So it is with software. <p> Last week I had to spend a lot of time in Windows working on a port of Electron. This means lots of Node scripts and Git on the command line. </p> <p> </p> <h3 id="id48099">Windows Pains</h3> <p> </p> <p> It may sound like it sometimes, but I really don't hate Windows. It's a fine GUI operating system but the command shell sucks. Really, really bad. Powershell is an improvement but still pretty bad. There has to be something better. I don't want to hate myself and throw my laptop across the room while coding. It dampens productivity. <a href='http://joshondesign.com/2014/09/30/msfixwindows'>This blog</a> was the result of that rage face. I tiny birdy told me things will get a lot better in Windows 10. I sure hope so. </p> <p> In the past I would have used Cygwin, which is a port of Bash and a bunch of unix utilities. Sadly it never worked very well (getting POSIX compliant apps to run on Windows is just a big ball of pain) and support has dwindled in recent years. </p> <p> Then something happened. After pondering for a while I realized I didn't actually care about having standard Unix utilities. Really I just want the Bash <i>interface</i>. I want a command line interpreter that has a proper history, tab completion, and directory navigation. I want <code>ls</code> and <code>more</code> and <code>cd</code>. I don't actually care if they are spec compliant and can be used in Bash shell scripts. I don't really care about shell scripts at all, since I write everything in Node now. I just want the interface. </p> <p> I could make a new shell, something simple that would get the job done. Node is already ported to Windows, it's built around streams, and NPM gives me access to endless existing modules. That's 90% of the work already done. I just need to stitch it together. </p> <p> </p> <h3 id="id2253">Photon</h3> <p> And so Photon was born. </p> <p> Photon is about 250 lines of Javascript that give a command line with <code>ls</code>, <code>cp</code>, <code>mv</code>, <code>rm</code>, <code>rmdir</code>, <code>mkdir</code>, <code>more</code>, <code>pwd</code>, and the ability to call other programs like <code>git</code>. It has a very simple form of tab completion (rather buggy), and uses ANSI colors and tables for formatting. (For some reason there are approximately 4.8 billion ANSI color modules for Node). </p> <p> All you need to do is <code>npm install -g photonsh</code> then <code>photonsh</code> to get this: </p> <p> <img src='http://joshondesign.com/images/65850_iTermScreenSnapz011.png' alt='Photon Shell screenshot'/> </p> <p> </p> <p> Most features were trivial to implement. Here is the function for <code>cp</code>. </p> <pre><code> cp: function(a,b) { if(!fs.existsSync(a)) return fileError("No such file: ",a); if(!fs.statSync(a).isFile()) return fileError("Not a file: ",a); var ip = fs.createReadStream(path.join(cwd,a)); var op = fs.createWriteStream(path.join(cwd,b)); ip.pipe(op); },</code></pre> <p> Pretty much exactly what you would expect. For the buffered editor with history I used Node's built in <code>readline</code> module which includes callbacks for tab completion. </p> <p> </p> <p> </p> <h3 id="id39930">The hard part</h3> <p> The grand irony here is that I wrote it because of my Windows pain but have yet to actually run it on Windows. I stopped that Windows porting effort for other reasons; so now I just have this program I randomly wrote. Rather than waste the man-months of effort (okay, it was really only about 3 hours), I figured something like this should be shared with the world so that others might learn from my mistakes. </p> <p> Speaking of mistakes, Photon is horribly buggy and you probably shouldn't run it. No really, it could totally delete your hard drive and stuff. More importantly, Node TTY support is iffy. It turns out Unix shells are very hard to write because of lots of semi-documented assumptions. Go try to write Xterm sometime. There's a reason few people have done it. </p> <p> In theory a unix shell is simple. You exec a program and pipe it's output to stdout until it's done. The same with input. But what about buffering? But what about ANSI codes? But what about raw keyboard input? Apparently there is a whole world of adhoc specs for how command line apps do 'interactive' things. Running grep from exec is easy. Running vim is not. </p> <p> In the end I found pausing Node's own REPL interface then execing with the 'inherit' flag worked most of the time. I'm sure there's a better way to do it, but casual Googling with Bing hasn't found it yet. </p> <p> </p> <h3 id="id80973">Onward!</h3> <p> So where does Photon go from here? I have no idea. There's tons of things you could do with it. Node can stream anything, so copying a remote URL to a local file should be trivial. Or you could build a text mode raytracer. Whatever. The choice is yours. Choose wisely. Or don't. <a href='https://github.com/joshmarinacci/photonsh'>The code will still be here</a> (on github). </p> <p> Enjoy! </p> http://joshondesign.com/2014/10/15/photonsh\nTypographic Programming Wrapup<i>I need to move on to other projects so I’m wrapping up the rest of my ideas in this blog. Gotta get it outta my brainz first.</i> <p> The key concept I’ve explored in <a href='http://joshondesign.com/tags/programming'>this series</a> is that the code you see in an editor need not be identical to what is stored on disk, or the same as what is sent to the compiler. If we relax this constraint then a world of opportunity opens up. We’ve been writing glorified text files for 40 years. We can do better. Let’s explore. </p> <p> </p> <h3 id="id16351">Keywords</h3> <p> Why can’t you name a variable <code>for</code>? Because in many common languages <code>for</code> is a reserved word. You, as the programmer, aren’t allowed to use <code>for</code> because it represent a particular loop construct. The underlying compiler doesn’t actually care of course. It doesn’t care about the name of <i>any</i> of your variables or other words in your code. The compiler just needs them to be unique symbols, some of which are mapped to existing constructs like conditionals and loops. </p> <p> If the compiler doesn’t care then why can’t we do it? Because the <i>parser</i> (the ‘front end’ of the compiler) does care. The parser needs to <i>unambiguously</i> transform a stream of ASCII text into an abstract syntax tree. It’s the unambiguous part that’s the trouble. The syntax restrictions in most common languages are there to make the parser happy. If the parser was magical and could just "know what we meant" then any syntax could be used. Perhaps even syntax that made more sense to the human rather than the computer. </p> <p> Fundamentally, this is what typographic programming does. It lets us tell the parser which text is what without using specific syntax rules. Instead we use color or font choices to indicate whether a given chunk of text is a variable or keyword or something else. Of course editing in such a system would be a pain, but we already know how to solve that problem. Graphical word processors are proof that it is possible. Before we get to <i>how</i> we solve it let us consider <i>why</i>. Would such a system have enough benefits to outweigh the cost of building it. What <i>new</i> things could we do? </p> <p> </p> <h3 id="id58800">Nothing’s reserved</h3> <p> If we use typography to indicate syntax, then keywords no longer need to be reserved. Any keyword could be used as a variable and any text string could be used as a keyword. You could swap <code>for</code> with <code>fore</code> or <code>thusly</code>. You could use spaces in keywords as <code>for each of</code>. These aren’t very useful examples but the compiler could easily handle them. </p> <p> With the syntactic restrictions lifted we are free to explore new control flow constructs. How about <code>forever</code> to mean an infinite loop and <code>10 times</code> for standard for fixed length loops? It’s all the same to the compiler but the human reading it would better understand the meaning. </p> <p> </p> <h3 id="id39542">Custom Operators</h3> <p> If nothing is reserved then user defined operators become easy. After all; what is an operator but a function with a single letter name from a restricted character set. In Python <code>4 + 5</code> is just sugar for <code>add(4,5)</code>. </p> <p> With no syntax rules anything could be an operator. Operators could have multiple letter names, or other symbols from the full unicode set. The only reason operators are given special treatment to begin with is because they represent functions which are so commonly used (like arithmetic) that we want a shorthand. With free syntax we can create a shorthand for the functions that are useful <i>to the task at hand</i> rather than the abstract general purpose tasks the language inventors imagined. </p> <p> </p> <p> Let’s look at something more concrete. Using complex numbers and vectors is common in graphics programming, but we have to use clumsy and verbose syntax in most languages. This is sad. Mathematics already has invented compact notation for these concepts but we can’t use them due to ASCII limitations. Without these limitations we could add complex numbers with the plus sign like this: </p> <pre><code>A +B</code></pre> <p> instead of </p> <pre><code>complexAdd(A,B)</code></pre> <p> </p> <p> To help the programmer remember these are complex numbers they could be rendered in a different color. </p> <p> There are two ways to multiply vectors: the dot product and the cross product. They have very different meanings. With full unicode we could use the correct symbols like this: </p> <pre><code>A &#8901; B // dot product</code></pre><pre><code>A &#x2a2f; B // cross product</code></pre> <p> No ambiguity at all. It would be too much to expect a language to support every possible notation. Much better instead to have a language that lets the programmer create their own notation. </p> <p> </p> <p> </p> <h3 id="id72793">Customization in Practice</h3> <p> </p> <p> So how would this work in practice? At some point the code must be transformed into something the compiler understands. Let’s postulate a hypothetical language called <i>X</i>. X has no syntax rules, only the semantic rules of it’s AST. To tell the complier how to convert the code into the AST we must provide our own rules. Something like this. </p> <pre><code>fun => function cross => cross dot => dot |x| => magnitude(x) fun intersection(V,R) { return V dot R / |V|; }</code></pre> <p> </p> <p> We have now defined a mini language in X which still compiles to the same syntactic structure. </p> <p> Of course typing all of these rules in every file (or compilation unit) would be a huge pain, so we could include them much as we include external libraries. </p> <pre><code>@include math.rules fun intersection(V,R) { return V dot R / |V|; }</code></pre> <p> Most importantly, not only would the compiler understand these rules but <i>so would the editor</i>. The editor can now indicate that <code>V &#8901; R</code> is valid only if they are both vectors. It could enforce the rules from the rule file. Now our code is limited only by the imagination of our rule writers, not the fixed compiler. </p> <p> In practice, were X to become popular, we would not see everyone making up their own rules. Instead usage would gather around a few popular rulesets much as JavaScript gathered around a few popular libraries like JQuery. We might call each of these rulesets <i>dialects</i>, each a particular flavor derived from the base X language. Custom DSLs would become trivial to implement. It would be common for developers to use one or two "standard" dialects for most of their code but use a special purpose dialect for a particular task. </p> <p> The important thing here is that the language no longer has a <i>fixed</i> syntax. It can adapt and evolve as needed. All without changing the compiler. </p> <p> </p> <p> </p> <h3 id="id41421">How do you edit?</h3> <p> I hope I’ve convinced you that a flexible syntax delimited by typography is useful. Many common idioms like iteration, accumulation, and data structure traversals could be distilled to concise syntax. And if it has problems then we can tweak it. </p> <p> There is one big problem though. How would you actually <i>edit</i> code like this? </p> <p> Fortunately this problem has already been solved by graphical word processors. These tools use color, font, size, weight and spacing to distinguish one element from another. Choosing the mode for a variable is as simple as selecting it with the cursor and using a drop down. </p> <p> Manually highlighting a entire page of code would quickly grow tedious, of course. For common operations, like declaring a variable, the programmer could type a special symbol like <code>@</code>. This tells the editor that the next letters are a variable name. The programmer ends it with @ or by pressing the spacebar or return key. This @ symbol doesn’t exist in the code. It is simply to indicate to the editor that the programmer wants to be in ‘variable’ mode. Once the mode is finished the @’s go away and the text is rendered with the ‘variable’ font. This is no different than using star word star to indicate bold in Markdown text. The stars never appear in the rendered text. </p> <p> The choice of the <code>@</code> symbol doesn't matter as long as it's easy with the user's native keyboard. @ is good for US keyboards. French or Russians might use something else. </p> <p> </p> <h3 id="id20820">Resolving Ambiguity</h3> <p> Even using manual markup might become tedious, though. Fortunately the editor can usually figure out the meaning of any given token by using the dialect rules. If the rules indicate that # equals division then the editor can just do the right thing. Using manual highlighting would only be necessary if the <i>dialect itself</i> introduces an ambiguity. (ex: # means division and also the start of a hex value) </p> <p> What about multiplying vectors? You could type in either of the two proper symbols, but the average keyboard doesn’t support those directly. You’d have to memorize a unicode code point or use a floating dialog. Alternatively, we could use code completion. If you type &#42; then the editor knows this must be either dot or cross product. It provides only those two choices in a drop down, much as we auto-complete method names today. </p> <p> Using a syntax free language does not fully remove the need to resolve ambiguity, it just moves the resolution process to edit time rather than compile time. This is good. The human is present at edit time and can explain to the computer was is correct. The human is not there at compile time, so any ambiguity must result in an error that the human must come back and fix. Furthermore, resolving the ambiguity need only happen once, when the human types it, not every time the code is compiled. This will further reduce code regressions when other parts of the system change. </p> <p> Undoubtedly we would discover more edge cases, but these are all solvable. Modern GUI word processors and spreadsheets prove this. A more challenging issue is version control. </p> <p> </p> <h3 id="id38816">Versioning</h3> <p> Code changes over time. It must be versioned. I don’t know why it took 40 years for us to invent distributed version control systems like Git, but at least we have it now. It would be a shame to give that up just as we’ve gotten the world on board. The problem is Git and other VCSs don’t really understand code. They just understand text. There are really only two ways to solve this: </p> <p> 1) modify git, and the other tools around it (diff viewers, github’s website, etc.) to support binary diffs specific to our new system. </p> <p> 2) make the on disk format be pure text. </p> <p> Clearly option 1 is a non-starter. One day, once language X takes over the world, we could ask the GitHub team to add support for X diffs, but that’s a long ways off. We have to start with option 2. </p> <p> You might think I’m going back on what I said at the start. After all, I stated we should no longer be writing code as text on disk, but that is exactly what I am suggesting. What I don’t want is to store <i>the same thing</i> that we edit. From the VCS’s point of view the editor and visual representation are irrelevant. The only thing that matters is what is the file on disk. X needs a canonical on serialization format. Regardless of what tool you use to edit X, as long as it saves to the same format we are fine. This is no different than SQL or HTML. Everyone has their favorite tool, but they all write to the same format. </p> <p> </p> <h3 id="id4130">Canonical Serialization Format.</h3> <p> X’s serialization format should obviously be plain text. < 128bit ASCII would be fine, though I think we could handle UTF8 easily. Most modern diff tools can work with UTF8 cleanly, so Japanese comments and math symbols would come through just fine. </p> <p> The X format should also be unambiguous. Variables are marked up explicitly as variables. Operators as operators. There should be no need for the parser to guess at anything or interpret syntax rules. We could use one of the many existing formats like JSON, XML, or even LaTex. It doesn’t really matter since humans will rarely need to look at them. </p> <p> But.... since we are defining a new serialization format anyways, there are a few useful things we could add. </p> <p> </p> <h3 id="id11764">Code as Graph</h3> <p> Code is really just a graph. Graphs can be serialized in many ways. Rather than using function names inline they could be represented by identifiers which point to a lookup table. Then, if a function is renamed the code only changes in one place rather than at every point in the code where the function is used. This creates a semantic diff that the diff tool could render as ‘function Y renamed to Z’. </p> <pre><code>v467 = foo v468 = bar v469 = baz fun v467 () { return v468 + v469; }</code></pre> <p> Semantic diff-ing could be very powerful. Any refactoring should be reducible to its essential meaning: <i>moved X to a new class</i> or <i>extracted Y from Z</i>. Whitespace changes would be ignored (or never stored in the first place). Commit messages could be context aware: <i>changed X in the unit test for Y</i> and <i>added logging to Z</i>. Our current tools just barely understand when a file has been renamed instead of deleted and a new one added. There’s a lot of room for innovation here. </p> <p> </p> <h3 id="id32518">WrapUp</h3> <p> I hope I’ve convinced you there is value in this approach. Building language X still won’t be easy. To be viable we have to make a compiler, useful dialect definitions, and a visual editor; all at the same time. That’s a lot of work before anyone else can use it. Building on top of existing tools like Eclipse or Atom.io would help, but I know it’s still a big hill to climb. Trust me. The view will be worth it. </p> http://joshondesign.com/2014/10/06/typoplwrapup\nHow Microsoft can fix Windows. They have the Technology.<i>Note: I’m a research at Nokia but this blog does not represent my employer. I didn’t move to Microsoft and I’ve never been on the Windows Phone team. These ill considered opinions are my own.</i> <p> Windows 10 seems nice and all, but it doesn’t do anything to make me care. Fortunately Microsoft can fix all of Windows problems if only they follow my simple multistep plan. You’re welcome. </p> <p> </p> <h3 id="id50492">First, Fix the damn track pads.</h3> <p> The problem: my employer gave me a very nice, probably expensive, laptop. It’s name rhymes with a zinc fad. It’s specs sure are nice. It’s very fast. but the track pad is horrible. Every Windows laptop I’ve tried (which is a lot because Jesse likes to ‘do computers’ at Costco) has a horrible trackpad. why is this so hard? I simply can’t bear to use this laptop without a mouse. the cursor skips around, gestures don’t work all the time, and it clicks when i don’t and it doesn’t click when I do. </p> <p> The fix: <i>Take over trackpad drivers</i> and make a new quality test for Win10 certification. It used to be that every mouse and keyboard needed it’s own driver, and they were usually buggy. I bought Logitech trackballs in the 90s because they seemed to be the only guys who cared to <i>actually test</i> their drivers (and the addon software was mildly useful). Sometime in the early USB days (Win98ish?) MS made a default mouse and keyboard driver that all devices had to work with. Since then it’s never been an issue. Plug in any mouse and it works perfectly. 100% of the time. MS needs to do the same for trackpads. </p> <p> Please write your own driver for the N most popular chipsets, standardize the gesture support throughout the OS, then mandate a certain quality level for any laptop that wants to ship windows 10. Hey OEM: If it’s not a Macbook Air quality trackpad experience then no Windows 10 for you. </p> <p> </p> <h3 id="id70689">Make A Proper Command Line Shell</h3> <p> Hide PowerShell, Cygwin, whatever Visual Studio ships with (it has a shell, right?) and the ancient DOS prompt. Make a proper terminal emulator with Bash. (Fix the bugs first). Build it in to the OS, or at least as a free developer download (one of those MS Plus thingies you promised us). </p> <p> This shell should be fully POSIX compliant and run all standard Unix utilities. I understand you might worry that full POSIX would let developers port code from another platform instead of writing natively for you. That is very astute thinking… for 1999. Unfortunately we live in the futuristic hellscape that is 2014. You need to make it as easy as possible for someone to port code to Windows. Eliminate all barriers. Any standard Unix command line program should compile out of the box with no code changes. Speaking of which.. </p> <p> </p> <h3 id="id73754">Give your C++ compiler a GCC mode. </h3> <p> For some reason all ANSI C code compiles perfectly on Mac and Linux but requires special #IFDEFs for Windows.h. Slightly different C libs? Sightly different calling syntax? None of this <i></i>cdecl vs <i></i>stdcall nonsense. Make a <code>--gcc</code> flag so that bog standard Linux code compiles with zero changes. Then submit patches to GNU Autoconf and the other make file builders so that this stuff just works. Just fix it. </p> <p> </p> <p> </p> <h3 id="id9036">Build a Package Manager</h3> <p> Now that we have a proper command line Windows needs a package manager. I use Brew on Mac and it works great. I can install any package, share formulas for new packages, and keep everything up to date. I can grab older versions of packages if I want. I can switch between them. Everything all works. Windows <b>needs</b> this, and it should work from both a GUI and CLI. </p> <p> I know Windows has NuGet and Chocolatey and supposedly something is coming called OneGet. There needs to be one official system that really works. It handles all dependencies. And it should be easy to use with no surprises. </p> <p> <i>"What surprises?"</i> I hear you say? I wanted to install Node. I couldn’t figure out which package manager to use so I chose Chocolatey since it seemed to be all the new hotness. I go to their website and find four different packages: Node JS (Install), Node JS, Node JS (Command Line), Node Package Manger. What? Which do I choose? They all have a lot of downloads. On every other platform you just install Node. NPM is built in. There are no separate packages. It’s all one thing because you can’t use part of it without the rest. </p> <p> NodeJS is an alias for NodeJS.commandline. NodeJS.commandline installs to the Chocolatey lib dir. NodeJS.install installs to a system dir. It turns out Chocolatey has both installable and portable packages. As near as I can tell they are identical except for the install path, which is something I shouldn’t have to care about anyway. Oh, and one way will add it to your path and the other won’t. What? Why should I have to care about the difference? Fix it! </p> <p> I really hope OneGet straightens all of this nonsense. There should be just one way to do things and it must work 100% of the time. I know Microsoft has MSDN subscriptions to sell, but that’s just another repo source added to the universal package manager. </p> <p> </p> <h3 id="id98230">Make Visual Studio be everywhere.</h3> <p> Visual Studio is really an impressive piece of software. It’s really good at what it does. The tooling is amazing. Microsoft needs to let the world know by making it <b>be everywhere</b>. </p> <p> If you are on Windows, you should get a free copy of VS to download. In theory this is the idea behind Visual Studio Express. So why do I still use Atom or Sublime or even JEdit on Windows? Partly because of the aforementioned package manager problem, but also because Visual Studio isn’t good for all kinds of coding. </p> <p> Visual Studio is primarily a C/C++ editor, meant for MS’s own projects (and now hacked up for WinPhone and presumably WinRT). They should make it good for everything. </p> <p> Are you a Java programmer? VS should be your first choice. It should have great Java language support and even version the JDKs with the aforementioned package manager. </p> <p> Are you a web developer? VS should have awesome HTML and JavaScript support, with the ability to edit remote files via sftp. (Which Atom still doesn't have, either, BTW). </p> <p> And all of this should be through open hackable plugins, also managed through the package manager. VisualStudio should be so good and so fast that it’s the only IDE you need on Windows, no matter what you are coding. </p> <p> Why should Microsoft do this? After all, they would be putting a lot of effort into supporting developers who don’t code for their platform. Because Microsoft needs developer mindshare. </p> <p> I know very few topflight developers who use Windows as their main OS. Most use Macbook Pros or Linux laptops. MS needs to make a development experience <b>so good</b> that programmers will <b>want</b> to use Windows, even if it’s just for web work. </p> <p> Once I use Windows every day I might take a look at MS’s other stacks. If I’m already using Visual Studio for my JavaScript work then I’d be willing to take a look at developing for Windows Phone; especially if it was a single download within a program I already have installed. Fix it! </p> <p> </p> <h3 id="id305">Buy VMWare.</h3> <p> You want me to test new versions of Windows? It should be a single click to download. You want me to use your cloud infrastructure? If I could use Visual Studio to create and manage VM instances, then it’s just a single button to deploy an app from my laptop to the cloud. MS’s cloud, where they real money from the movie is made. Buy VM ware to make it happen if you need to. I don’t care. Just fix it! </p> <p> </p> <p> </p> <h3 id="id75986">Be open and tell the world.</h3> <p> MS has always had a problem with openness. They have great technology but have always felt insular. They build great things for Windows Devs and don’t care about the rest of the world. Contribute to the larger community. Make Visual Studio for all sorts of development, even those that don’t add to the bottom line. </p> <p> Maybe Visual Studio Express already has all sorts of cool plugins that make web coding awesome. I will never know because MS doesn’t market to me. All I hear is “please pretty please make some crappy Windows Phone apps”. </p> <p> Maybe OneGet fixes all of the package management problems, but I didn’t even know about it until I was forced to use a Windows laptop and did my own research. </p> <p> </p> <h3 id="id49374">Fix It !</h3> <p> Here is the real problem. MS has become closed off. An ecosystem unto itself. This is a great strategy if you are Apple, but you aren’t. Your a software company become a cloud company. You must become more open if you expect your developer mindshare to grow. And from that mindshare new platforms will grow. When MS releases their Windows smart watch, or the Windows Toaster, they will find it a lot easier to get developers on board if they’ve built an open community up first. Efforts like CodePlex are nice, but this philosophy has to come from the top. </p> <p> Good Luck Nadella. </p> http://joshondesign.com/2014/09/30/msfixwindows\n60sec Review: Rust LanguageLately I've been digging into Rust, a new programming language sponsored by Mozilla. They recently rewrote their docs and <a href='http://blog.rust-lang.org/2014/09/15/Rust-1.0.html'>announced a roadmap to 1.0</a> by the end of the year, so now is a good time to take a look at it. I went through the <a href='http://doc.rust-lang.org/guide.html'>new Language Guide</a> last night then wrote <a href='https://twitter.com/joshmarinacci/status/512344513725992960/photo/1'>a small ray tracer</a> to test it out. <p> One of the biggest success stories of the last three decades of programming is memory safety. C and C++ may be fast but it's very easy to have dangling pointers and buffer overflows. Endless security exploits come back to this fundamental limitation of C and C++. Raw pointers == lack of memory safety. </p> <p> Many modern languages provide this memory safety, but they do it at runtime with references and garbage collection. JavaScript, Java, Ruby, Python, and Perl all fall into this camp. They accomplish this safety at the cost of runtime speed. While they are typically JITed today instead interpreted, they are all slower than C/C++ because of their runtime overhead. For many tasks this is fine, but if you are building something low level or where speed really matters, then you probably go back to C/C++ and all of the problems it entails. </p> <p> Rust is different. Rust is a statically typed <i>compiled</i> language meant to target the same tasks that you might use C or C++ for today, but it's whole purpose in life is to promote memory safety. By design, Rust code can't have dangling pointers, buffer overflows, or a whole host of other memory errors. Any code which would cause this <b>literally can't be compiled</b>. The language doesn't allow it. I know it sounds crazy, but it really does work. </p> <p> Most importantly, Rust achieves all of these memory safety guarantees at compile time. There is no runtime overhead, making the final code as fast as C/C++, but far safer. </p> <p> I won't go into how all of this work, but the short description is that Rust uses several kinds of pointers that <i>let the compiler prove</i> who owns memory at any given moment. If you write up a situation where the complier can't predict what will happen, it won't compile. If you can get your code to compile then you are <i>guaranteed to be memory safe</i>. </p> <p> I plan to do all of my native coding in Rust when it hits 1.0. Rust has a robust FFI so interfacing with existing C libs is quite easy. Since I absolutely hate C++, this is a big win for me. :) </p> <p> Coming into Rust I was worried the pointer constraints would make writing code difficult, much like <a href='http://prog21.dadgum.com/38.html'>puzzle languages</a>. I was pleasantly surprised to find it pretty easy to code in. It's certainly more verbose than a dynamic language like JavaScript, but I was able to convert a JS ray tracer to Rust in about an hour. The resulting code roughly looks like what you'd expect from C, just with a few differences. Let's take a look. </p> <p> First, the basic type definitions. I created a Vector, Sphere, Color, Ray, and Light class. Rust doesn't really have classes in the C++/Java sense, but it does have structs enhanced with method implementations, so you can think of them similar to classes. </p> <pre><code>use std::num; struct Vector { x:f32, y:f32, z:f32 } impl Vector { fn new(x:f32,y:f32,z:f32) -> Vector { Vector { x:x, y:y, z:z } } fn scale(&self, s:f32) -> Vector { Vector { x:self.x*s, y:self.y*s, z:self.z*s } } fn plus(&self, b:Vector) -> Vector { Vector::new(self.x+b.x, self.y+b.y, self.z+b.z) } fn minus(&self, b:Vector) -> Vector { Vector::new(self.x-b.x, self.y-b.y, self.z-b.z) } fn dot(&self, b:Vector) -> f32 { self.x*b.x + self.y*b.y + self.z*b.z } fn magnitude(&self) -> f32 { (self.dot(*self)).sqrt() } fn normalize(&self) -> Vector { self.scale(1.0/self.magnitude()) } } struct Ray { orig:Vector, dir:Vector, } struct Color { r:f32, g:f32, b:f32, } impl Color { fn scale (&self, s:f32) -> Color { Color { r: self.r*s, g:self.g*s, b:self.b*s } } fn plus (&self, b:Color) -> Color { Color { r: self.r + b.r, g: self.g + b.g, b: self.b + b.b } } } struct Sphere { center:Vector, radius:f32, color: Color, } impl Sphere { fn get_normal(&self, pt:Vector) -> Vector { return pt.minus(self.center).normalize(); } } struct Light { position: Vector, color: Color, }</code></pre> <p> Without knowing the language you can still figure out what's going on. Types are specified after the field names, with f32 and i32 meaning integer and floating point values. There's also a slew of finer grained number types for when you need tight memory control. </p> <p> Next up I created a few constants. </p> <pre><code>static WHITE:Color = Color { r:1.0, g:1.0, b:1.0}; static RED:Color = Color { r:1.0, g:0.0, b:0.0}; static GREEN:Color = Color { r:0.0, g:1.0, b:0.0}; static BLUE:Color = Color { r:0.0, g:0.0, b:1.0}; static LIGHT1:Light = Light { position: Vector { x: 0.7, y: -1.0, z: 1.7} , color: WHITE };</code></pre> <p> Now in my <code>main</code> function I'll set up the scene and create a lookup table of one letter strings for text mode rendering. </p> <pre><code>fn main() { println!("Hello, worlds!"); let lut = vec!(".","-","+","*","X","M"); let w = 20*4i; let h = 10*4i; let scene = vec!( Sphere{ center: Vector::new(-1.0, 0.0, 3.0), radius: 0.3, color: RED }, Sphere{ center: Vector::new( 0.0, 0.0, 3.0), radius: 0.8, color: GREEN }, Sphere{ center: Vector::new( 1.0, 0.0, 3.0), radius: 0.3, color: BLUE } );</code></pre> <p> Now lets get to the core ray tracing loop. This looks at every pixel to see if it's ray intersects with the spheres in the scene. It should be mostly understandable, but you'll start to see the differences with C. </p> <pre><code> for j in range(0,h) { println!("--"); for i in range(0,w) { //let tMax = 10000f32; let fw:f32 = w as f32; let fi:f32 = i as f32; let fj:f32 = j as f32; let fh:f32 = h as f32; let ray = Ray { orig: Vector::new(0.0,0.0,0.0), dir: Vector::new((fi-fw/2.0)/fw, (fj-fh/2.0)/fh,1.0).normalize(), }; let mut objHitObj:Option&lt;(Sphere,f32)> = None; for obj in scene.iter() { let ret = intersect_sphere(ray, obj.center, obj.radius); if ret.hit { objHitObj = Some((*obj,ret.tval)); } }</code></pre> <p> The <code>for</code> loops are done with a <code>range</code> function which returns an iterator. Iterators are used extensively in Rust because they are inherently safer than direct indexing. </p> <p> Notice the <code>objHitObj</code> variable. It is set based on the result of the intersection test. In JavaScript I used several variables to track if an object had been hit, and to hold the hit object and hit distance if it did intersect. In Rust you are encouraged to use options. An Option is a special enum with two possible values: None and Some. If it is None then there is nothing inside the option. If it is Some then you can safely grab the contained object. Options are a safer alternative to null pointer checks. </p> <p> Options can hold any object thanks to Rust's generics. In the code above I tried out something tricky and surprisingly it worked. Since I need to store several values I created an option holding a tuple, which is like a fixed size array with fixed types. <code>objHitObj</code> is defined as an option holding a tuple of a <code>Sphere</code> and an <code>f32</code> value. When I check if <code>ret.hit</code> is true I set the option to <code>Some((<b>obj,ret.tval))</code>, meaning the contents of my object pointer and the hit distance. </p> </b> <p> Now lets look at the second part of the loop, once ray intersection is done. </p> <pre><code> let pixel = match objHitObj { Some((obj,tval)) => lut[shade_pixel(ray,obj,tval)], None => " " }; print!("{}",pixel); } }</code></pre> <p> Finally I can check and retrieve the option values using an <code>if</code> statement or a <code>match</code>. Match is like a <code>switch</code>/<code>case</code> statement in C, but with super powers. It forces you to account for all possible code paths. This ensures there are no mistakes during compilation. In the code above I match the some and none cases. In the <code>Some</code> case it pulls out the nested objects and gives them the names obj and tval, just like the tuple I stuffed into it earlier. This is called <i>destructuring</i> in Rust. If there is a value then it calls <code>shadepixel</code> and returns character in the look up table representing that grayscale value. If the <code>None</code> case happens then it returns a space. In either case we know the <code>pixel</code> variable will have a valid value after the match. It's impossible for <code>pixel</code> to be null, so I can safely print it. </p> <p> The rest of my code is basically vector math. It looks almost identical to the same code in JavaScript, just strongly typed. </p> <pre><code>fn shade_pixel(ray:Ray, obj:Sphere, tval:f32) -> uint { let pi = ray.orig.plus(ray.dir.scale(tval)); let color = diffuse_shading(pi, obj, LIGHT1); let col = (color.r + color.g + color.b) / 3.0; (col * 6.0) as uint } struct HitPoint { hit:bool, tval:f32, } fn intersect_sphere(ray:Ray, center:Vector, radius:f32) -> HitPoint { let l = center.minus(ray.orig); let tca = l.dot(ray.dir); if tca &lt; 0.0 { return HitPoint { hit:false, tval:-1.0 }; } let d2 = l.dot(l) - tca*tca; let r2 = radius*radius; if d2 > r2 { return HitPoint { hit: false, tval:-1.0 }; } let thc = (r2-d2).sqrt(); let t0 = tca-thc; //let t1 = tca+thc; if t0 > 10000.0 { return HitPoint { hit: false, tval: -1.0 }; } return HitPoint { hit: true, tval: t0} } fn clamp(x:f32,a:f32,b:f32) -> f32{ if x &lt; a { return a; } if x > b { return b; } return x; } fn diffuse_shading(pi:Vector, obj:Sphere, light:Light) -> Color{ let n = obj.get_normal(pi); let lam1 = light.position.minus(pi).normalize().dot(n); let lam2 = clamp(lam1,0.0,1.0); light.color.scale(lam2*0.5).plus(obj.color.scale(0.3)) }</code></pre> <p> </p> <p> That's it. Here's the final result. </p> <p> <img src='http://joshondesign.com/images/98232_iTermScreenSnapz005.png' alt='text'/> </p> <p> </p> <p> So far I'm really happy with Rust. It has some rough edges they are still working on, but I love the direction they are going. It really could be a replacement for C/C++ in lots of cases. </p> <p> Buy or no buy? <b>Buy!</b> <a href='http://www.rust-lang.org'>It's free!</a> </p> http://joshondesign.com/2014/09/17/rustlang\nImproving Regular Expressions with TypographyAfter the more <a href='http://joshondesign.com/2014/09/10/cyberprog'>abstract talk</a> I’d like to come back to something concrete. <a href='http://en.wikipedia.org/wiki/Regular_expression'>Regular Expressions</a>, or <i>regex</i>, are powerful but often inscrutable. Today let’s see how we could make them easier to use through typography and visualization without diminishing that power. <p> </p> <p> </p> <p> Regular Expressions are essentially a mini language embedded inside of your regular language. I’ve often seen regex written like this, </p> <pre><code>new Regex(“^\\s+([a-Z]|[0-9])\\w+\\$$”) // regex for special vars</code></pre> <p> then sometimes reformatted like this </p> <pre><code>//regex for special vars new Regex( “^” // start of line +“\\s+” // one or more whitespace +“([a-Z]|[0-9])” //one letter or number +”\w+” // one word +”\\$” // the literal dollar sign +”$” // end of line )</code></pre> <p> </p> <p> The fact that the author had to manually split up the text and add comments simply <i>screams</i> for a better syntax. Something far more readable but still terse. It would seem that readability and conciseness would be mutually exclusive. Anything more readable would also be far longer, eliminating much of the value of regex, right? </p> <p> Au contraire! We have a special power at our disposal: we can render whatever we want in the editor. The compiler doesn’t care as long as it receives the description in some canonical form. So rather than choosing readable vs terse we can cheat and do both. </p> <p> </p> <h2 id="id60968">Font Styling</h2> <p> Let’s start with the standard syntax but replacing delimiters and escape sequences with typographic choices. This regex looks for variable names in a made up language. Variables must start with a letter or number, followed by any word character, followed by a dollar sign. Here is the same regex using bold italics for all special chars: </p> <p> <img src='http://joshondesign.com:/images/16121_SafariScreenSnapz040.png' alt='text'/> </p> <p> </p> <p> </p> <p> Those problematic double escaped backslashes are gone. We can tell which dollar sign is a literal and which is a magic variable thanks to font styling. </p> <p> </p> <h2 id="id29377">Color and Brackets</h2> <p> Next we can turn the literals green and the braces gray, so it’s clear which part is actual words. We can also replace the <code>$</code> and <code>^</code> with symbols that actually look like beginning and ending of lines. Open and close up brackets or floor brackets. </p> <p> <img src='http://joshondesign.com/images/12535_SafariScreenSnapz041.png' alt='text'/> </p> <p> </p> <p> Now one more thing, let’s replace the w and s magic characters with something that looks even more different than plain text: letter boxes. These are actual unicode characters from the <a href='http://en.wikipedia.org/wiki/Enclosed_Alphanumeric_Supplement'>"Unicode Characters in the Enclosed Alphanumeric Supplement Block"</a>. </p> <p> </p> <p> <img src='http://joshondesign.com/images/42874_SafariScreenSnapz042.png' alt='text'/> </p> <p> </p> <p> Now the regex is much easier to read but still compact. However, unless you are really familiar with regex syntax you may still be confused. You still have a bunch of specific symbols and notation to remember. How could we solve this? </p> <p> </p> <h2 id="id48829">Think Bigger</h2> <p> Let’s invent a second notation that is even easier to read. We already have a clue of how this should work. Good programmers write the regex vertically with comments as an adhoc secondary notation. Let’s make it official. </p> <p> If we have two views then the editor could switch between them as desired. When the user clicks on the regex is will expand to something like this: </p> <p> </p> <p> <img src='http://joshondesign.com/images/78563_SafariScreenSnapz044.png' alt='text'/> </p> <p> </p> <p> We get what looks like a tiny spreadsheet where we can edit any term directly, using code completion so we don’t have to remember the exact terms. Furthermore the IDE can show the extra documentation hints only when we are in this "detailed" mode. </p> <p> Even with this though, there is still a problem with regex. Just by looking at it you can’t always tell what it will match and what it won’t. Without a long comment, how do programmers today know what a regex will match. They use their brains. Yes, they actually look at the text and imagine what it will match in their heads. They essentially simulate the computer the regex mentally. This is totally backwards! The whole point of a computer is to simulate things for us, not the other way around. Can’t we make the computer do it’s job?! </p> <p> </p> <h2 id="id70728">Simulate</h2> <p> Instead of simulating the regex mentally, let’s give it some strings and have the computer tell us what will match. Let’s see what that would look like: </p> <p> </p> <p> <img src='http://joshondesign.com/images/20697_SafariScreenSnapz045.png' alt='regex tester'/> </p> <p> </p> <p> </p> <p> We can type in as many examples as we want. Having direct examples also lets us test out the edge cases, which is often where regexes fail. </p> <p> Hmm. You know… this is basically some unit tests for the regex. If we just add another column like this: </p> <p> </p> <p> <img src='http://joshondesign.com/images/5053_SafariScreenSnapz046.png' alt='regex unit tests'/> </p> <p> </p> <p> then we can see at a glance if the regex is working as expected. In this example the last test is failing so it is highlighted in red. </p> <p> Most importantly, the unit tests are right next to the regex in the code; <i>right where they are used</i>. If we collapse the triangle then everything goes away. It’s still there, just hidden, until we need it. </p> <p> This is the power of having a smart IDE and flexible syntax. Because these are only visualization changes it would work with any existing compiler. No new language required. </p> http://joshondesign.com/2014/09/15/regextypo5\nPaper and the Cybernetically Enhanced ProgrammerI’ve talked a lot about ways to improve the syntax and process of writing code. In <a href='http://joshondesign.com/2014/08/22/typopl'>Typographic Programming Language</a>, <a href='http://joshondesign.com/2014/08/25/typopl2'>Fonts</a>, and <a href='http://joshondesign.com/2014/09/02/bar'>Tabs Vs Spaces</a> I've talked about the details of how to improve programming. However, I haven't really talked about my larger vision. Where am I actually going with this? <p> My real goal is to build the <b>Ultimate IDE and Programming Language</b> for solving problems cleanly and simply. Ambitious much? </p> <p> Actually, my real goal is to create the <b>computer from Star Trek</b> (the one with Majel Barrett's voice). </p> <p> Actually, my real goal is to create <b>a cybernetically enhanced programmer</b>. </p> <p> Okay. Let’s back up a bit. </p> <p> </p> <h2 id="id75096">The Big Picture</h2> <p> When we are programming, what are we really doing? What is the essence? Once we figure that out we should be able to work backwards from there. </p> <p> Programming is <i>when you have a problem to solve and you tell the computer how to solve it for you</i>. That’s really it. Everything we do comes back to that fundamental. Functions are ways of encapsulating solving stuff in small chunks so we can reason about it. The same thing with objects (often used to "model" what we are solving). Unit tests are to help verify what we are solving, though it often helps to define the problem as well. At the end of the day it's all to serve the goal of teaching the computer how to solve problems for us. </p> <p> So how could we compare one PL against another? </p> <p> </p> <h2 id="id54582">Metrics</h2> <p> From here out I'm going to use Programming Language, PL, to mean the entire system of IDE, compiler, editor, build tools, etc. The entire system that lets you have the computer solve a problem for you. </p> <p> How can we say that one PL is better than another? By what metric? Well, how about <i>what lets you solve the program the fastest, or the easiest, or with the least headache</i>. That sounds nice and is certainly true, but it's rather subjective. We need something more empirical. </p> <p> Hmm. That's not very helpful. Let's back up again. </p> <p> </p> <h2 id="id75064">Paper and Pencil</h2> <p> What is a pad of paper and a pencil? It’s a thinking device. If you want to add up some numbers you can do it in your head, but after more than a few numbers it becomes tricky to manage them all. So we write them down. We outsource part of the process to some paper. </p> <p> If we want to do division we can do it with the long division process. This is actually not the most efficient way to divide numbers, but it works well because you can have the paper manage all of the state for you. </p> <p> What if you need to remember a list of things to do? You write it down on paper. The paper becomes an extension of your brain. It is <i>a tool for thinking</i>. This perhaps explains some people’s fetish over moleskin style sketch books (not that I would <a href='https://www.kickstarter.com/projects/joeycofone/baron-fig-sketchbooks-and-notebooks-for-thinkers'>ever invest in a Kickstarter for sketchbooks</a>. </p> <p> </p> <h2 id="id58396">A Tool for Thinking</h2> <p> If we think of a programming language as a tool for thinking, then it becomes clear. The PL helps you tell the computer what to do. So a good PL would help you around the parts of programming that are hard: namely keeping state in your head. A bad PL requires you to remember a lot of things. </p> <p> For example, suppose you write a function that calls another function named 'foo'. You must remember what this other function does and what it accepts and what it returns. If the function is named well, say 'increment', then the function name itself helps your brain.You have less to remember because the function name carries information. </p> <p> Now suppose we have type information in our PL. The function increment only takes numbers. Now I don’t have to remember that it only takes numbers; the compiler will enforce it for me. Of course I only find this out when I compile the code. To make the PL give me less to remember the IDE can compile constantly, giving me an immediate warning when I do something bad. Code completion can also help by only suggesting local values that are numbers. </p> <p> With these types of features the PL acts as a tool for thinking. An extension of the brain by holding state. </p> <p> </p> <p> So we can say a PL is “better” if it reduces the cognitive load of the programmer. Things like deterministic performance and runtime speed are nice, but they are (or at least should be) secondary to <i>reducing the cognitive load of the programmer</i>. Of course a program which is too slow to be used is a failure, so ultimately it does matter. However computers get faster. The runtime performance is less of a concern than the quality of the code. Perhaps this explains the resurgence in functional programming styles. The runtime hit matters less than it did 30 years ago, so we can afford to waste cycles on things which reduce the cognitive load of the programmer. </p> <p> </p> <p> </p> <h2 id="id15875">Regex</h2> <p> Now, where were we? Oh, right; the Fire Swamp. </p> <p> Let's look at a more concrete example. Regular expressions. Regexes are powerful. They are concise. But a given regex is <b>not</b> easy to read if you didn’t write it yourself; or even if you did but you didn’t <b>just</b> write it. Look at your regex from 6 months ago sometime. I hope you added good documentation. </p> <p> A regex conveys a lot of information. You have a lot to load up into your brain. When you look at a regex to see what it does you have to start <i>simulating</i> it in your brain. Your brain basically becomes a crappy computer that executes the regex on hypothetical strings. </p> <p> That's crazy. Why are we simulating a state machine in our heads? That’s what we have computers for! <b>To simulate things</b>. We should have the PL show the regex to us in an easier to understand form, or perhaps even multiple forms. With unit tests. And visualizers. Or an embedded regex simulator to show how it works. I have a lot to say about regular expressions in an upcoming blog, but for now I'll just say they are some extremely low hanging fruit in the mission to reduce cognitive load. </p> <p> </p> <p> </p> <h2 id="id27946">Expanding Complexity </h2> <p> Now you might think, if we make a PL which sufficiently reduces cognitive load then programmers will have little to do. Programming will become so easy that anyone could do it. True, this might happen to some degree. In fact, I would argue that letting novices program is actually a good thing (though we would call it problem description rather than programming). However, in general this won’t happen. As we decrease the cognitive load we <i>increase the complexity of the programs we can make</i>. </p> <p> There seems to be a limit to how much complexity the human brain can handle. This limit varies from person to person of course. And it is affected by your health, hunger level, stress, tiredness, etc. (Never code on an empty stomach.) But there is a limit. </p> <p> Historically better tools have reduced the complexity at hand to something below the cognitive limit of the programmer. So what did we do? <b>We tackled more complex tasks</b>. </p> <p> <i>Josh’s first postulate of complexity</i>: <b>Just as data always expands to fill available disk space, programing tasks always increase in complexity to fit our brain budget</b>. </p> <p> Offloading complexity to tools merely allows us to tackle bigger problems. It’s really no different then the brain boost we got from inventing paper and pencil, just separated by a few thousand years. [1] </p> <p> Now I think we can agree that a PL which reduces more cognitive load of the human is better than one which reduces less. That's our metric. So how can we turn this into something actionable? Does it suggest possible improvements to real world programming languages? </p> <p> The answer is yes! If we stop focusing on PL implementations but rather the user experience of the programmer, then many ideas become readily available. Everything I’ve discussed in previous blogs is driven by this core principle. Showing a color or image <i>inline</i> reduces cognitive load because you don’t have to visualize in your head what the color or image actually looks like. The editor can just do it for you. This is just the beginning. </p> <p> </p> <h2 id="id54698">My Forever Project</h2> <p> These are ideas I’ve been working on a long time. In fact I recently realized some of these ideas have been in my head for twenty years. I found evidence of tools I (attempted) to write from my college papers. It’s only recently that everything has started to gel into an expressible form. It’s also only recently that we’ve had the "problem" of computers with too much computational power going to waste. This is my <a href='http://jwb.io/20130122-the-joys-of-having-a-forever-project.html'>Forever Project</a>. </p> <p> There’s so much possibility now. If a notepad and a text editor are our current cybernetic enhancements, what else could we build? Could Google Glass help you with programming? How about an Oculus Rift? Or using an iPad as an extra screen? The answer is Yes! We could definitely use these to reduce cognitive load while interacting with a computer. We just might not call all of these tasks "programming" but they are (or will be shortly as software continues to eat the world). </p> <p> <i>deep breath</i> </p> <p> </p> <p> My concept summarized: Programming systems should not be thought of as ways to make a computer do tricky things. They are ways to make a computer solve problems for you. Problems you would have to do in your head without them (assuming you could do them at all). Thus PLs are <b>tools for thinking</b>. This gives us a metric. Do particular PLs help us think better and solve problems better? As it turns out, most PLs fail miserably by this metric. Or at least they could be a whole lot better. Many ideas from the 60s and 70s still remain unimplemented and unused. </p> <p> But don’t be sad. Our field is less than 100 years old. We are actually doing pretty well. It took a few thousand years to invent suspension bridges and they still don’t work 100% of the time. </p> <p> So from now on let us consider how to make better tools for thinking. Everything <a href='http://worrydream.com'>Bret Victor</a> has been doing, and <a href='http://alarmingdevelopment.org/?p=893'>Jonathan Edwards</a>, and even the work from the 70s & 80s that <a href='http://en.wikipedia.org/wiki/Alan_Kay'>Alan Kay</a> did with Smalltalk and the Dynabook come back to the same thing: <i>building better tools for thinking</i>. With better tools we can think better thoughts. With better tools we can solve bigger problems. </p> <p> So let’s get crackin'! </p> <p> footnote: [1] Before someone calls me on this, I have no idea when paper and pencil were first invented for the purposes of reducing problem complexity. Probably in ancient Egypt for royal bookkeepers. I'll leave that as an exercise to the reader. </p> http://joshondesign.com/2014/09/10/cyberprog\nTabs vs Spaces, the Pointless WarSo far my posts on Typographic Programming have covered <a href='http://joshondesign.com/2014/08/25/typopl2'>font choices</a> and <a href='http://joshondesign.com/2014/08/22/typopl'>formatting</a>. Different ways of rendering the source code itself. I haven’t covered the spacing of the code yet, or more specifically: indentation. Or even more specifically: tabs vs spaces. <p> Put on your asbestos suits, folks. It’s gonna get <b>hot</b> in <i>this</i> kitchen. </p> <p> Traditionally source code has been rendered with a monospace font. This allows for manual horizontal positioning with spaces or tab characters. Of course the tab character doesn’t have a defined width (I’ll explain in a moment why) so flame wars have erupted around spaces vs tabs, on par with the great editor wars of the last century. Ultimately these are pointless arguments. Tabs vs spaces is an artifact of trying to render code into a monospace grid of characters. It’s the 21st century! We can do better than our dad's 1970s terminal. In fact, they did better in the <b>19th century</b>! </p> <p> </p> <h2 id="id1328">In The Beginning</h2> <p> Let’s start at the beginning. Fixed whitespace indenting can be used to line things up so they become pretty, and therefore easier to read. But that's a lot of work. All that pressing of space bars and adjusting when things change. </p> <p> Instead of manually controlling whitespace what if we used tab stops. I don’t mean the tab character, which is mapped to either 4 or 8 spaces, but actual tab stops. Yes. They used to be a real physical thing. </p> <p> <img src='http://i.imgur.com/mi0fg2Q.jpg' alt='image of typewriter tab stop'/> </p> <p> In the olden days, back when we used manual typewriters (I think I was the last high school class to take typing on such machines), there was such a thing as a tabstop. These were vertical brackets along the page (well, along that metal bar at the bottom of the current line). These tiny pieces of metal literally stopped the tabs, thus giving them the name <i>tabstops</i>. We were so creative with names in those days. </p> <p> When you hit the tab key the <i>cursor</i> (a rapidly spinning metal ball imprinted with the noun: “Selectric”) would jump from the left edge of the paper to the first tabstop. Hit tab again and it will go to the next tabstop. Now of course, these tab stops were adjustable, so you could choose the indenting style you wanted for your particular document. </p> <p> Let me repeat that. The tabs stops could be adjusted to the indenting style of <i>your particular document</i>. Inherent is the concept that there is no “one right way”, but rather the format must suit the needs of the particular document, or part of a document, that you are writing. </p> <p> When WYSIWYG editors came along they preserved the notion of a tabstop. They even made it better by giving you nice vertical lines to see the effect of changing the tabstop. When you hit tab the text would move to the stop. If you later move the stop then the text aligned with it will magically move as well. Dynamic tabstops! Yay. We can finally rock like its the 1990s. </p> <p> </p> <p> <img src='http://computersandcomposition.candcblog.org/archives/v10/10_2_html/10_2_8_Boudreau1.gif' alt='Word for Mac, circa 1991'/> </p> <p> </p> <p> </p> <h2 id="id63003">Semantic Indentation</h2> <p> So why do we go back to the 1970s with our text editors? Tabstops are a simple concept for semantically (sorta) indenting our code. Let’s see what some code would look like with simple <i>tabular</i> semantic indenting. </p> <p> Here’s some code with no formatting other than a standard indent. </p> <p> <img src='http://joshondesign.com:3194/images/3391_SafariScreenSnapz030.png' alt='text'/> </p> <p> This is your typical Cish code with brackets and parameters. It would be nice to line up the parameters with their types. The drawRect code is also similar between lines. We should clean that up too. </p> <p> </p> <p> Here is code with semantic indenting. </p> <p> <img src='http://joshondesign.com:3194/images/41902_SafariScreenSnapz031.png' alt='text'/> </p> <p> </p> <p> How would you type in such code? When you hit the tab key the text advances to the next tabstop. these tabstops are dynamic, however. Instead of giving you a line with a ruler at the top, the tabstops automatically expand to fit the text in the column. Essentially they act more like spreadsheet cells than tab stops. </p> <p> Furthermore, the text will be left aligned at the tabstop by default, but right aligned for text that ends with a comma or other special character. This process is completely automatic and hidden, of course. The programmer just hits the tab key and continues typing, the IDE handles all of the formatting details, <i>as it should be</i>. We humans write the important things (the code) and let the computer handle the busy work (formatting). </p> <p> The tab stops (or columns if you think of it as a table) don’t extend the entire document. They only go down as far as the next logical chunk. There could be multiple ways to define a ‘chunk’ semantically, but one indicator would be a double space. If you break the code flow with a double space then it will revert to the document / project wide defaults. This lets us use standard indentation for common structures like functions and flow control bracing, while still allowing for custom indentation when needed. </p> <p> </p> <h2 id="id86177">Ludicrous Speed</h2> <p> </p> <p> Furthermore, using semantic indentation could completely remove the need for braces as block delimiters. Semantic indentation can replace where blocks begin and end. </p> <pre><code>if(x==y) { foo } else { bar }</code></pre> <p> becomes </p> <pre><code>if x==y foo else bar</code></pre> and<pre><code>if(x==y) { foo }</code></pre> can become<pre><code>if x==y foo</code></pre> or even<pre><code>if x==y foo</code></pre> <p> using the tab character. </p> <p> This might be a tad confusing, however, because there is only whitespace between the <code>x==y</code> and the <code>foo</code>. How do we know its not a space instead? If you hit the tab key, which indicates you are going to the next chunk instead of just a long conditional expression, the editor could draw a light glyph where the tab is. Perhaps a rightward unicode arrow. </p> <p> Now I know the Rubyists and Pythoners will say that they've already removed the block delimiters. Quite true, but this goes one step further. </p> <p> Python takes the choice of whitespace away from the programmer, but the programmer still has to implement it. With semantic indentation the entire job of formatting is taken away. You just type your code and the editor does the right thing. Such a system also opens the door for alternative rendering of the code in particular circumstances. </p> <p> </p> <h2 id="id274">Better Fonts</h2> <p> And of course we come to our final advantage. Without manual formatting with spaces we don't need to be restricted to a monospace font anymore. Our code could look like this: </p> <p> <img src='http://joshondesign.com:3194/images/43574_SafariScreenSnapz032.png' alt='text'/> </p> <p> Semantic indenting. Less typing, more readable code. Let’s rock like it’s the 1990s! </p> http://joshondesign.com/2014/09/02/bar\n60 sec review: The Art of Lego Design<b>The Art of LEGO Design: Creative Ways to Build Amazing Models</b> <p> <i>by Jordan Schwartz</i> </p> <p> </p> <p> <a href='http://www.nostarch.com'>No Starch Press</a> is really doubling down on their Lego books. Their latest is a stunner. <a href='http://www.nostarch.com/legodesign'>The Art of Lego Design</a> by Jordan Schwartz is less of an art book and more of a hands on guide. It shows actual techniques used by the Lego artists featured in other No Starch books like Mike Doyle’s <a href='http://www.nostarch.com/beautifullego'>Beautiful Lego</a>. </p> <p> As one of the LEGO Group’s youngest staff designers; <a href='http://www.jrschwartz.com'>Jordan Schwartz</a> worked on a number of official LEGO sets. His attention to detail and gift for teaching really come through in the book. Many of the models that seem impossible at first, such as stained glass windows, are actually pretty simple once explained in the book. </p> <p> <i>The Art of Lego Design</i> is the perfect entry point to rabbit hole that is Lego sculpture. With Lego specific jargon like cheese slopes, SNOT (Studs Not On Top), and the Lowell sphere; it would be easy to get lost; but Jordan explains it all clearly, along with general design principles like texture and composition. </p> <p> The book takes the reader through many styles of construction and technical advantages of different pieces, with as dash of Lego history thrown in. I didn’t know there once was a Lego set with a fuzzy bear rug or a line of big Lego people for the Technic sets. </p> <p> </p> <p> Read or Read Not? <b>Read!</b> </p> <p> <a href='http://www.nostarch.com/legodesign'>Get it from No Starch Press</a> </p> http://joshondesign.com/2014/09/01/legodesign\nTypographic Programming: FontsApparently <a href='http://joshondesign.com/2014/08/22/typopl'>my last post</a> hit <a href='https://news.ycombinator.com/item?id=8214257'>HackerNews</a> and I didn’t know it. That’s what I get for not checking my server logs. <p> Going through the comments I see that about 30% of people find it interesting and 70% think I’m an idiot. That’s much better than usual, so I'm going to tempt fate with another installment. The general interest in my post (and let’s face it, typography for source code is a pretty obscure topic of discussion), spurred me to write a follow up. </p> <p> In today’s episode we’ll tour the font themselves. If we want to reinvent computing it’s not enough to grab a typewriter font and call it a day. We have to plan this carefully, and that starts with a good selection of typefaces. </p> <p> </p> <p> Note that I am <i>not</i> going to use color or boxes or any other visual indicators in this post. Not that they aren’t useful, but today I want to see how far we could get with just font styling: typeface, size, weight, and style (italics, small caps, etc.). </p> <p> </p> <p> </p> <p> Since I'm formatting symbolic code, data, and comments; I need a range of typefaces that work well together. I’ve chosen the Source Pro family from Adobe. It is open source and freely redistributable, with a full set of weights and italics. More importantly, it has three main faces: a monospace font: Source Code Pro, a serif font: Source Serif Pro, and a sans-serif font: Source Sans Pro. All three are specifically designed to work together and have a range of advanced glyphs and features. We won't use many of these features today but they will be nice to have in the future. </p> <p> </p> <p> Lets start formatting some code. This will be a gradual process where we chose the basic formatting then build on top for different semantic chunks. </p> <p> For code itself we will stick with the monospace font: Source Code Pro. I would argue that a fixed width font is <i>not</i> actually essential for code, but that’s an argument for another day when we look at indentation. For today we’ll stick with fixed width. </p> <p> </p> <p> Code comments and documentation will use Source Serif Pro. Why? Well, comments don’t need the explicit alignment of a monospace font, so definitely not Source Code Pro. Comments are prose. The sans serif font would work okay but for some reason when I think "text" I think of serifs. It feels more like prose. More <i>texty</i>. </p> <p> So I won’t use Source Sans Pro today but I <i>will</i> save it for future use. Using the Source [x] Pro set gives us that option. </p> <p> Below is a simple JavaScript function set with the default weights of those two fonts. This is the base style we will work from. </p> <p> </p> <p> <img src='http://joshondesign.com:3194/images/38720_SafariScreenSnapz025.png' alt='text'/> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> So that’s a good start but.., I can immediately think of a few improvements. Code (at least in C derived languages) has five main elements: comments, keywords, symbols, literals, and miscellaneous — or what I like to call ‘extraneous cruft’. It’s mainly parenthesis and brackets for delimiting functions and procedure bodies. It is <i>possible</i> to design a language which uses ordering to reduce the need for delimiters, or to be rid of them completely with formatting conventions (as I talked about last week). However, today’s job is to just restyle without changing the code so let’s leave them unmolested for now. Instead we will minimize their appearance by setting them in a thin weight. (All text is still in black, though). </p> <p> Next up is symbols. Symbols the part of a program that the programmer can change. These are arguably the most important part of the program; the parts we spend the most time thinking about, so let’s make them stand out with a very heavy weight: bold 700. </p> <p> </p> <p> <img src='http://joshondesign.com:3194/images/28447_SafariScreenSnapz026.png' alt='text'/> </p> <p> </p> <p> </p> <p> Better, but I don’t like how the string literal blends in to with the rest of the code. String literals are almost like prose so let’s show them in serif type, this time with a bolder weight and shrunk a tiny bit (90% of normal). </p> <p> For compatibility I did the same with numeric literals. I’m not sure if ‘null’ is really a literal or a symbol, but you can assign values to it so I’ll call it a literal. </p> <p> <img src='http://joshondesign.com:3194/images/34373_SafariScreenSnapz027.png' alt='text'/> </p> <p> </p> <p> Next up is keywords. Keywords are the part of the language that the programmer <i>cannot</i> change. They are strictly defined by the language and completely reserved. Since they are immutable it doesn’t really matter how we render them. I could use a smiley face for the <code>function</code> keyword and the compiler wouldn’t care. It always evaluates to the same thing. However, unlike my 3yr old’s laptop, I don’t have a smiley face key on my computer; so let’s keep the same spelling. I do want to do something unorthodox though. Let’s put the keywords in <i>small caps</i>. </p> <p> </p> <p> Small caps are glyphs the size of lower case letters, but drawn like the upper case letters. To do small caps right you can’t just put your text in upper case and shrink it down. It would look strange. Small caps are actually different glyphs designed to have a similar (but not identical) width and a shorter height. They are hard to generate programmatically. This is one place where a human has to do the hard work. Fortunately we have small caps at our disposal thanks to the great contributions by <a href='http://blog.typekit.com/2012/11/02/source-sans-pro-adoption-and-development-to-date/'>Logos and type designer Marc Weymann</a>. Open source is a good thing. </p> <p> </p> <p> <img src='http://joshondesign.com:3194/images/77897_SafariScreenSnapz028.png' alt='text'/> </p> <p> </p> <p> </p> <p> Now we are getting somewhere. Now the code has a <b>dramatically</b> different feel. </p> <p> </p> <p> There’s one more thing to address: the variables. Are they symbols like function names? Yes, but it feels different than function names. They are also not usually prefixed with a parent object or namespace specifier. Really we have three cases. A fully qualified symbol like ‘baz’ in foo.bar.baz, the prefix part (foo.bar), and standalone variables that aren’t qualified at all (like ‘x’). This distinction applies whether or not the symbol is a function or an object reference (it could actually be both in JavaScript). </p> <p> </p> <p> In the end I decided these cases are related but distinct. Standalone symbols have a weight of 400. Technically this is the default weight in CSS and shouldn’t appear to be ‘bold’, but since the base font is super light, regular will feel heavier against it. The symbol at the end of a qualifier chain will also be bold, but with a weight of 700. Finally the prefix part will be italics to further distinguish it. There really isn’t a right answer here; other combinations would work equally well, so I just played around until I found something that felt right. </p> <p> This is the final version: </p> <p> <img src='http://joshondesign.com:3194/images/81556_SafariScreenSnapz029.png' alt='text'/> </p> <p> </p> <p> </p> <p> I also shrunk the comments to 80%. Again it just felt right, and serifed fonts are easier to read in longer lines, so the comments can handle the smaller size. </p> <p> </p> <p> Here’s a <a href='http://joshondesign.com/p/demos/typopl/test2.html'>link to the live mockup</a> in HTML and CSS. This design turned out much better than I originally thought it would. We can do a lot without color and spacing changes. Now imagine what we could do will our full palette of tools. But that will have to wait for next time. </p> <p> </p> <p> BTW, if you submit this to Hacker News or Reddit please let me know <a href='https://twitter.com/joshmarinacci'>via Twitter</a> so I can answer questions. </p> http://joshondesign.com/2014/08/25/typopl2