2010
Every time you use CSS, you’re doing Aspect-Oriented Programming
Each AOP term and its HTML/CSS counterpart…
| AOP | HTML/CSS | explanation |
|---|---|---|
| join point | every HTML element | places you could possibly apply behavior |
| pointcut | CSS selector (e.g. #nav span.highlight) | expression that specifies which places to apply behavior |
| advice | CSS declarations (e.g. color: blue; margin: 1em;) | what behavior to apply |
| aspect | logical grouping of CSS statements (selectors + declarations), sometimes separated into its own .css file | module that groups the combination of what behaviors to apply and where to apply them that logically has to do with the same thing/feature (i.e. have the same concern) |
Once you start spending a lot of time writing HTML and CSS, you start to see patterns. Groups of CSS rules that you re-use all the time. CSS classes can be used as functions.
Instead of saying:
<div style="clear: both">
… you can define a clear class …
.clear {
clear: both;
}
… and then say …
<div class="clear">
At first, this might not seem like it saves a lot, but depending on your site, the patterns may be bigger. For example, when I was working with Chap Ambrose, I discovered he used a class called float_left all over. I immediately assumed it applied the single rule “float: left”, so I began using it too. However, I got frustrated when I realized the “float_left” class applied two rules:
.float_left {
float: left;
margin-right: 1em;
}
Eventually, though, by spending more time writing HTML/CSS, it became obvious to me that a lot of the time, when I want to float something, I also don’t want the things next to it bumping up against it. I want there to be a margin. And so the pattern (or function) is born.
So What about Aspect-Oriented Programming?
A group of CSS rules is essentially a function. (They even use the same curly-brace and semicolon syntax.) But with CSS, you actually don’t have to explicitly call a function to use it. Where you define the CSS rules (or function), you can use a selector instead of a class name which injects the behavior where you want it. The advantage is that you never have to explicitly reference the CSS rules where they’re used — i.e. you never have to explicitly call the function.
When you write the following CSS statement, you’re injecting the behavior of the rules into your entire site, without touching the code that’s already there.
form h1 {
font-size: 15px;
color: blue;
}
Suddenly, all h1 tags inside forms have this behavior, even though none of them reference this “function”.
Aspect-oriented programming is the most misunderstood programming paradigm. But fundamentally, the reason it exists is the same reason CSS exists — to better separate concerns in your code.



