Structuring JavaScript libraries: modularity
The answer is simple, all those libraries try to conceal the apparently contradictory needs that are generalization and customization.
We need to generalize to have calendar functions that can be used in all the situations without any modification. To achieve that we strip from the library all the features that are specific to a given case. We end up having a library that does almost nothing, like simply returning days of a month organized in a 7 days × 6 weeks grid.
We need to customize to have calendars displaying week numbers, allowing date range selection or time picking. To achieve that we add the features, and for each of them a flag that we can activate or not, allowing us to enable the feature only when needed. We end up having a library continuously growing, with numerous parameters and difficult to maintain.
The JavaScript language allows easy integration of multiple libraries with the notions of callbacks and object oriented programming.
The idea is simple: define core features and write separate libraries for each of them. Define the data structure that will allow communication between them. Define simple default behaviors for features that can be overridden with additional plug-ins.
If you use only the core library, you have a simple set of features easy to understand and with few parameters. You can plug more features if you need them. You can rewrite your own plug-in - and only this one - if it does not exactly meet your needs.
For a calendar, the code feature is to display a date grid. The data structure is a date value, with flags indicating if a date range is selected. The additional plug-ins could be week number information, enabling selection of a month or a year, adding a second calendar for range selection, allowing time picking.
Each of these plug-ins is obviously small, easy to maintain and debug. You reduce the amount of code to download to the client if you don't use all the features.
A common mistake is mixing HTML rendering with internal logic. Avoid that at all cost, and eventually make the render engine a plug-in.
Creating modular libraries may seem more complicated at first look, but forcing you to think of the structure before you start will make your ideas clearer and you will actually reach your goal faster.
Labels: JavaScript, Methodology
