Chapter 9. Separate Configuration Data from Code
Code does nothing more than define a set of instructions for a computer to execute. Data is frequently passed around and modified by those instructions, ultimately producing a result. The problem comes when the data must change. There’s a risk of creating an error any time you edit source code, and editing code just to change some data value introduces unnecessary risk for something that shouldn’t affect the surrounding instructions. Well-designed applications keep vital data outside of the main source code to ensure worry-free editing.
What Is Configuration Data?
Configuration data is any hardcoded value in an application. Consider the following example:
// Configuration data embedded in code function validate(value) { if (!value) { alert("Invalid value"); location.href = "/errors/invalid.php"; } } function toggleSelected(element) { if (hasClass(element, "selected")) { removeClass(element, "selected"); } else { addClass(element, "selected"); } }
There are three pieces of configuration data in this code. The first is the string “Invalid value,” which is displayed to the user. As a UI string, there’s a good chance that it will change frequently. The second is the URL /errors/invalid.php. URLs tend to change as development progresses, due to architectural decisions. The third is the CSS class name “selected.” This class name is used three times, meaning that a class name change requires changes in three different places, increasing the ...
Get Maintainable JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.