Archive

Archive for the ‘Engineering’ Category

“Don’t Make Me Think” applies to your code, too

March 27th, 2008 Mark Turansky 4 comments

Don’t make me think. That’s how I feel about your code.

Or as Martin Fowler puts it:

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” -Martin Fowler, Refactoring: Improving the Design of Existing Code

You’ve reached a whole new level of mastery when you write for simplicity, elegance, and maintainability. This is done on purpose, and it’s hard to get right. Deadlines, schedules, pressure, and stress all encourage us to cut corners and adopt a “Git ‘er done!” mentality. But Abandonment of planning under pressure is one of software’s classic mistakes. It’s a cardinal sin.

How do you write simple and maintainable code? I’ve got a 3-step program for you:

Step 1: Admit that simple isn’t easy

Designing simple software is hard. It has to be done on purpose. You can’t accidentally find yourself with well-written code and an elegant solution, it has to be written that way on purpose.

This admission is a bedrock principle required for designing great software and products. If you can’t admit that simple is Hard Work™, you haven’t hit rock bottom yet by having to maintain code that would make readers of The Daily WTF blush.

Step 2: Read “Don’t Make Me Think”

Steve Krug’s excellent book “Don’t Make Me Think” is about website usability, yet it changed how I look at my code.

Why? Because Steve applied the same principles in his book to his book! And if it works in those two mediums, I thought it just might work for me, too, in my medium (code).

“Don’t Make Me Think” is very easily absorbed because he’s feeding you information in a readily accessible way. He wrote it simply on purpose, and I’m certain it took many more hours to edit than it did to write. Simple is hard.

Step 3: Practice simple everyday

There are innumerable decisions you make everyday that affect your project for better or worse. You need to recognize these as the opportunities they are. Here are a few things you can do every day:

  • Code in plain English. Use an active voice (just like writing). What do you think this method does?
  • dao.findCustomerBy(order);

    Or what about this if statement?

    if(admin.hasPermission(Permissions.VIEWFILE)){
       // allow...
    }

    or better yet…

    if(admin.hasViewFilePermission()){
       // allow...
    }

    The pretty method on the Admin class looks like this:

    public boolean hasViewFilePermission(){
       return hasPermission(Permissions.VIEWFILE);
    }

  • Make Stuff Obvious. Quick, what does this line of code do?
  • Date dt = march(28, 1973);

    When I’m reading through unit tests, I’d much rather see the above statement to create a date than the equivalent Java:

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, Calendar.MARCH);
    cal.set(Calendar.DATE, 28);
    cal.set(Calendar.YEAR, 1973);
    Date dt = cal.getTime();

    You can find those convenient date methods here: dates.java (it’s Free software). Use Java 5’s static imports to make the short date seen above.

  • Be Merciless. Be your own worst critic when reviewing your code. Always strive to improve what you’ve written. Just as great essays and novels (and books like “Don’t Make Me Think”) require several rounds of editing, so too does your code.
  • Never nest ternary statements. ’nuff said.
  • Write comments, but be brief and explain why your code does what it does, not how it does it. We already know how it does it, we’re looking at the code.
  • That’s it. Three steps to better code. Putting it into practice won’t be easy, but if you want to be a master of your craft you’ll embrace the challenge and write things simply on purpose. The people who follow you and maintain your code will appreciate it.

    Categories: Code Hints, Design, Engineering, HOW TO Tags:

    No one should work alone. Ever.

    March 25th, 2008 Mark Turansky 9 comments

    No one should work alone; not in design or planning or coding or any other aspect of software development. Why?

    Nobody gets it right the first time. Nobody.

    Moreover, different people have difference experience. I’d be foolish to think I could write something as good as someone who’s already done it. You cut down on rework issues but tapping into others’ experience. You get it closer to right the first time by having others help think through the issues surrounding a design, and often by watching over your shoulder as you write code. Even then, no one gets it exactly right the first time, but you won’t be nearly as far off as you would be by yourself.

    Xtreme Programming advocates pair programming on all production code. Not all code needs to be written by a pair, in my opinion; most is just fine for a single programmer, but that programmer should never be coding in isolation. Everyone on my team is involved with 100% of the project. We all know everything that is going on and we can jump in at any spot. Any non-trivial code is discussed by the entire team so that we can understand the best path to take. Not only does this help find flaws earlier in the process, it also gives all team members a keen understanding of the entire project.

    Two separate incidences came up today that drove the point home for me.

    First, a co-worker and I were profiling a piece of slow production code. We found a bottleneck and discussed a solution. His original fix would have worked, but it wasn’t as elegant as another piece of code I was able to point to that faced a similar problem and had an elegant solution. We only came to the right solution because we were working together on the same problem.

    Later, another teammate discussed a Spring classloading issue with me (It was a tricky issue surrounding the generation of classes in Hibernate in Spring and having more than one instance of this in the same classloader). He and another coder came up with a solution that would have worked around their problem, but I was able to talk about an experience I had nearly two years ago where I was asked to find and fix a disastrous memory leak in our production servers. Both issues involved class generation in Spring and Hibernate, and I was able to set them on a new path. They are going to tease apart the distinct pieces of software from the monolithic whole and deploy them as separate components on our message bus. All our components are deployed in isolated classloaders, which will solve their problem.

    The older issue involved the constant instantiation/initialization of a Spring ApplicationContext, where each instance caused the generation of Spring proxy classes and Hibernate DOAs. Classes once loaded are never unloaded from a JVM. This was our memory leak. The issue manifested itself at login, and our QA department did not login thousands of times a day like our users do. Code complete doesn’t mean you’re done. You’ve got abuse your system to find bugs like this.

    I can’t begin to count the number of times I’ve asked for help with the design of a tricky piece of code only to find I was going about it entirely the wrong way. Oftentimes, people with a fresh pair of eyes will see things differently than you do. This does, of course, require egoless programming and smart teammates. If don’t have either, well, you’re project has bigger problems than we can solve here.

    Doesn’t all this review and pair programming and constant communication decrease productivity? I’d argue no. In fact, as an investment of time, it’s paying rich dividends in decreased maintenance costs, robust production deployments, and higher morale during a time when other projects are struggling to pay off their design debt. We’re swimming when most others are just trying to tread water.

    I’ve done the solo thing. I’ve also lead or been part of smart teams with tight communication. Pair programming is always the natural result of open communication and egoless programming as the team works together.

    I know which one I prefer. How about you?

    Categories: Engineering Tags:

    Scalability & High Availability with Terracotta Server

    March 7th, 2008 Mark Turansky 4 comments

    Our message bus will be deployed to production this month. We’re currently sailing through QA. Whatever bugs we’ve found have been in the business logic of the messages themselves (and assorted processing classes). Our infrastructure — the message bus backed by Terracotta — is strong.

    SCALABILITY

    People are asking questions about scalability. Quite frankly, I’m not worried about it.

    Scalability is a function of architecture. If you get it right, you can scale easily with new hardware. We got it right. I can say that with confidence because we’ve load tested the hell out of it. We put 1.3 million real world messages through our bus in a weekend. That may or may not be high throughput for you and your business, but I guarantee you it is for our’s.

    The messages we put through our bus take a fair amount of processing power. That means they take more time to produce their result than they do to route through our bus. How does that affect our server load? Terracotta sat idle most of the time. The box hosting TC is the beefiest one in our cluster. Two dual-core hyperthreaded procs, which look like 8 CPUs in htop. We figured we would need the most powerful server to host the brains of the bus. Turns out we were wrong, so we put some message consumers on the TC box, widening our cluster for greater throughput. Now the box is hard at work, but only because we put four message consumers on it.

    When we slam our bus with simple messages (e.g, messages that add 1+1), we see TC hard at work. The CPUs light up and the bus is running as fast as it can. 1+1 doesn’t carry much overhead. It’s the perfect test to stress the interlocking components of our bus. You can’t get any faster than 1+1 messages. But when we switched to real world messages, our consumers took all the time, their CPUs hit the ceiling, and our bus was largely idle. The whole bus, not just TC. We’ve got consumers that perform logging and callbacks and other sundry functions. All of these are mostly idle when our message consumers process real world workloads.

    We’ve got our test farm on 4 physical nodes, each running between 4 and 8 Java processes (our various consumers) for a total of 24 separate JVMs. All of these JVMs are consumers of queues, half of them are consumers of our main request queue that performs all the real work. The other half are web service endpoints, batch processors, loggers, callback consumers, etc. and each are redundant on different phsyical nodes. Because our message processing carries greater overhead than bussing, I know we can add dozens more consumers for greater throughput without unduly taxing Terracotta. If we hit a ceiling, we can very easily create another cluster and load balance between them. That’s how Google scales. They’ve got thousands of clusters in a data center. This is perfectly acceptable for our requirements. It may or may not be suitable for your’s.

    You might be thinking that dozens of nodes isn’t a massive cluster, but our database would beg to differ. Once we launch our messaging system and start processing with it, we’ll begin to adversely impact our database. Scaling out that tier (more cheaply than buying new RAC nodes) is coming next. I hope we can scale our database as cheaply and easily as our message bus. That’ll enable us to grow our bus to hundreds of processors.

    Like I said, I’m not worried about scaling our bus.

    HIGH AVAILABILITY

    I might not be worried about scalability, but I am worried about high availability. My company is currently migrating to two new data centers. One will be used for our production servers while the other is slated for User Acceptance Test and Disaster Recovery. That’s right, an entire data center for failover. High availability is very important for our business and any business bound by Service Level Agreements.

    Terracotta Server has an Active-Passive over Network solution for high availability. There is also a shared disk solution, but the network option fits our needs well. Our two data centers are connected by a big fat pipe, and Terracotta Server can have N number of passive servers. That means we can have a redundant server in our production data center and another one across the wire in our DR data center. We’ve also got a SAN that replicates disks between data centers. We might go with the shared disk solution if we find it performs better.

    Overall, though, it is more important for our business to get back online quickly than it is to perform at the nth degree of efficiency. Messaging, after all, doesn’t guarantee when your stuff gets run, just that it eventually runs. And if everything is asynchronous, then performance, too, is a secondary consideration to high availability.

    CONCLUSION

    If there’s one lesson to be learned through this blog article, it’s that one size does not fit all. Not all requirements are created equal. Our message bus is the right solution for our needs. Your mileage may vary. Some factors may outweigh others. For example, having a tight and tiny message bus that any developer can run in their IDE without a server (even without TC) is a great feature. No APIs lets us do that with Terracotta. You might have very different requirements than we do and find yourself with a very different solution.

    HOW TO: Better JavaScript Templates

    March 5th, 2008 Mark Turansky 4 comments

    JavaScript Templates (Jst) is a pure Javascript templating engine that runs in your browser using JSP-like syntax. If that doesn’t sound familiar, check out the live working example on this site and download the code. It’s Free Open Source Software.

    Better JavaScript Templates

    Categories: Code Hints, Engineering, HOW TO, Technology Tags:

    Horses For Courses 2 (or Tools for Fools)

    March 1st, 2008 Mark Turansky 2 comments

    My recent post “Linux is killing Solaris” is surpisingly controversial, if you could infer that by reading the comments on Reddit or watching the split vote on DZone.

    I think the critics and naysayers are missing a big point. One tool (htop on linux) is ridiculously easy to read at a glance while the other (prstat on solaris) requires parsing and mental math.

    You be the judge. Can you choose the right horse to run this course?

    Imagine you’ve got a dozen nodes on the network, each one hosting components of your enterprise message bus. You and your operations folks need visibility into the entire system so that you can tell at a glance whether something is going wrong or not.

    One tool is plain text, with row on row of process data, cpu utilization by process, etc. Want to know total CPU usage of the box? Add your processes together! “Well, process A is using 38%, process B is using 13%, and process C is using 4%. Let’s see, 38 + 13 + 4 is 55%. On to the next box!” Twelve console windows into all twelve nodes looking like this:

    htop_vs_prstat21.png

    Can you tell how much swap space your system is using by looking at this first tool? Nope!

    Alternatively, you can look at another tool that’s also plain text in a console, but has simple yet effective color-coded bars that display CPU and memory usage. It looks something like this:

    htop_vs_prstat1.png

    What’s important here is people. I don’t care if prstat runs twice as fast as htop. I don’t care if htop uses more memory or is less efficient. The fact is, they both run fast enough. What I want is for people to be fast when reading the console.

    Our Config Management team is going to have a single monitor with SSH shells open to all the nodes on the network. The monitor will sit in our Ops center and plenty of people will glance at it to see how our system is doing. If even one of them is doing math in their head to get CPU usage on a box, then I’ve failed the usability test. I picked the wrong horse for the course.

    So, htop runs on Linux and there’s no mention anywhere on the internet about it being unavailable for Solaris (except here on this blog). Get me used to all the niceties of Linux and I’m not a happy camper when I have to deploy my message bus to Solaris because my quick visual status bars are gone.

    This might seem like a trivial thing to get worked up about, but my responsibility as a leading architect at my company is to make things which are simple to run, easy to test, quick to report status, and to remain cognizant of the Ops and business folks that use our system to make money for our company. There’s still a ton of work to do after you’re code complete. Monitoring is one of those non-functional but critical requirements that has to be built in if you want a robust system.

    Solaris on x86 was too late. I could never afford Sun hardware at home or for development. So it all went Linux. And it’s not just for me, it’s for a lot of people. That’s why I wrote Linux is killing Solaris. I still think it’s an obvious point missed by no one, yet somehow it managed to stir up enough emotion in people on Reddit and Dzone.

    Categories: Engineering Tags:

    Linux is killing Solaris

    February 28th, 2008 Mark Turansky 44 comments

    This just in from the “duh, obvious” department… Linux is killing Solaris.

    Search Google for “htop on Solaris.” You’ll probably find the very page you’re reading right now. There were plenty of hits for solaris, top, and htop, but none for solaris and htop together. (Editor’s note: not 5 minutes after publishing this article, Google has this very page as the first hit for ‘htop on solaris.’ See comments.)

    We got used to htop’s color-coded bars in a console for our messaging system, and then we deployed to a datacenter on Sun hardware without htop. prstat just isn’t quite the same.

    What’s htop? htop is a little command-line tool for Linux that’s similar to top but shows CPU and Memory usage visually in simple text format. It’s not flashy or whiz-bang. It’s a simple yet effective way of seeing what’s going on inside your OS at a quick glance.

    So, what does this have to do with killing Solaris? We couldn’t find even a single person interested in running htop on Solaris (besides us). Other programs (like pound) have either been ported to Solaris or at least talked about somewhere else on the internet. We couldn’t even find a discussion about htop on Solaris. There’s just no interest.

    I admit this is a specious argument at best, the thinnest of strawmen. But more subtly, an entire generation of Linux geeks are getting used to GNU tools that are similar but not quite like their non-GNU Unix counterparts. For example, I’m frustrated that I can’t simply type “tail -n 200 <file>” on Solaris. The -n argument is not the same. Add up enough of these little differences and I find myself wanting to work in a Linux environment where I’m more familiar. Linux captured the low-end of the market, revitalizing the old PCs people had lying around the house. The next generation is cutting their teeth on GNU/Linux, not Solaris. Sorry, BSD.

    But like I said, this is from the “duh, obvious” department. It’s not particularly insightful. I’m merely a consumer reflecting on my choice of server OS. But if I’ve learned one thing in life, it’s that we’re not as unique as we think we are. There are probably other people thinking/feeling/experiencing the same thing you are. You might be part of a larger trend.

    Happily, we’re only temporarily deploying to Solaris. Our company is in the middle of a move to a larger data center with a lot more capacity. We’ll have shiny, new blade servers to deploy to. They’ll be running Linux, naturally.

    Categories: Engineering Tags:

    Some wheels need reinventing

    February 21st, 2008 Mark Turansky 10 comments

    Reinventing a square wheel is a common anti-pattern. The idea is a) we don’t need to reinvent the wheel because b) we’re likely to recreate it poorly compared to what is already available. But if we never reinvent any wheels, then we never progress beyond what we have. The real question, then, is when does it make sense to recreate a wheel? Some wheels need to be recreated.

    I recently reinvented a wheel. A big one. The wheel is “Enterprise Messaging,” which much be complex because it has “enterprise” right in the name! I’d be a fool to reinvent that wheel, right? Maybe. Maybe not. We fit our “enterprise messaging system” into 92kb:

    enterprise_messaging_in_92kb.jpg

    Some won’t consider 92kb to be “enterprisey” enough, but that’s ok with me. I know we were able to put 1.3 million real-world messages through our bus over a weekend. That’s enterprisey.

    Jonas Bonér wrote an article about building a POJO datagrid using Terracotta Server, and I replied on his blog saying we did something similar by using Terracotta Server as a message bus. Another reader asked why I did this instead of using JMS.

    I think there are several benefits to this reinvented wheel:

    TINY!

    92kb contains the entire server framework. We have another jar containing common interfaces we share with client applications that weighs in at 18kb.

    It works!

    A single “consumer” in our framework is bootstrapped into an isolated classloader, which enables our framework to load applications (the various apps we need to integrate) into their own isolated classloaders. One consumer can process a message for any integrated application.

    This is utility computing without expensive VMWare license fees.

    We’re consolidating servers instead of giving each application dedicated hardware. The servers were mostly idle, anyway, which is why enterprises are looking to utility computing and virtualization to make more efficient use those spare CPU cycles. In our framework, hardware becomes generic processing power without the need for virtualizing servers. Scaling out the server farm benefits all applications equally, whereas the prior deployments required separate capital expenditures for each new server.

    Pure POJO

    Our framework runs inside an IDE without any server infrastructure at all. No ActiveMQ, no MySQL, and no Terracotta Server. Developers can stand up their own message bus in their IDE, post messages to it, and debug their message code right in the framework itself.

    We introduce Terracotta Server as a configuration detail in a test environment. Configuration Management handles this part, leaving developers to focus on the business logic.

    So, I might not be writing my own servlet container anytime soon (not when Tomcat and Jetty are open source and high quality), but I think it made a lot of sense to reinvent the “enterprise messaging” wheel. Terracotta Server allows me, in effect, to treat my network as one big JVM. My simple POJO model went wide as a configuration detail. That makes my bus (and TC) remarkably transparent.

    Beware the non-namespaced classpath resource

    February 16th, 2008 Mark Turansky 2 comments

    We spent too long hunting down a bug in a database method call that consistently returned “null” in our integration environment, but returned the correct value in a development unit test.

    Do you see the problem here? Compare these two screenshots. Both screenshots show a look into two different jars on our classpath. The title of this article is a big hint.

    jar_two.JPG jar_one.JPG

    Two points goes to the first person to explain the problem. (-2 points for any of my teammates that answer first!)

    The moral of the story is that namespaces are one heck of a good idea and that we should always be very careful when relying on classpath-based resources.  I’ll write more about the problem after giving others a chance to solve the puzzle.

    Categories: Engineering Tags:

    Code complete doesn’t mean you’re done

    February 13th, 2008 Mark Turansky No comments

    Joe Coder runs through his feature in the UI. It works. The doodad renders beautifully on the screen, and when he clicks the button, all the right things happen on the server. He checks his code in, writes a quick comment in Jira, changes the issue status to “Completed & Checked-in”, and goes to his next task. Lo and behold, his To Do list is empty! Joe’s done coding!

    Or is he?

    Configuration Management cuts a branch off the trunk code. Joe’s code goes through QA.

    Some QA departments try to break developers’ code, others just test the “go path” to insure their test scripts work. In Joe’s case, the QA department has a test script that is a step-by-step use case for how the feature should work. QA signs off on his feature. The doodad worked exactly as specified, which is to say, the select/combo box was correctly filled with test data from the database.

    Joe’s code goes to production … and takes down an entire server.

    How can this be? It went through QA! Testers verified that his code did what it was supposed to do!

    Most software organizations use the term robust wrongly. I generally hear it used in a context that implies the software has more features. Robustness has nothing to do with features or capabilities! Software products are robust because they are healthy, strong, and don’t fall over when the table that populates a select/combo box has a million rows in it.

    Joe Coder never tested his feature with a large result set. Michael Nygard — in his excellent book Release It! from the Pragmatic Press — calls this problem an unbounded result set. It’s a common problem and an easy trap to fall into.

    Writing code for a small result set enables rapid feedback for a developer. This is important, because the developer’s first task is to write his program correctly. It seems, though, that this first step is oftentimes the only step in the process! Without testing the program against a large result set, the new feature is a performance problem waiting to happen. The most common consequences are memory errors (have you ever tried filling a combo/select box with a million rows from the database?) or unscalable algorithms (see Schlemiel the Painter’s Algorithm).

    In our case, testing with big numbers revealed concurrency issues that we did not and could not find when developing with simple, smaller tests. Our multi-threaded, multi-node messaging system would routinely deadlock whenever we slammed it with lots and lots of messages. It didn’t do this when we posted simple messages to the endpoint during development. Similarly, we noticed that we held on to objects for too long during big batch runs. They all got garbage collected when the batch completed, so it wasn’t exactly a memory leak, but there was no need to hold on to the references. After we fixed that, we noticed that our servers would stay within a tight and predictable memory band, as opposed to GC’ing all at once at the end of a batch. Terracotta server expertly pages large heaps to disk, so we were never at risk of running out of memory. Still, it’s nice to see our JVMs running lean and mean.

    We’re still stress testing our system today. This past weekend, we pumped over one million real-world messages through our message bus. Our concurrency issues are gone, memory usage is predictable, and we stopped our test only to let our QA department have at our servers. There are zero technical reasons why our test couldn’t have processed another million messages. Terracotta Server held up strong throughout.

    But we’re still not done testing yet. We still have to see what happens if we pull the plug (literally) on our message bus. We still have to throw poorly written messages/jobs at our bus to see how they’re handled. We need to validate that we’ve got enough business visibility into our messaging system so that operations folks have enough info at runtime to do their jobs. We need canaries in the coal mine to inform us when things are going wrong, and for that we need better metrics and reporting built into our system that shows performance over time.

    We’re code complete, but we’re not done yet.

    Categories: Engineering, Terracotta Tags:

    Dead Programs Tell No Tales (or “We don’t need no stinkin’ error handling!”)

    February 5th, 2008 Mark Turansky 5 comments

    Imagine two pieces of software. One has “robust error handling” while the other prints a stacktrace and dies. Which one do you prefer?

    I like the one that dies. Loudly. Depending on the type of application you’re building, the dead program might serve you better, too. Why? Because it’s obvious when something goes horrifically wrong. The message won’t be buried in a snowcrash of logging output.

    What is “robust error handling” anyway? My team is currently building a sophisticated message bus and we’ve run into a few subtle concurrency issues. These are the hardest things to find when writing a distributed application with many threads on different physical nodes. Our error handling consisted of trapping the exception, logging it to Log4J at ERROR level, setting the correct state on our class (or so we thought), and going back to what the code was doing. It seemed like a good first pass, except that it didn’t work. We didn’t or couldn’t predicate every possible state in our system, so we made our best guesses, but naturally some corner cases bit us with an unexpected deadlock. Everything stopped and we didn’t know why.

    Our logs, naturally, were huge with debugging turned on. Application logging is largely useless, anyway, without a plan to use it. And without a debug statement prefixing every line of code, you’re going to have a hard time finding deadlock situations across JVMs on the network.

    So how’d we find our gremlin? We killed the process. Our “robust error handling” now looks like this:

    try {
         // attempt the work
    } catch(Exception e){
         e.printStackTrace();
         System.exit(-1);
    }

    Once we made that change and deployed our software to all the nodes, we found our deadlock.

    Our problem was an unsychronized getter (you think gets are reads and therefore thread safe? Ha!). It turns out that somewhere in the callstack, this getter called toArray() on an ArrayList, which internally uses an iterator to build the array. If you’ve done any multi-threaded programming, you probably know what happens when another thread tries to modify your collection/list concurrently while using an iterator.

    Our problem arose in a parent message (those that divide work among many child messages for parallel execution) which would leave orphaned children in certain error scenarios. We didn’t discover this cornercase in the logs, but we found it quickly when we crashed the program and exited.

    I understand that exiting a running program isn’t the correct solution for all problems, but it was for our’s and it was dramatically more revealing than looking through tons of debug gibberish in log files. So, if you have the kind of program that can safely exit, then I say…

    Fail loudly and proudly.

    Categories: Engineering Tags:

    Switch to our mobile site