While reviewing other developers’ code, one of the issues I face very often is its readability. Before understanding whether a piece of code is correct and what improvements can be done, a reviewer needs to be able to read the code and understand its internal structure, its approach, to later see what it does in general terms.
In this post I’ll talk about HTML with a extremely simple example, but it obviously can be expanded. In my reviews, I often see pieces of code like this, which is by the way a perfect valid piece of code:
<form> <fieldset> <div> <input type="text" id="fullname" name="fullname" placeholder="Arthur Dent" required> <label for="fullname">Your full name</label> </div> </fieldset> </form>
Intentionally, I have avoided common attributes like class names or event callbacks, but even without them, isn’t it hard to read? Specially that
input with several attributes.
On top of that, we could easily have more HTML code, or a function or a
Class to wrap the component in any framework. That would increase as well the indentation and make the lines longer, probably out of our screen if you divide the editor in two columns.
Instead of that long lines of code, I usually prefer a more vertical version where each one of the tag names and attributes is in its own line of code, except for tags with a single attribute.
Following the first example:
<form> <fieldset> <div> <input type="text" id="fullname" name="fullname" placeholder="Arthur Dent" required > <label for="fullname"> Your full name </label> </div> </fieldset> </form>
Am I the only one seeing the beauty in this HTML code styling? I can think of several reasons why I prefer the latter:
- It is more readable.
- It is more understandable when this code becomes legacy.
- It has room for more attributes without decreasing readability.
- Avoid horizontal scroll in favor of a more natural vertical scroll.
- New frameworks are modular, code files tend to be have a fairly reduced number of lines. Meaning that normally the number of lines is not an issue.
- A developer can still collapse the tags in the editor. Although that means some extra clicks, I do that all the time to see general structures without focusing on details.
- Makes easier to split the code editor into two columns.