Smooth CoffeeScript

Page 175

Modularity

I think you can see that this code practically begs to be abstracted and modularized. Instead of an if chain, we could have a function with an object as argument where each attribute is a request and each value a function to handle the request. Then there is error handling, if the file is not found then the server throws an error and stops. The purpose of '10-SeedLife.coffee' is to show how you can use a module on a web page, so refactoring and beautifying the server is up to you27 . Building a program as a set of nice, small modules often means the program will use a lot of different files. When programming for the web, having lots of small code files on a page tend to make the page slower to load. This does not have to be a problem though. You can write and test your program as a number of small files, and put them all into a single big file when ‘publishing’ the program to the web. The CoffeeScript compiler has a join feature for this.

◦•◦ A module or group of modules that can be useful in more than one program is usually called a library. For many programming languages, there is a huge set of quality libraries available. This means programmers do not have to start from scratch all the time, which can make them a lot more productive. For CoffeeScript, unfortunately, the number of available libraries is not very large. But you can use JavaScript libraries as a stopgap. Underscore is an example of a good library with its ‘basic’ tools, things like map and clone. Other languages tend to provide such obviously useful things as built-in standard features, but with CoffeeScript you will have to either build a collection of them for yourself or use a library. Using a library is recommended: It is less work, and the code in a library has usually been tested more thoroughly than the things you write yourself. Some things to check when selecting a library is functionality, adequate documentation, and readable source code — and that the library is small enough that you can understand and fix bugs in it — if need be on your own.

◦•◦ 27

If you want to understand how to write your own HTTP server then Manuel Kiessling has a tutorial that you can easily translate into your own CoffeeScript web server.

174


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.