Elegance, or, simplicity, or as some have call it “the right way” is something all developers strive towards. The feeling of developing a clean, tight, and elegant solution to programming problems is something we all enjoy.
Today a thread came up on twitter which opened the topic so i decided it would be time to get some of my thoughts down. This is very much a first thoughts on the topic and i am really interested in discussion.
Elegance, thought hidden complexity is not real elegance.
One of the suggested solutions was to use a clever jquery selector, it simply identified any links where were not relative. This is a very clever solution, its superficially clean and elegant. However, on closer inspection i feel uncomfortable about it.
The reason is thus, simplicity and using things how intended is important for something to be elegant. In the world of standards we have an in built way of identifying hooks for behaviors and styles. Which is simply the class attribute.
Im my opinion as long as a class is semantic and meaningful then it makes sense to use one. Even more so if the class in question will also be used for styling the external. Though, at the same time, we need to be careful not to litter our code with meaningless classes or going class crazy.
By using a class attribute with the value of “external” then we have have our hook for both styling and CSS. Its not heavy markup, its flexible and it makes sense in the context. Another side effect is that i makes the markup link into the script in a easy to follow and understand way. By looking at the markup and seeing the class i can easily see how the open in new window functionality works. It provides more context to the solution.
1: Its brittle - it will give false positives when using absolute URLS. And coding around this flaw makes the solution less elegant.
2: Its needlessly complex. It hides the complexity within the jQuery source code but it is a very heavily solution. just because the complexity is hidden does not mean that its not there. Using a simple class is less complex, and thus i would feel the better solution.
3: its not easy to see. As i have mentioned above, its more complex to see the relationship with the markup and the code. If i was investigating how the clever jquery worked i don’t really have any clues. I will have to read all the source code or look for comments. Using a class of external, i can simply search the JS for the class name and then find the related script.
class=”external” is not perfect tho
For one, its added weight to the page. It makes pages heavier and means that external links need to be marked. This adds some complexity to any backend code and slows the page down a little.
So, theres my thoughts. Please feel free to shares you in the comments or ask any questions.