Posts Tagged ‘patterns’

planning a frontend architecture

Saturday, August 14th, 2010

About two months ago, I was asked to begin writing widgets for a product that didn’t exist even as a set of requirements. I declined to do this task, but couldn’t really explain why. Now the same project is nearing completion and I’m finally able to articulate my misgivings about writing code in anticipation of the actual use cases, and with not planning out the front-end before coding it in general.

As developers, I think we’ve got some cultural issues that often preclude planning things very well. For one, we often tend to become so enamored of our own code/approach that we refuse to admit when it doesn’t address the goals of the application it’s used in. I’m super guilty of that, myself. For another, when it’s crunch time we have a tendency to get all heroic, pulling all-nighters and promising things we know we shouldn’t be promising. Combine these proclivities and you get the potential for creating a codebase out of weird one-off solutions that have been hacked together overnight to form an “architecture” that’s the code debt equivalent of those 0% interest for one year credit cards that balloon up to 33% the first time you miss a payment. And you promise, naturally, that you’ll refactor all that as soon as things quiet down, but let’s face it: if things quiet down it’ll be because you moved on to some other project, and even when someone does finally find the time to refactor it they’re just going to tear the mess out and start from scratch.

That’s the project I’m on right now, the project that began with a request for widgets. There’s been no front-end planning in the scope of the application as a whole, aside from a consensus about where JS and CSS files should live. The same tasks are performed differently on different pages. Custom plugins are used in places they weren’t designed for. But those aren’t even such serious issues. The plugins can be made more (or less) generic, that’s not a terribly difficult change to make. What’s going to be problematic is going back after the fact and defining an actual architecture where currently we just have lots of code.

I’m no expert on this shit. But it is something I’ve done several times out of necessity, in the interest of doing good work and preserving my sanity. If I were going to get in my time machine and head back to where this project began (taking all the user stories with me, even at the risk of creating a catastrophic paradox) here’s what I’d do:

Figure out the requirements

If you’re on a project you’re doing for money (i.e., not a personal labor of love), presumably you have a project owner or some other business person who will tell you what the product needs to do. But there’s a difference between those requirements and the requirements you’ll code to. I believe front-end developers are people who have to be willing to dip their toes into a variety of fields to be effective. We have to be able to consider the best technical solution, but that’ll come later in the process. When the planning stage begins, we need to be able to ask the right questions about things like branding, design, and copy, things that – when you look at our role literally – ought not concern us. Whitney Hess wrote a really good article on this recently, listing off all the things developers, not just IAs or UX Designers, should figure out before even thinking about writing code.

Why do we need to know all that crap? Why can’t we just wait for someone whose actual job it is to figure it out to do so? For the same reason we don’t put our code in a glass case as soon as we write it and never change it again over the course of the project: every spec, wireframe, and mockup you receive is subject to change. If it’s a couple words in the copy, NBD. But if the change completely alters, for instance, the intent of the site’s landing page and what information it contains, your code is going to be completely fucked and newly useless. Unless you make a nuisance of yourself starting the second you arrive at the kickoff meeting and ask lots and lots of questions about things that are none of your business. If you know the business goals of each piece of your application, you can better predict what the requirements for the final product will end up being, and you can write code based on assumptions that are more likely to be correct.

Define the ground rules for users

This isn’t as simple as just saying, “We’ll support IE7 and up.” In addition to which browsers the users favor, you have to know:

  • What is their level of internet savvy
  • Do they have Flash/Silverlight/some other damned thing installed
  • Are they accessing the site from mobile devices and, if so, which ones
  • Most important: do they all have Javascript enabled

Dealing with mobile, accessibility, and other issues is complex and challenging, and I don’t mean to imply it’s not. However, the thing most likely to completely alter the shape of your application, to my mind, is Javascript support. If you can assume Javascript, you’re kind of home free, much in the way you would be if you could guarantee all your users had the latest version of Webkit installed or something. If you can define your audience that narrowly, super. And not fucking likely. Even Gmail, poster-child for the single page app revolution, has that “little Gmail” for people with Javascript turned off. If you can get away with it, that’s a great approach – just write a different, simpler app for no-JS and older browsers. If there is no “optional” functionality, however, you have to figure out how to do two things with every click, and it’s hardly just as simple as hijacking the click with Javascript and progressively enhancing. I cannot tell you how many times in the last week I’ve been provoked nearly to the point of throwing things by issues that arose due to not dealing with this problem at the outset.

Duke it out with your backend people

Your counterparts on the backend are probably having their own discussion about architecture. If you don’t want to be in the position of having to work around decisions they make that affect you, talk to them early while all this shit is still hypothetical. If they can integrate your pattern into theirs (and vice versa), things will probably go a lot smoother. I’ve talked here before about how I think it’s ideal when the only thing frontend people and backend people need to discuss is what properties should be in a JSON object and what form elements should be named when they get POSTed. If you can get to that point, you save a ton of grief. It’s great to be able to switch between the front and back end, but if you have specialists on both sides, it’s better to just have everyone stick to their territory. Yeah, I said it, grab some territory. Grab it early. I don’t care if that sounds like I’m advocating not being a team player. If your area of concern is the entire fucking application, you’re going to be a lot less efficient and your “team” is going to end up in last place, if you finish at all.

Pimp your ride

Probably you are gonna need some bling. You’re going to need widgets like a calendar to ease the selection of dates and a rich text editor so your users can have access to extremely important features like bulleted lists. You’re going to need swooshy little animations whenever something updates and tooltips that look like little thought-bubbles. Find all of these things. Search through every mockup and run a mental background check on every IA and Visual Designer working on your project to try and remember their propensities. Once you’ve defined them, research each and look at all your options. Rank them, list the pros and cons, and group them by framework. Don’t forget to look at the CSS and the markup they generate. There exist plugins that look totally hot on their demo pages, but are rapidly revealed to be complete pieces of shit once you try to reskin them. And then you can’t change the background color of the RTE without rewriting the whole damned thing and the utility of the plugin nosedives and your client tries to sue you.

Choose a framework

Having clearly defined your needs, you’re in a position to choose the toolkit that will best meet them (or to be a masochistic purist and choose no toolkit at all). In this idealized timeline, this is the penultimate step, but of course it may not always be possible. Sometimes you’re stuck with one framework because it’s what your company has standardized on and you’re using it in a bunch of related applications and – though not ideally suited – it’s good enough. There is an argument for sticking with what’s in place because it’s familiar. But let’s say you can choose. If you’ve got a good sense of the project’s requirements and how those will translate to framework-dependent things like server communication and plugins, this should be a no-brainer. Refer to the totes awesome research you’ve labored over and commit.

Do all those things you’re supposed to do

You know. Write unit tests. Write documentation. Lazy-load your scripts instead of just dumping them all down at the bottom of the page and telling yourself they don’t really count if they’re there. Kick off the infrastructure before you start creating objects and wiring things up to page elements. For me, this is a totally theoretical step. I have yet to do this on the frontend, and I know that is a really bad thing. The last time I wrote a unit test, I was a state employee. The last API I documented was for a JSF widget library, and this was when JSF was the new hotness. The problem is that I don’t think about it early enough. Like refactoring, I tell myself I’ll do this when things quiet down. And things never quiet down. They start quiet and get progressively noisier. If, on my current project and on many prior to it, I’d started with this type of “housekeeping,” I think I would have actually had time to do it. Instead I got bogged down adding more features, fixing bugs (bugs unit tests would have helped discover), and finally explaining the code to whoever I handed it over to (which would have gone much more quickly if I’d documented it outside of random where-I-thought-of-it inline comments). I am totally sick of doing things that way. Next project I work on, immediately after downloading whatever toolkit I’m using, I will take care of this stuff.

So there’s my plan. Now I just need the time machine, and I’m golden.

Addendum: It feels weird to talk about this stuff without mentioning Rebecca Murphey’s recent posts on large applications and rolling your own. It’s not directly related, but it’s something I’ve been thinking about a lot lately, as I’m sure many other people have. Something I couldn’t find a way to spell out clearly above was that, if I were going back to square one with those posts in mind and it were all up to me, I might have made different choices as far as a toolkit. Then again I might not have – this is not the world’s most complex app here, it’s mostly just a lot of show/hide and XHRs. Doesn’t mean it shouldn’t be unit tested and documented, though, and having a clear way of handling data from the server and XHRs from the get-go would definitely have made a difference in the amount of time we’ve spent debating different approaches. I do think debates like that are worth having, but sometimes it’s also very valuable to be able to point to a toolkit and say, “This is the [Framework X] WAY.” Anyway, my point is that this is not an exhortation to come up with the whole thing on your own, merely to get all the pieces laid out and thought about beforehand.

5 ways to not write html in your backend code

Sunday, July 11th, 2010

At work right now I’m involved in a minor turf war over HTML. I write it in the .aspx and then other people sometimes move it into the C#, which aggravates me. The reason given for this is Don’t Repeat Yourself, but I’m trying to make the case that there are other ways to respect DRY in this situation. I can think of at least five methods that would be both more maintainable and less code the server needs to interpret.

1. Provide additional properties

I admit it’s not the cleanest thing to do, but adding boolean properties on the objects being rendered that say things like whether a user is the same one who’s logged in or whether some object has an image attached to it offers a lot of flexibility on the UI. It’s a simple way to get around writing backend logic in the page itself while offering the possibility of later reuse. It’s messy, though, because there’s a temptation to just misuse existing properties instead of asking for a new property, and conversely, you can end up with a lot of duplicate information. A good example is the length of an array. You could end up repeatedly asking the array for its size to render things differently for 0 objects or some minimum number of objects that you want users to be able to page through. You could get this information instead in properties like hasObjects and doPaging or something, but that’s just adding to an API things you could infer from what you have already. And neither alleviates the need for backend loops and conditionals mixed in with your HTML.

2. Put repeated logic in user controls

Forgive me for not knowing how this concept works in other frameworks, but I’m guessing they all natively have something similar or can be abused into offering it. Instead of adding helper properties to your API, you could create those properties based on a single object passed into a control. This is less flexible than having the extra properties available to everything on the page, but it feels much cleaner and object oriented. In .NET MVC, there seems to be a movement against having code behinds for anything, which I think is unfortunate, since creating helpers for use within the context of a specific user control based on one large, self-contained object makes much more sense from an MVC perspective than having the server try to figure out beforehand everything the page will need.

3. Use JSON and render everything client-side

This is not a solution that works for all situations, obviously, since it requires Javascript. However, if you’ve got a client-based application that just has to have Javascript anyway, it works very well. I know this is not a popular approach with some people because of the extra rendering time when the page/application first loads and you have to parse and insert your data only after that happens, instead of doing it all beforehand. But if we’re assuming this is a client-based application, we can also assume it runs on AJAX and you’re only going to be loading the page once. So sometimes the tradeoff seems acceptable.

4. Server side Javascript

Since I haven’t actually played with this technology, I will sound like a dumbass if I try to go into why this would be good and therefore I won’t. But from what I think I understand of it, it would fix the problems in the method above (reliance on Javascript, needing to parse everything when the page first loads). I take the proposal to include templates in jQuery as a sign that, if templates don’t already work with these server side JS technologies, they soon will. If I’m correct about not needing duplicate files, it seems like it could be really easy and fly as hell.

5. User controls + templates

This is my favorite. When the page first renders, you pass an object from the server side into the control, it plugs in the values, and all the HTML is rendered and ready when the client downloads it. Say there’s an existing list of Things, and the user adds a new Thing. The markup from the same user control that rendered the other Things has been added to the page inside a script tag (or a convenient external URL) and now, when the server responds with the confirmed data about the newly added Thing, it’s applied to the template and that gets rendered without refreshing the page. I think that’s fucking elegant. My boss thinks I’m high and that we should put the markup in user controls and use those both the first time the page renders and to respond to XHRs with the markup pre-populated.

If you’re reading this, what do you think? Am I betting on the wrong horse here? Did I miss something?

tracking focus on multiple objects

Friday, July 9th, 2010

You remember that time period when website navigations of all types had to be in drop-downs? Remember when they’d be like two, three levels deep, pretty much your whole damned site map stretched out across the top or down the left of your page? I remember that. And during that time, I remember running into a problem that plagues me to this day. I was using Dead Edwards’ IE7 to get :hover to work, I think, and still running into problems because IE was interpreting my mousing over a child element as equivalent to mousing out of its parent. I find it annoying that this is still an issue.

I was trying to implement an autocomplete jQuery plugin at work today and was dismayed that I had apparently broken it by putting overflow:auto and a height on the faux dropdown of results. Clicking on the scrollbar (thus out of the input field) hid the results div. I was able to fix it using the code below, but then the damned thing would hide itself if I scrolled and then tried to click one of the results to select it:

// track whether the field has focus, we shouldn't process any results if the field no longer has focus
hasFocus = true;
.blur(function() {
// track whether the field has focus
hasFocus = false;
if (!resultsHasFocus) {
.mouseover(function(e) {
resultsHasFocus = true;
.mouseout(function(e) {
resultsHasFocus = false;
if (!hasFocus) {

Fortunately, my neighbor in the cube village at work is Mr. Cravey, and I was able to turn to him and ask him if he knew how to get IE to stop misinterpreting my mouse movements (he did – substitute mouseenter and mouseleave for mouseover and mouseout, something I cannot believe I lived this many years without knowing). Strangely enough, he had the code right in front of him because he was working on a very similar problem.

And so we had an interesting discussion about how you track explicit and implicit focus (i.e., clicking and hovering) across multiple different objects in order to determine when to toggle state. I kept the approach above, setting flags, because the elements I needed to track focus in didn’t share a container. His did, and required only explicit focus, so I believe he ended up using focusin and focusout. We sort of agreed that, once this problem gets sufficiently complex, there’s no solution for it that isn’t kind of dirty. Setting flags seems like it shouldn’t be necessary, but it’s a very obvious way for separate elements to inform each other of their state so that one doesn’t go toggling something the other isn’t ready to have toggled yet. I was thinking about custom events, but honestly that feels like a more palatable version of the same concept, like the old cat food commercial where the cat food has been mashed up and adorned with a sprig of parsley.

Kind of dancing around the real issue here, which is not actually the focusing, but the blurring. Assuming what you want to toggle is show and hide, you put a little close button on that shit and none of this is an issue anymore. The real problem is that any member of the set of tracked elements can opt in on behalf of all of them, but they all need to explicitly opt out.

I know what seems like the most comprehensive solution to me, but it’s not very elegant.. It would be thorough, though, to put your series of objects in an array and attach handlers for both implicit and explicit focus and blur to the array itself. I could see that taking a long time, though, since you’d have to check whether anything in the array had focus every time something within the array lost or received it. Practically, the best thing to do is probably to use Cravey’s method even in cases where it means adding an extra wrapper element. One extra tag is really not so bad when compared to any alternative I can think of.

MVC in Javascript

Friday, August 21st, 2009

Nothing against Ajaxian, but I don’t usually look to them for pithy wisdom – mostly I look to them for clever jQuery plugins and stuff. However, the paragraph at the end of this post on MVC for Javascript sums up my feelings pretty well:

If you think that view source / semantic markup is a great feature of the Web platform, then this kind of world is a touch worrying, but major apps have been doing this for years.

Once I worked on this project with a lot of contractors from IBM, and they were the ones defining the architecture. They had a very literal approach to MVC. As in, every single link went through a controller. Home link? Ask the controller. About Us link? Ask the controller. I’ve implemented MVC in C# (back before they had the framework for it, which from what I gather is pretty cool) and had it be useful, don’t get me wrong.

MVC to me is one of those FUD problems, though. Even the experts can’t quite agree on how it should be implemented. Reminds me of the not-Agile-enough or not-semantic-enough debates that seem to eat up a lot of valuable time that would be better spent coding. This is why I want MVC to keep its white-gloved, mechanically precise fingers off my Javascript.

As far as I’m concerned, there is no good pattern except the one that is obvious. The one that makes you smack your head, exclaiming, “Of course!” because it is perfectly suited to your problem and its application is absolutely clear. I think of the Factory pattern as a good example. What it does and why you need it aren’t up for debate. MVC, on the other hand, is subject to interpretation once you try to apply it to environments it didn’t grow up in. Javascript is a language for manipulating CSS and HTML. Manipulating the View. There is no single, clear answer to the question of how to apply MVC to Javascript because MVC in Javascript doesn’t answer a need. Forgive me because – again – MVC has been very useful to me in the past (on the backend), but in this context MVC is nothing more than a buzzword.