codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

Say No to Null Checks

| Comments

Hey, do you check your methods’ arguments to make sure they’re not null?

Today, I got into a little discussion with a teammate about testing contracts of methods: should we check for null in every public method?

I was against it, and he was for it.

The simple reasons to do it are, first, that it makes your code more defensive. You fail explicitly instead of failing implicitly when the code tries to dereference the null object. Another argument was that given 20 callers of an interface, it’s easier to test in the interface for the precondition than to test each and every one of the callers. And, of course, that it is better API implementation, and that even if a class isn’t part of one’s public API now it might very well become part of it in the future, so why not add the tests now?

I’ll tackle these all. First, I have to agree that some null checks are required, at the boundaries of your system. I believe a system should have a paranoid barrier, before it everything is as suspect as someone going on a bus with a heavy coat on a hot day – that’s just waiting to blow. Once you’ve passed the barrier you know things are secure and no longer need to be paranoid.

So yes, some null checks are of course required.

But, because we want our API to be user-friendly and error-proof does that mean we need to make every public method in our code paranoid just in case it will become part of the public API at some point? 5 letters: YAGNI! :)

The interesting part is the testing of the callers. I agree, if we have to write the test 20 times for each caller, it will get tedious. But we don’t write the same thing twice, do we? As good old J.B Rainsberger teaches, what we actually need are collaboration tests. Each of the callers collaborate with the interface. And so, we create a collaboration test that makes sure the user is using the interface according to the contract. These are usually abstract tests that require us to create derivatives that implement a factory method for creating the calling class. This way we write the tests only once and make explicit the interface and contract, even in dynamic language.

In general, this is a powerful solution, that solves a basic problem with defensive programming. Say we do test for nullity wherever possible, what do we do then? Our system is likely to crash or throw an exception any way, since what is the interface to do? Obviously something is wrong if we were called in a way that doesn’t match the contract, so is the hassle worth it? I think testing for nullity everywhere is a thing of the past, especially once you adopt dynamic programming and get used to the fact that most of the times you can’t even be sure the object you’ve got will answer the methods you’re about to use, so what difference does a null check make?

So let’s write some awesome collaboration tests tests and get cracking!

You should subscribe to my feed and follow me on twitter!

Letting DRY Drive

| Comments

The reason I stress DRY so much is because it is one of the simplest yet most effective pieces of knowledge we have gained for software development. When I first read about DRY (in The Pragmatic Programmer) I got it’s amazing strength in saving extra maintenance by making sure that changes will be localized as much as possible in the future. And I’ve used it as such for a couple years.

Only after I started practicing TDD did I realize how significantly DRY can drive coding. Whenever I test drive code, the third step of the cycle, Refactor, is usually a lot about removing duplication. And the amazing part is that this alone drives a useful implementation. In the awesome book TDD By Example, Beck describes a method of implementing called Triangulation. It’s for those rare occassions where you really have no real clue what way is best to solve the problem – the ground that allows TDD to flourish. In this method, you start by getting a couple of tests to pass with dumb implementations and then refactor to generalize the code and make it DRY. The mere act of DRYing your code can simply through a solution at you. I’m still amazed when this happens to me, both because of the sheer beauty of the process, and because it means I’m doing something right.

About 5 years ago, when first heard about the concept of TDD, I wrote a greenfield project for about 5 months in what I believed was TDD. Only more than a year later did I realize that I wasn’t doing TDD at all, but TFD (Test First Development). I did in fact write all my tests before I wrote production code, but I didn’t let the tests drive the development. Now although that is better than not testing at all or TAD, it just wasn’t it, and I didn’t get why.

Whenever I wrote a test, I already knew how the implementation was going to look, be it simple or complex. Sometimes I might have alreayd decided that I was going to add a decorator there, and then wrote the test that forced me to implement a decorator. This, of course, is wrong. When I learned to let go and stop micro-managing my code, things took off at a better direction.

I write a simple test that explicitly uses the code as I would like to use it had someone else already imlpemented it. This is crucial, as it makes sure that I am not allowing myself to sustain a lousy interface simply because it’s the easier one to implement. The harder part is to always disconnect yourself from prejudice – what you might think the code should become. Currently this is a deliberate effort for me, to make sure I’m not thinking a few steps further and adding what I think I’ll need then too early. Even adding code I believe I’ll just have to add anyway in about 2 tests is wrong.

After making the test pass by the simplest way I could come up with I start DRYing the code up. I actually do more stuff, such as improving naming etc. but generally, DRY is the main force behind the changes in this phase for me. I listen to the code and try to make it. This is where knowing your refactorings well pays off. I might extract a method only to inline it 20 seconds later and extract a different part of it. I move things around a bit and see what feels right. Because I’ve already got the tests, there’s no reason not to use them right away to see just how far I can stretch the code to my ideal vision.

For me the magic is when I notice, after 30 minutes of doing this, that I’ve suddenly got a solution without realizing it. Suddenly the code falls into place. A lot of the times it turns out simpler than what I thought I’d turn out with.

Jumping from basic DRY to full blown TDD isn’t easy or straight forward, but let DRY drive you design for a while and see it grow on you. I’ve yet to meet someone that’s given it a shot and disagreed this a whole new way to programming.

You should subscribe to my feed and follow me on twitter

Refactoring to Heaven

| Comments

My last blog was about how many people refer to refactoring as the wrong thing. For completeness of discussion I’d like to talk about what a lot of people seemed to not get in my previous post. I said that the ‘Big Refactoring’ is the new ‘Big Redesign in the Sky’, and got a bunch of questions along the linse of “so we’re never supposed to redesign?”

Well, of course that’s not the case. Even the best programmers occasionally dig themselves into a hole that will require some effort to get out of. The point is that the best thing to do is never to take those 2 days to 2 weeks period just for doing that refactoring. That is never the right approach to solve such a problem.

First of all, I’ve seen many times that it was intended to spend “only” 2 days (which is already a huge amount of time) to do some refactoring, but 2 days in, the dev team found it they actually need 2 more days because of extra complications they’ve got, and the team’s lucky if after a week of hard work they still have a working system, not to mention better.

Another problem with that is, once the devs think they have a picture in mind of this perfect redesign that management won’t let them take a week to get to (with good reason!), a lot developers stop thinking about how to make the current code better. It’s just let’s add this hack here, because management won’t let us do this the right way. That’s BS. Will you come to your dentist 3 days in a row for ‘general groundwork’ before have a 2 hour filling? I thought so.

Programming is about adding value. Don’t get me wrong, I like writing elegant and clean code as much as the next guy (actually, probably a bit more given I walk around with one of these). But, what we’re hired to do is solve problems and help someone’s life by doing it. If all we do is bitch about how the design could be better, we’re only benefiting ourselves, and not doing a good job at it.

So what is the right way? Well, the right way is to pull things off towards the right direction, in steady and controlled baby steps. I’ve seen this work, and I’ve heard from much better programmers than myself that they’ve got it working multiple times. After spending a day in an awesome Responsive Design workshop by Kent Beck, I was a bit amazed to hear there are so many ways of pushing design towards a better place in baby steps. Up until that point I would have done it anyway, but Kent taught me there’s actually an art to it.

Do you think it’s impossible in your case because “X is too big”? Well, say you’ve got N steps in your redesign, all are safe atomic changes. Many of the times you might think the order of steps you’ve came up with simply won’t do and it will be too hard to do it without the big blunder. But, think about it this way: Those N steps have N! (N-factorial) different ways to be ordered. What are the odds that none of those ways will solve your problem? I’ve yet to see when this is not the case (and this, among others, is why you should spend the time with better and more experienced coders, such as Kent).

Yes, it means that “2 day refactoring” of yours will probably be spread over 2 weeks (which is just might have done anyway). But it also means that no matter what happens during those 2 weeks, you’re always on the safe side. Find out after 2 days that your idea simply won’t cut it? Well, no biggie. The code still works, and you added features those 2 days. Find out it’ll take longer? Yeah, so what. We’re doing a few small steps a day anyway. The awesome thing is that you’ve got time to learn during the work what you may have thought up wrong and use that as input for the next parts of the refactoring. No rush here. And I think the most important point is that if you simply spend 30 minutes a day to refactor things at the right direction, weaved into your daily work and refactorings, you’ll get it done without have to pitch your Big Redesign to management.

This allows you to simply do what you’re supposed to do: add value to customers daily, while making sure the system stays responsive to future changes. And that, my friends, is how the big refactoring should be done.

You should subscribe to my feed and follow me on twitter

Refactoring: You’re Doing it Wrong

| Comments

I’ve been writing quite a bit about DRY lately, but I think it’s time to take a few steps back and talk about something even more fundamental, refactoring. Today, refactoring as a concept is pretty common. I think it’s even passed the buzzword stage. It’s still not too known in academia (I’ve yet to hear the term mentioned in my studies), but given that most IDEs come with refactoring support or have supplementary tools for it, people are familiar with the term.

It has been written a lot about that the term refactoring is being heavily misused lately. Have you ever said “we need to do a big refactoring here?” If so, you’ve done the term wrong. The Big Refactoring is the new Big Redesign in the Sky. Have you ever told your boss you need time to refactor something? You’re doing it wrong. Wrote Refactoring as a task on the board? Wrong once more.

Refactoring should be engrained in our constant flow of work. I mean it should be assimilated into the way you think of basic coding. Stop thinking of code changes as a stream of characters. To be an efficient coder you need to think of code at a higher level. The level of refactorings should be the level we think of code.

I really believe that generally typing is not the bottleneck. In spite of that, I believe that being able to perform refactorings quickly, efficiently and seamlessly as part of your flow is a major differentiator in one’s ability to quickly check ideas and be able to push design forward. I’ve deliberately spent time to put all refactorings of IDEs I use into my muscle memory. Extracting a method is not some heavy mind process, it’s just a swift movement I do with my fingers.

An interesting example of how refactorings should be used I’ve heard from Kent Beck is his way to perform changes cohesively. Say you’re editing a method 10 lines long and need to perform a change on 2 lines in the middle of it. Most people might simply make the change, but Kent (at least some of the time) will extract those lines to a new method and make the change in that new method. If the new method feels right after the change he’ll just leave it there. If not, he’ll inline it. If you’re thinking that’s a lot of hassle, you’re missing all the fun here. This whole process has an overhead of 1 second on most IDEs, given you don’t have a hard time coming up with a name for the method.

Doing refactorings the right way means you do dozens of refactorings on each coding session. This means you get the ability to tailor your code in much bigger chunks – methods, members, classes, interfaces. After all, we usually don’t think about the need to move those parenthesis – we think about intent. Refactoring is all about intent!

Do yourself a favor and note your use of refactoring for a week. Learn all the hot keys your IDE has and make it a point to use them whenever possible. Whether you’re doing Java, C#, Python or Ruby, there’s no excuse not to use these basic building blocks for your every day use. Our stream of changes should be made of a lot of small, constant refactorings, pushing our design to a better place one small step at a time. Getting so familiar with this technique means you will no longer need to ask your boss for refactoring time. You won’t need those big refactorings. You’ll stop thinking about refactorings so much, they’ll simply happen.

Refactoring’s no longer a buzzword, but it’s time for us to learn how to use it properly. Refactor constantly and get your groove on.

You should subscribe to my feed and follow me on twitter!

DRY: Don’t Get Trigger Happy

| Comments

Once you’ve started to assimilate DRY into your regular routine, it usually becomes addictive. The feedback loop constructed of removing moving parts, making stuff clearer and reducing chances of error simply gets you into a certain rhythm that’s hard to get enough of.

The problem is, that as with any skill, you have to learn to master even the corner cases and not just blindly follow a mantra. Following a mantra is good enough for starting everything, but there comes a time you have to experience and understand for yourself when using a rule of thumb is a good idea and when it isn’t. So, let’s now talk about the ‘Ha’ part of the ShuHaRi cycle in DRY.

We know that duplicate code is a code smell and a DRY violation that needs to be removed. But, as with any rule, it has exceptions. Taking the dumb example, look at this piece of code:

In the snippet above you can see the value ‘0’ referenced twice. Is that a DRY violation? I’m sure you’ll agree it isn’t. After all, even though it is the same value that appears multiple times syntacticly, it has a different meaning semantically. The first zero is an initialization value and the other seems to indicate bad values in the array. The fact that they both are zero is meaningless and a coincidence. It might very well be that the next version will mark bad values as ‘null’, which surely shouldn’t change the way the array index is initialized. OK, so that was an easy one. Let’s look at this next snippet, taking from some code whipped up solve the Game of Life:

In that example, 2 appears twice also. Is that a DRY violation? After being in a code retreat, and hearing from other code retreaters, I understand that many people that try and focus on DRY think that is in fact a DRY violation. After all, both occurrences refer to the number of living neighbours a cell has and the number is part of the rules of the problem domain. But, let’s give this a bit more thought. Although both instances of 2 reference a rule of the game, they reference different rules of the game. Semantically, they are different. If we decide to change the minimal number of neighbours for a cell to stay alive it does not mean we will want to change the number of neighbours it takes to bring a cell to life.

I hope you’re catching my train of thought here. Now let’s look at another example. This is a snippet of code one might get to while doing the famous Bowling Kata:

This snippet adds the current frame’s score to the total score of the bowling game, taking into account whether the frame has a strike, a spare, or is a ‘simple’ frame. Now, you might notice there is some “duplication” here. I can tell you that when I started refactoring this code to make it look better, I had to think a bit whether the calculation of the score in the first branch and the second branch should be extracted to be the same method. But again, this is a mere textual duplication, and not a violation of real DRY, which is duplication of intent. The first one takes the score of the strike frame itself and adds the strike bonus (2 next rolls), the other takes the score of the spare frame and adds the spare bonus (1 next roll), so even though it takes the same additions, it is not the same logic. The better way is of course this:

This is a tricky one, and if you noticed it before reading give yourself a pat on the back! If you start and refactor this with an IDE, most IDEs will actually make a bit of a mess for you here, because they usually try and replace same occurrences of code once you extract a method, but here that would not be the better choice. Always keep an eye on your refactoring tools, because they, unlike you, can’t tell the difference between syntactic duplication and semantic duplication!

The big money of DRY comes when you learn to tell the difference between duplication of intent and mere duplication of text. This simple rule for judging your code helps you understand your code better, simply by making you actively consider what your real intention is.

I’ve written more about DRY here and here if you’d like to hear more.

You should subscribe to my feed and follow me on twitter!

Taking DRY Further

| Comments

After learning to spot basic DRY violations, such as code you’ve just copied from somewhere, it’s time to learn how to use DRY to drive a lot more in your system.

DRY can be used extensively in your code base to alert you of problems waiting to happen. For example, similar code structures in different parts of the code are usually a DRY violation. This violation causes coupling which in turn will make it harder to change the code. The good scenario is that you have to tediously go through all the repetitions and change them to accommodate the change. The worse case is you forget to change one and introduce inconsistency in your code.

Train yourself to note these feelings of “yeah, I’ll have to do that again here”. Lucky for me, whenever I do something too many times I automatically start referring to it as “the dance”. So, once I hear myself saying to a teammate that “I’m doing the add-view-dance” I know it’s time to do something about it.

But DRY need not apply only to your code. Actually, it certainly shouldn’t! Copying is bad, even if you do it in a configuration file, or “just in that script”. It’s our tendency to disregard these “minor” parts of our system as not worthy of our attention, but these are places that are at least as likely to cause problems as our code. Taking the time to make the deployment scripts tidier will pay off once you decide to leave that server at home and deploy your app on EC2.

DRY used correctly will make driving changes in your app a breeze, be it a configuration change, a DB change or a real feature you need to add. The saved cycles of work saved by not having to dig around the code and look for other places your forgot to update, or hunt the bugs caused after making a change pay off immensely for the time spent on making things the good way.

Let’s take this one step further. Do you document your app? For example, do you supply wiki pages with explanations for installing the system, executing it or making configuration changes? There isn’t a coder out there that hasn’t been bitten by an outdated guide that was updated to reflect the way things should be done now. This is a subtle DRY violation – the is repetition between the description of the process in the wiki and the real process, as is usually saved in people’s heads or scripts. If you’ve got a script, why not simply use it as documentation?

Most people will probably understand your shell script better, and it is sure to be up-to-date. I tend to document the script itself to make it clearer (and generally treat it as part of the code base) which pays off when I don’t have to hear people get angry with me for not updating the wiki.

The even more important example is sample code. Almost every app will, at some point, require you to supply sample code for working with it. The knee-jerk solution is to hack some code and put it on a wiki page. You might even go the extra mile and run the code to make sure it works. 24 hours later, you change the code and the samples are now obsolete. Again, duplication between real code and sample code has created a problem for us. The solution, once more, is to fight this duplication. Putting the samples as part of the app’s version control, which will make sure they compile and run with every change, and pointing the wiki to these files (or even embedding them in the wiki) will save you a great hassle. Sometimes you can even make these examples part of the code, such as Python’s Doctests, which allows you to put executable usage examples right next to the code.

Once more, training your senses to notice these violations and finding creative solutions for them takes practice and time, but gets a lot easier once you get the trick. This is a crucial tool in the pragmatic programmer’s belt.

DRY, actually, is a measure of technical debt. The more violations you allow to slip in the codebase, the harder you’ll have to work later to change the code. A DRY codebase is usually more cohesive and loosely coupled which leads to a more responsive design. Effort you put into keeping your code DRY pays off, quickly and by manyfold.

You should subscribe to my feed and follow me on twitter.

Short Intro to DRY

| Comments

If you’re just starting to learn programming you might be feeling the need for a few solid guidelines for producing better code right now. Joining an industry with so many Best Practices, Rules of Thumb and The Right Things is not easy and certainly not too welcoming for newbies.

One of the best programming mantras that everyone can understand and use for better code right away is DRY – Don’t Repeat Yourself. DRY is about removing duplication from the code base at pretty much every level, and this, I believe, is one of the pillars of good software engineering.

Academia rarely talks about DRY with enough stress. I’ve heard something like it only twice. Once, when I was told to use constants instead of magic numbers. This is maybe the simplest way to get started with DRY – replace magic numbers that you use several times in your code with a constant. All of a sudden the numbers got a real meaning but the more important thing is that changing the value becomes a no-brainer. Want to send more bytes with every packet? Just update the constant! That’s real value right there, instead of having to start searching files for the current number, and distinguishing between the times 512 is the packet size and when it’s just the maximal file size.

Another reference to DRY in Academia is “Reuse”. Reuse is the holy grail of software engineering. I know that after taking a few courses it seemed that Reuse is that peace of mind only OOP Gurus can get to by writing speckless code with good design. Although in academic courses you’re not likely to see real reuse and examples of code that reaches this goal in a good way, this is still a DRY manifestation that’s easy for a lot of people to grasp. What’s a better way to refrain from repeating myself than to not write new code at all and use that GenericAwesomeThing class I created before?

But, as with many things, those 2 well-rehearsed topics are only the tip of the DRY iceberg. Once you get it into your head that DRY is one of the easiest and most effective ways to get better and cleaner code, you’ll start seeing its violations left and right.

The easiest way to spot DRY violations is by looking at your typing. Pretty much any time you catch yourself using copy and paste, you know you’re doing it wrong. The mear act of copying some code around means, literally, you’re repeating the same thing somewhere else. Spotting those is usually a happy occasion, an opportunity to learn. This usually means you’re code is missing some basic abstraction to make that idea you’re trying to replicate a concrete concept of your system.

For example, whenever I copy a few lines from a method I know I probably need to extract a method. There are so many advantages to simply sticking to this as a golden rule that Uncle Bob is calling this “Extract till you Drop”. Practice DRY enough and “Extract Method” will become a regular coding step. It is no longer a “refactoring”. It is no longer a “task”. For me, it’s as simple as adding a variable, or writing a loop. It’s a tool, the simplest we’ve got.

But until you get familiar enough with extracting methods, you should be aware of these acts of copying stuff around and fight them with wrath. If extracting methods scares you, I’d start with even simpler stuff. Are you using the same string a couple of times, e.g. “Error: ” is all over your code? Keep it DRY! Some simple computation appears a few times? Keep it DRY!

To start the ball rolling in the craftsmanship direction and adhering to what people that are wiser than you and I, keeping things DRY is a pretty simple, sure-fire way to do things better. Keep your watch for patterns that look all too similar. Imagine your keyboard has a DRY key that simply removes the duplication, be it by extracting a method, a constant or a class.

Try sticking a DRY post it to your monitor and do your best for a week. You will likely gain a whole new perspective of your code and learn to notice minute details you used to disregard. The magic is that once you start following DRY, you will also notice that the amount of places you need to go through to make changes is decreasing. There’s nothing better than finding that change you wanted to make is a one-line change, as there’s nothing more frustrating than finding out you now need to untangle 8 snippets in 5 files in order to get that simple change done.

DRY is a power tool you should master quickly and add to your tool box. I’ve written more about taking DRY further here.

You should subscribe to my feed and follow me on twitter.

Pairing for Life

| Comments

A few years ago I joined a team of Java developers without me having any real-world experience in it. The first project I did on that team was with another teammate, that’s now a good friend. Luckily for me, we did the whole project pairing. It was the first time ever I had done pair programming and I really liked it.

It was pretty amazing. I’ve gone from totally new to an environment to pretty efficient so fast I couldn’t believe it. I still haven’t had the chance again of learning a language in such a way, that simply allows me to code and have a mentor watching over, alerting me whenever I got too close to one of Java’s (many) pitfalls.

The whole project was about 2 months. During it the coding conventions of the team got totally ingrained in me. Even now, years later, my “native” Java code looks just like it did then, with new-lines exactly where they should be and breaking long lines exactly like we all liked. It was just a pleasure working in a team that fostered using your tools better. We used to pick on each other for not knowing this shortcut or that, and refactored our code to be cleaner simply to not disappoint other teammates.

Doing XP, we also wrote the majority of the code test first (back then we called it TDD, but I now know better). That experience was new to both of us, and it was a treat learning it together. We had ideas together, shared ways to attack certain problems, and simply enjoyed ping-pong pairing. As a developer it was a pleasure working in a scheme where all your moves were in sync with the rest of the team. We had the same rhythm and the same habits.

A few months ago, after not working together for about 3 years, we got the chance to pair again during a code retreat. It was odd how fast we got back to business. All our “lingo” was the same, and we got the chance to compare a few new habits we learned over the years. Pairing well can bring real trust, and enables you to get even more satisfaction out of our craft. One known example from the XP community is Ron Jeffries and Chet Hendrickson who have been pairing for over a decade now (and more, such as coaching).

Pairing, my friends, is something you owe yourselves. It’s so good, people are going on tours of pairing! Do it, you won’t go back.

You should subscribe to my feed and follow me on twitter.

Pairing for a Better Future: Grunts Making a Change

| Comments

If you’ve read just about any of my posts you probably know I’m one of those guys that don’t really go for the “live and let live” mantra when it comes to code. If you’re looking for a way to make your work place better (even in extremely small baby steps), one of the best moves is pairing.

Pairing, or pair-programming, is simply the act of two coders sitting together to work on a problem. This method’s advantages have been enumerated so many times before I won’t go into it. The interesting part is that pairing is one of the best tools you have to really change stuff.

Whenever you pair, you shouldn’t cut corners. More importantly, you shouldn’t agree to cut corners because your pair sees things differently. If you spend a day around me, you’ll probably hear me say stuff like “you’re really going to add more code to that mess?” or “dude, please rename that method”. I use pairing to make my work place better. I want to make sure things are fully tested? “Here, I’ll write the test and you’ll make it pass”. I want to remove duplication mercilessly? “… now if we just extract a method here”. Simply want us to be more productive? “You know you could have simply done that with Cmd+Alt+T, right?”

It might sound like I’m one nagging pair to have, but you’d be surprised how much this actually helps things change. After pairing for just a few weeks I get to nag a lot less. “Oh, and here-” “Yeah, I see, we can extract that” or “Want to write the test?”. Yeah, people can change from no-tests to test-first in just a couple of weeks of seeing the benefit.

By pairing, we all get to learn new tricks and views. Every time we disagree we discuss pros and cons and become smarter. There’s nothing I like more than my pairing stopping me as I write code with “I’d actually use this” and show me there’s a much simpler way. Well, maybe other than seeing them write tests when I’m not pairing with them.

But how do you get the pairing ball rolling? That’s actually pretty simple too. I already did these and only recently found out they were all thought of long ago (read about these in Extreme Programming Installed). The easiest is just to look up at your nearest teammate and ask “can you help me here a little?” Or, if someone asks a question that makes my spidey sense tingle instead of telling him what to look for I’ll just come over and help him out. And maybe the best move is to simply drop by when you see someone staring at his screen frustrated and ask “What’cha doing?”

Give it a try, you’d be surprised what you can accomplish with just a little nagging and whole lot of caring.

You should subscribe to my feed and follow me on twitter.

Logging with a Context: Users in Logback and Spring Security

| Comments

During this hectic time of starting an amazing adventure we find that along many of the big and important challenges we have there is an endless stream of small technical problems that solving poorly means a lot of time will go to waste.

One of these is proper logging in a way that will allow you see what your users are doing properly. Pretty quickly we came to the conclusion we want each log message to contain information about the user’s context, so we could easily understand what went wrong when a user tells us about it, and be able to track usage patterns.

The simplest thing we thought of was creating our own logger wrapper to insert our special values, but didn’t like the idea of having to write our own logging interface all over again. We’re using Logback and Spring Security, and after some googling and stackoverflowing I’ve found this solution:

We create simple Converters to insert the username and session ID to the logs, if present:

To make logback know where to find these converters, we add this little guy:

And now all that’s left are configuration changes. Make your pattern contain our cool new keys (“%user” and “%session”):

And this last part is needed for the session context thingie to work (as I was instructed on Stack Overflow). We need to add a certain listener to our web.xml:

And that’s about it. Happy logging!