<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Squirrel&#039;s</title>
	<atom:link href="http://squirrel.pl/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://squirrel.pl/blog</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 16:17:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Culture Kills (or Wins)</title>
		<link>http://squirrel.pl/blog/2012/05/18/culture-kills-or-wins/</link>
		<comments>http://squirrel.pl/blog/2012/05/18/culture-kills-or-wins/#comments</comments>
		<pubDate>Fri, 18 May 2012 16:17:44 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Code Quality]]></category>
		<category><![CDATA[The Big Picture]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=626</guid>
		<description><![CDATA[This post is about one of the things that everyone is aware of to some degree. It feels familiar, but the picture becomes a lot sharper once you put it in a proper perspective. The Project There is an older &#8230; <a href="http://squirrel.pl/blog/2012/05/18/culture-kills-or-wins/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This post is about one of the things that everyone is aware of to some degree. It feels familiar, but the picture becomes a lot sharper once you put it in a proper perspective.</p>
<h1>The Project</h1>
<p>There is an older project created a few years ago, perhaps in 2000 or 2005. At the time it was running a single service on a single server for 100 users. The architecture and tools were adequate: One project, one interface, one process. Some shortcuts &#8211; that&#8217;s fine, you need to get something out to get the money in. Now-standard tools and techniques like TDD, IoC / DI, app servers etc. were nowhere to be seen &#8211; either because they were not needed at that time, or they did not even exist in a reasonable form (Spring, Guice, JEE in 2000 or 2005?).</p>
<p>Five or ten years later, the load went up by a few orders of magnitude. So did the number of features. The codebase has been growing and growing, and new features have been added all the time.</p>
<p>Now, let&#8217;s consider two situations.</p>
<h1>Bad Becomes Worse</h1>
<p>What if the architecture and process remained the same from the very beginning? Single project (now many megabytes of source code). Single process with core logic driven by eight-KLOC-long abominations. Many interesting twists related to &#8220;temporary&#8221; shortcuts from the past. No IoC. No DI. No TDD. Libraries from 2000 or 2005. No agile.</p>
<p>It could be for different reasons. The developers are poor, careless souls who have not improved themselves for so many years and they are not aware that different ways exist (or neglect them). Or they know there are better ways, but are drowned with feature requests.</p>
<p>There is little rotation in the team. A few persistent core members persist, able to navigate in this sea of spaghetti. They are still able to pump out new features. Slower and slower, but anyway. That&#8217;s probably the only reason keeping the project alive. They just neglect change, because if the thing still kind of works. Why fix something that is not broken? Why spend money on improving something that&#8217;s working?</p>
<p>Now we have a fairly fossilized team and project. I dare say in this shape it can only get worse. Even if the product itself was somewhat interesting and stable, would you like to change your job to join the team and work on it? Dealing with tons of legacy code, in a culture that fears change, with no modern tools at your disposal? With no way to learn anything? </p>
<p>Right.</p>
<p>Very good developers usually already have a job and there is no way they would ever quit for this. You will not be able to hire them, unless you pay insane amount of money. Even then, money is not as good a motivator as genuine passion and interest.</p>
<p>Who would do it? Only people with poor skill, lack of experience, desperates or those who don&#8217;t give a damn. They will take forever to get up to speed in this ever growing mudball. And because they&#8217;re not top class, chances are the project won&#8217;t get any better.</p>
<p>We get a nasty negative feedback loop. Bad code and culture encourages more bad code. Mediocre new hires make it even worse. And so the spiral continues.</p>
<h1>Good Gets Better</h1>
<p>In the second scenario, the team has some caring craftsmen. They constantly read, learn, think, explore and experiment. They observe their product and process and improve them as they recognize more adequate tools and techniques. Some time along the path they broke it down into modules and instead of a monolithic mudball got an extensible service-oriented architecture. They understood inversion of control and brought it in together with a DI container, refactoring the god classes before they grew out of control. They got higher test coverage. In short, they constantly evaluate what and how they&#8217;re doing, how they can make it better, and put that to practice.</p>
<p>Now this team can hire pretty much anyone they like. They may decide to hire inexperienced people with the right attitude and train them. But they also are able to attract passionates who are much above average and who will make it even better.</p>
<p>It creates a sweet positive feedback loop. Great culture never loses the edge and it attracts people who can only make it better.</p>
<h1>Quality Matters</h1>
<p>That&#8217;s why quality and refactoring matter. It&#8217;s OK to take a shortcut to get something out. It&#8217;s OK to use basic tools for a basic job. But if you never improve, the project will stagnate and rot away.</p>
<p>Sure, fulfilling business needs is important. Having few bugs is important. Avoiding damage (to people or the business) is important. But in the long run if you just keep cranking out features and never retrospect or pay down technical debt, it will become a nasty ever-slowing grind. If you&#8217;re lucky, it will just get slower and require some babysitting in production and emergency bug fixing. If you&#8217;re less lucky, it will become inoperable and completely unmaintainable if some of the persistent spaghetti wranglers leave or are hit by a truck.</p>
<h1>Are We Doomed?</h1>
<p>To end this sermon with a positive accent, let&#8217;s say that while the feedback loops are strong, they are not unbreakable. Culture change is hard in either direction, but possible. If the &#8220;bad&#8221; team or its management realizes the situation in time and starts improving, they may be able to shift to the positive loop. Introduce slack or retrospectives, start discussion and slowly, but regularly improve. And if for whatever reason you abandon good practices, letting leaders go or drowning them up to the neck with work, it will start the drift towards the negative loop.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/05/18/culture-kills-or-wins/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Software for Use</title>
		<link>http://squirrel.pl/blog/2012/04/26/software-for-use/</link>
		<comments>http://squirrel.pl/blog/2012/04/26/software-for-use/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 16:27:31 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[The Big Picture]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=582</guid>
		<description><![CDATA[Here&#8217;s confession of a full time software developer: I hate most software. With passion. Why I Hate Software Software developers and people around the process are often very self-centered and care more about having a good time than designing a &#8230; <a href="http://squirrel.pl/blog/2012/04/26/software-for-use/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s confession of a full time software developer: I hate most software. With passion.</p>
<h1>Why I Hate Software</h2>
<p>Software developers and people around the process are often very self-centered and care more about having a good time than designing a useful product. They add a ton of cool but useless and bugged features. They create their own layers of frameworks and reinvent everything every time, because writing code is so much more fun than writing, reusing or improving it.</p>
<p>They don&#8217;t care about edge cases, bugs, rare conditions and so on. They don&#8217;t care about performance. They don&#8217;t care about usability. They don&#8217;t care about anything but themselves.</p>
<p>Examples? Firefox that has to be killed with task manager because it slows to a crawl during the day on most powerful hardware. Linux which never really cared or managed to solve the issues with drivers for end user hardware. Google maps showing me tons of hotel and restaurant names instead of street names, the exact opposite of what I want when planning a trip. Eclipse or its plugins that require me to kill the IDE from task manager, waste some more time, and eventually wipe out the entire workspace, recreate it and reconfigure.</p>
<p>All the applications with tons of forms, popups, dialogs and whatnot. Every error message that is a page long, has a stacktrace, cryptic code and whatever internal stuff in it. All the bugs and issues in open source software, which is made in free time for fun, rarely addressing edge cases or issues happening to a few percent users because they&#8217;re not fun.</p>
<p>It&#8217;s common among developers to hate and misunderstand the user. It&#8217;s common even at helpdesk, support and many people who actually deal with end users. In Polish there is this wordplay &#8220;użyszkodnik&#8221;, a marriage of &#8220;użytkownik&#8221; (user) and &#8220;szkodnik&#8221; (pest).</p>
<h1>What Software Really Is About</h1>
<p>Let me tell you a secret.</p>
<p>The only purpose of software is to serve. We don&#8217;t live in a vacuum, but are always paid by someone who has a problem to solve. We are only paid for two reasons: To save someone money, or to let them earn more money. All the stakeholders and users care about it is solving their problems.</p>
<p>I&#8217;ve spent quite a few years on one fairly large project that is critical for most operations of a corporation. They have a few thousand field workers and a few dozen managers above, and only a handful of people responsible for software powering all this. Important as it is, the development team is a tiny part of the entire company.</p>
<p>Whenever I design a form, a report, an email or whatever that the end user will ever see, the first and most important thing to do is: Get in their shoes. Understand what they really need and what problem they are trying to solve. See how we can provide it to the them so that it&#8217;s as simple, concise, self-explanatory and usable as possible. Only then we can start thinking about code and the entire backend, and even then the most important thing to keep in mind is the end user.</p>
<p>We&#8217;re not writing software for ourselves. Most of the time we&#8217;re not writing it for educated and exceptionally intelligent geeks either. We write it for housewives, grandmas, unqualified workers, accountants, ladies at bookshops or insurance companies, all kinds of business people.</p>
<p>We write it for people who don&#8217;t care about software at all and do not have a thorough understanding of it. Nor do they care care how good a time you were having while creating it. They just want to have the job done.</p>
<h1>You&#8217;re Doing It Wrong</h1>
<p>If someone has to ask or even think about how something works, it&#8217;s your failure. If they perform some crazy ritual like rebooting the computer or piece of software, or wipe out a work directory, that&#8217;s your fault. If they have to go through five dialogs for a job that could be done with two clicks, or are forced to switch between windows when there is a better way, it&#8217;s your failure. When they go fetch some coffee while a report that they run 5 times a day is running, it&#8217;s your fault. If there is a sequence of actions or form entries that can blow everything up, a little &#8220;don&#8217;t touch this&#8221; red button, it&#8217;s your fault. Not the end user&#8217;s.</p>
<p>It&#8217;s not uncommon to see a sign in Polish offices that reads (sadly, literally): &#8220;Due to introduction of a computer system, our operations are much slower. We are sorry for the inconvenience.&#8221; Now, that&#8217;s a huge, epic failure.</p>
<h1>Better Ways</h1>
<p>That&#8217;s quite abstract, so let me bring up a few examples.</p>
<p>IKEA. I know furniture does not seem as complicated as software, but it&#8217;s not that trivial either. It takes some effort to package a cabinet or a chest of drawers in a cardboard box that can be assembled by the end user. They could deliver you some wood and a picture of cabinet, and blame you for not knowing how to turn one into another. They could deliver a bunch of needlessly complicated parts without a manual, and blame the user again. </p>
<p>They know they need to sell and have returning customers, not just feel good themselves and blame others.</p>
<p>What they do is carefully design every single part and deliver a manual with large, clear pictures and not a single line of text. And it&#8217;s completely fool-proof and obvious, so that even such a carpentry ignorant as you can assemble it.</p>
<p>LEGO. Some sets have thousands of pieces and are pretty complex. So complex that it would be extremely difficult even for you, craftsman proficient in building stuff, to reproduce.</p>
<p>Again, they could deliver 5,000 pieces and a single picture to you and put the blame on you for being unable to figure it out. Again, that&#8217;s not what what they do. They want to sell and they want you to return. So they deliver a 200-page-long manual full of pictures, so detailed and fool-proof that even a child can do it.</p>
<p>There are good examples in software world as well. <a href="http://stackoverflow.com">StackOverflow</a> is nice, but only for certain kind of users. It&#8217;s great for the Internet geeks who get the concept of upvotes, gamification, focusing on tiny narrow parts and not wider discussion etc. Much less for all kinds of scientists and, you know, regular people, who seem to be the intended audience of StackExchange.</p>
<p><a href="http://google.com">Google search</a> and <a href="http://maps.google.com">maps</a> (for address search, intuitiveness and performance), <a href="http://duckduckgo.com">DuckDuckGo</a> are pretty good. <a href="http://wolframalpha.com">Wolfram Alpha</a>. <a href="http://skyscanner.net">Skyscanner</a> and <a href="http://hipmunk.com">Himpunk</a>. Much of the fool-proof Apple hardware and software.</p>
<p>In other words, when you know what it does and how to use it the first time you see it, and it Just Works, it&#8217;s great.</p>
<h1>Conclusion</h1>
<p>Successful startups know it. They want to sell and if they make people think or overly complicate something, people will just walk on by. I guess many startups fail because they don&#8217;t realize it. Many established brands try to do it and learn from startups, simplifying and streamlining their UIs (Amazon, MS Office, Ebay&#8230;). It&#8217;s high time we applied it to all kinds of software, including the internal corporate stuff and open source.</p>
<p>After all, we&#8217;re only here to serve and solve problems of real people.</p>
<p>That&#8217;s the way you do it.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/04/26/software-for-use/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;Programming Concurrency on the JVM&#8221;</title>
		<link>http://squirrel.pl/blog/2012/04/21/programming-concurrency-on-the-jvm/</link>
		<comments>http://squirrel.pl/blog/2012/04/21/programming-concurrency-on-the-jvm/#comments</comments>
		<pubDate>Sat, 21 Apr 2012 12:35:09 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=553</guid>
		<description><![CDATA[A few years ago when I took concurrency classes pretty much everything I was told was that in java synchronized is key. That&#8217;s the way to go, whenever you have multithreading you have to do it this way, period. I &#8230; <a href="http://squirrel.pl/blog/2012/04/21/programming-concurrency-on-the-jvm/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div style="float:right; margin-left: 2em; margin-bottom:2em"><a href="http://www.amazon.com/gp/product/193435676X/ref=as_li_ss_tl?ie=UTF8&#038;tag=squirs-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=193435676X"><img src="http://squirrel.pl/blog/wp-content/uploads/2012/04/programming_concurrenc.jpg" /></a></div>
<p>A few years ago when I took concurrency classes pretty much everything I was told was that in java <code>synchronized</code> is key. That&#8217;s the way to go, whenever you have multithreading you have to do it this way, period. I also spent quite a while solving many classic and less classic concurrency problems using only this construct, reimplementing more fancy locks using only this construct, preventing deadlocks, starvation and everything.</p>
<p>Later in my career I learned that is not the only way to go, or at least there are those fancy <code>java.util.concurrent</code> classes that take care of some stuff for you. That was nice, but apparently I never took enough time to actually stop and think how those things work, what they solve and why.</p>
<p>The light dawned when I started reading <a href="http://www.amazon.com/gp/product/193435676X/ref=as_li_ss_tl?ie=UTF8&#038;tag=squirs-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=193435676X">Programming Concurrency on the JVM: Mastering Synchronization, STM, and Actors</a> by Venkat Subramaniam.</p>
<p>The book starts with a brief introduction on why concurrency is important today with its powers and perils. It quickly moves on to a few examples of different problems: IO-intensive task like calculating size of a large directory, and computationally intensive task of calculating prime numbers. Once the ground is set, it introduces three approaches to concurrent programming.</p>
<p>The first way to do it is what I summed up in the first paragraph, and what Venkat calls the &#8220;synchronize and suffer&#8221; model. Been there, done that, we know how bad it can get. This approach is called shared mutability, where different threads mutate shared state concurrently. It may be tamed (and a few ways to do it are shown in the book), but is a lot harder than it seems.</p>
<p>Another approach is isolated mutability, where each mutable part of state is only accessed by one thread. Usually this is the actor based concurrency model. The third way is pure immutability where there simply is no mutable state. That is typical for functional programming.</p>
<p>In the following chapters the book explores each of those areas in depth. It briefly explains the Java memory model nad shows what options for dealing with shared mutability and coordinating threads exist in core Java. It clearly states why the features from Java 5 are superior to the classic &#8220;synchronize and suffer&#8221; and describes locks, concurrent collections, executors, atomic references etc. in more detail. This is what most of us typically deal with in our daily Java programming, and the book is a great introduction to those modern (if old, in a way) APIs.</p>
<p>That&#8217;s about one third of the book. The rest is devoted to much more interesting, intriguing and powerful tools: software transactional memory and actors. </p>
<p>Sometimes we have to deal with shared mutability, and very often we need to coordinate many threads accessing many variables. The classic synchronization tools don&#8217;t have proper support for it: Rolling back changes and preventing one thread from seeing uncommited changes of another is difficult, and most likely they lead to coarse-grained locks which basically lock everything while a thread is mutating something. </p>
<p>We know how relational databases deal with it with their ACID transactional model. Software transactional memory is just that but applied to memory, with proper atomicity, consistency and isolation of transactions. If one thread mutates a transactional reference in transaction, another will not see it until that transaction is committed. There is no need for any explicit locks as the libraries (like Akka or Clojure) monitor what variables you access and mutate in transaction and apply locking automatically. They even can rollback and retry the transaction for you.</p>
<p>Another approach is isolated mutability, a.k.a. actors, best demonstated on Akka. Each actor runs in a single thread and all it can do is receive or pass messages. This is probably closest to the original concept of object-oriented programming (<a href="http://michaelfeathers.typepad.com/michael_feathers_blog/2012/03/tell-above-and-ask-below-hybridizing-oo-and-functional-design.html">recommended reading by Michael Feathers</a>). You have isolated cells that pass messages to each other, and that&#8217;s it. When you have a task to execute, you spawn actors and dispatch it to them as immutable messages. When they&#8217;re done, they can call you back by passing another message (if the coordinator is also an actor), or if you&#8217;re not that pure you can wait for the result. Either way, eveything is neatly isolated in scope of a single thread.</p>
<p>Lengthy as this summary/review is, it really does not do justice to the book. The book itself is dense with valuable information and practical examples, which are as close to perfection as possible: There are a few recurring problems which are fairly simple and easy to grasp, solved over and over again with different techniques and different languages. There are many examples in Java, Scala, Groovy, Clojure and JRuby, dealing with libraries such as the core Java API, Clojure, Akka, GPars&#8230; In a few words, a ton of useful stuff.</p>
<p>Last but not the least, it&#8217;s excellently written. If anyone has seen Venkat in real life, this book is all like him &#8211; entertaining, but also thought-provoking, challenging and inspiring. It reads like a novel (if not better than some of them) and is very hard to put down until you&#8217;re done.</p>
<p>Highly recommended.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/04/21/programming-concurrency-on-the-jvm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IDEs of the Future</title>
		<link>http://squirrel.pl/blog/2012/04/14/ides-of-the-future/</link>
		<comments>http://squirrel.pl/blog/2012/04/14/ides-of-the-future/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 06:12:42 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=546</guid>
		<description><![CDATA[I suspect that by now everyone has seen Bret Victor&#8217;s &#8220;Inventing on Principle&#8221; talk. If you haven&#8217;t, here it is: Bret Victor &#8211; Inventing on Principle from CUSEC on Vimeo. I found it great and inspiring not only for the &#8230; <a href="http://squirrel.pl/blog/2012/04/14/ides-of-the-future/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I suspect that by now everyone has seen Bret Victor&#8217;s &#8220;Inventing on Principle&#8221; talk. If you haven&#8217;t, here it is:</p>
<p><iframe src="http://player.vimeo.com/video/36579366?byline=0" width="800" height="450" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<p><a href="http://vimeo.com/36579366">Bret Victor &#8211; Inventing on Principle</a> from <a href="http://vimeo.com/cusec">CUSEC</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>I found it great and inspiring not only for the interactive features, but also for the moral parts. I&#8217;ve seen some previous inventions by Bret in the past around <a href="http://worrydream.com/">WorryDream.com</a>. I wish I had been taught science like this. I try to teach like this, and this definitely is the way I am going to try to teach my children with.</p>
<p>Back to the point, though. Cool as they were, Bret&#8217;s interactive examples made me ask myself whether it could work with something more complicated (or less contrived?). I was not quite sure.</p>
<p>Today <a href="http://getprismatic.com">Prismatic</a> served me Chris Ganger&#8217;s Light Table &#8211; similar concept, even inspired by Bret, applied to an IDE. Take a look at this video:</p>
<p><iframe src="http://player.vimeo.com/video/40281991?title=0&amp;byline=0&amp;portrait=0" width="600" height="450" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></p>
<p>The video tells a lot, but if you prefer text you can read more at <a href="http://www.chris-granger.com/2012/04/12/light-table---a-new-ide-concept/">Chris&#8217; blog</a>.</p>
<p>Now, this is something that probably could work. Maybe not exactly like showed here, maybe not <i>that</i> minimalistic, but it has some ideas that I would really like to see in my IDE today. </p>
<ul>
<li>Showing and searching documentation this way seems absolutely possible. Eclipse does not do it for me yet, though.</li>
<li>I would really love to see this kind of view where you focus on a single chunk of code (class, method or function) and can automatically see all the referenced bits (and only them) and navigate back and forth. I imagine a navigable graph that takes me between places, but it shows contents of more than one file at a time, and is not really based on files but &#8220;chunks&#8221; like functions or classes. Does not seem very far either, and could be as life-changing as multiple desktops or monitors (if not more).</li>
<li>Finally, the interactive debugging. Looks great and could work on functional language like Clojure and I can see how it would work there. It would be one hell of an effort to get it working for Java though, with all the encapsulation and baroque ceremony.</li>
</ul>
<p>All in all, very inspiring ideas. I really hope my IDE does some of those things one day. Keep up the good work, guys!</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/04/14/ides-of-the-future/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ring Handlers &#8211; Functional Decorator Pattern</title>
		<link>http://squirrel.pl/blog/2012/04/10/ring-handlers-functional-decorator-pattern/</link>
		<comments>http://squirrel.pl/blog/2012/04/10/ring-handlers-functional-decorator-pattern/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 21:28:10 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[Librarian]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=529</guid>
		<description><![CDATA[During our last pairing session with Jacek Laskowski on Librarian there was a brief moment of confusion over Ring handlers. We struggled for a short while trying to figure out what order to put them in and what it really &#8230; <a href="http://squirrel.pl/blog/2012/04/10/ring-handlers-functional-decorator-pattern/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>During our last pairing session with <a href="http://japila.pl">Jacek Laskowski</a> on <a href="https://github.com/jaceklaskowski/librarian-clojure">Librarian</a> there was a brief moment of confusion over <a href="https://github.com/mmcgrana/ring">Ring</a> handlers. We struggled for a short while trying to figure out what order to put them in and what it really means to have code like:</p>
<pre class="brush: clojure; title: ; notranslate">
(def app
  (-&gt; routes
    ; sandbar
    (auth/with-security security-policy log-in)
	; compojure helper that includes a few Ring handlers
    site
	; sandbar again
    session/wrap-stateful-session))
</pre>
<p>It didn&#8217;t take us long to figure it out and the solution turns out to be a very elegant functional flavor of decorator.</p>
<p>It&#8217;s easy to dive too deep without proper understanding (and that&#8217;s what I admittedly did). Let&#8217;s start from the very beginning and see what these bits really mean. For starters, here&#8217;s a very basic app in plain Ring that simply returns the entire <code>request</code>:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn my-handler [request]
    {:body (str request)})

(def app my-handler)
</pre>
<p>When I hit http://localhost:3000/?my_param=54 in my browser, in return I get:</p>
<pre class="brush: clojure; title: ; notranslate">
{:remote-addr &quot;0:0:0:0:0:0:0:1&quot;,
 :scheme :http,
 :request-method :get,
 :query-string &quot;my_param=54&quot;,
 :content-type nil,
 :uri &quot;/&quot;,
 :server-name &quot;localhost&quot;,
 :headers {&quot;cookie&quot; &quot;__utma=111872281.60059650.1328613066.1328726201.1328785442.5; __utmz=111872281.1328613066.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&quot;, &quot;connection&quot; &quot;keep-alive&quot;, &quot;accept-encoding&quot; &quot;gzip, deflate&quot;, &quot;accept-language&quot; &quot;pl,en-us;q=0.7,en;q=0.3&quot;, &quot;accept&quot; &quot;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&quot;, &quot;user-agent&quot; &quot;Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0&quot;, &quot;host&quot; &quot;localhost:3000&quot;},
 :content-length nil,
 :server-port 3000,
 :character-encoding nil,
 :body #&lt;Input org.mortbay.jetty.HttpParser$Input@7c04703c&gt;}
</pre>
<p>Note that <code>my_param</code> made it to <code>:query-string</code>, but obviously it&#8217;s quite inconvenient at this point and that&#8217;s not what we really want to deal with.</p>
<p>What is <code>app</code> at this point? No magic here, it&#8217;s just a very simple and boring function.</p>
<p>Let&#8217;s move on and add one of the seemingly magic Ring handlers &#8211; <code>ring.middleware.params/wrap-params</code>:</p>
<pre class="brush: clojure; title: ; notranslate">
(def app
  (wrap-params my-handler))
</pre>
<p>This time for the same URL I get the same map, with a few new entries:</p>
<pre class="brush: clojure; title: ; notranslate">
{:remote-addr &quot;0:0:0:0:0:0:0:1&quot;,
 ; Trimmed for brevity
 :query-params {&quot;my_param&quot; &quot;54&quot;},
 :form-params {},
 :query-string &quot;my_param=54&quot;,
 :params {&quot;my_param&quot; &quot;54&quot;}}
</pre>
<p>I can see that the wrapper added a few new entries: <code>:query-params</code>, <code>:form-params</code> and <code>:params</code>. Great, just like it was supposed to.</p>
<p>Now, what is <code>app</code> at this point? Just like before, it&#8217;s a regular function of <code>request</code>. So what does <code>wrap-params</code> really do? Let&#8217;s take a peek at (parts of) its source:</p>
<pre class="brush: clojure; highlight: [7]; title: ; notranslate">
(defn wrap-params
  [handler &amp; [opts]]
  (fn [request]
    (let [request  (if (:query-params request)
                     request
                     (assoc-query-params request))]
      (handler request))))
</pre>
<p><code>assoc-query-params</code> is no magic, it simply parses query params and merges it with the <code>request</code> map.</p>
<p>Now let&#8217;s take a close look at the last line and back at <code>wrap-params</code> signature. Here&#8217;s what&#8217;s really going on:</p>
<ol>
<li><code>wrap-params</code> takes handler (which is a function of <code>request</code>) as argument. In our case, it&#8217;s the trivial function that returns <code>request</code> in body.</li>
<li>It then performs some work, in this case rebinding <code>request</code> to a map with a few more entries.</li>
<li>Eventually it calls the <code>handler</code> that it got as parameter with the augmented <code>request</code> map.</li>
</ol>
<p>In other words, <code>wrap-params</code> takes a <code>handler</code> function, and returns a function that performs some extra work and invokes the original <code>handler</code>.</p>
<p>Does it look familiar? Yup, it&#8217;s the old good decorator pattern. Do some work, then pass control on to the next handler (which can also be a decorator and delegate it further). In this case, though, it&#8217;s astonishingly simple (compared to what it takes in Java).</p>
<p>Now let&#8217;s say I want to chain one more handler that relies on the previous one. Let&#8217;s say I dislike strings and want to map params by Clojure keywords. There&#8217;s a handler for it: <code>ring.middleware.keyword-params/wrap-keyword-params</code>.</p>
<p>No need to think too long, let&#8217;s jump in and use it:</p>
<pre class="brush: clojure; title: ; notranslate">
(def app
  (wrap-keyword-params (wrap-params my-handler)))
</pre>
<p>&#8230; and I get:</p>
<pre class="brush: clojure; title: ; notranslate">
{; Trimmed for brevity
 :params {&quot;my_param&quot; &quot;54&quot;}}
</pre>
<p>Whoops, that&#8217;s not what I expected. <code>wrap-keyword-params</code> was supposed to create a map with keys as keywords, not strings. Why didn&#8217;t it work?</p>
<p>Naive intuition tells me to treat wrappers as function calls. I wrap <code>my-handler</code> in <code>wrap-params</code> and pass the result of this invocation to <code>wrap-keyword-params</code>, right? Wrong!</p>
<p>Take a look at a sample wrapper above (<code>wrap-params</code>) and think what we were trying to do. What I really created here is a <strong>reversed</strong> chain like:</p>
<ol>
<li>Given a <code>request</code>, map its <code>:params</code> into keywords (<code>wrap-keyword-params</code>).</li>
<li>Then pass control to the next function in chain, <code>wrap-params</code>. It parses query string and adds <code>:params</code> map to <code>request</code>.</li>
<li>Then pass control to <code>my-handler</code> which prints the whole thing to browser</li>
</ol>
<p>Nothing happens in the first step, because <code>:params</code> does exist at this point &#8211; it&#8217;s only created by <code>wrap-params</code> in the second step.</p>
<p>If we reverse it, it works like expected:</p>
<pre class="brush: clojure; title: ; notranslate">
(def app
  (wrap-params (wrap-keyword-params my-handler)))
</pre>
<pre class="brush: clojure; title: ; notranslate">
{; Trimmed for brevity
 :params {:my_param &quot;54&quot;}}
</pre>
<p>To recap, a few things to remember from this lesson:</p>
<ul>
<li>In functional programming, the decorator pattern is elegantly represented as a higher order function. I find it much easier to grasp than the OO flavor &#8211; in Java I would need an interface and 3 implementing classes for the job, greatly limiting (re)usability and readability.</li>
<li>In case of Ring wrappers, typically we have &#8220;before&#8221; decorators that perform some preparations before calling the &#8220;real&#8221; business function. Since they are higher order functions and not direct function calls, they are applied in reversed order. If one depends on the other, the dependent one needs to be on the &#8220;inside&#8221;.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/04/10/ring-handlers-functional-decorator-pattern/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java Puzzlers: Number.MIN_VALUE</title>
		<link>http://squirrel.pl/blog/2012/04/03/java-puzzlers-number-min_value/</link>
		<comments>http://squirrel.pl/blog/2012/04/03/java-puzzlers-number-min_value/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 20:57:25 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Quirks]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=520</guid>
		<description><![CDATA[If I asked you what the largest possible Integer in Java is, you would easily answer 2^31-1, or Integer.MAX_VALUE. Smallest possible Integer? Integer.MIN_VALUE, -2^31. How about a Long? It&#8217;s also a Number, and each Number has MIN_VALUE and MAX_VALUE, and &#8230; <a href="http://squirrel.pl/blog/2012/04/03/java-puzzlers-number-min_value/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If I asked you what the largest possible <code>Integer</code> in Java is, you would easily answer 2^31-1, or <code>Integer.MAX_VALUE</code>. Smallest possible <code>Integer</code>? <code>Integer.MIN_VALUE</code>, -2^31. </p>
<p>How about a <code>Long</code>? It&#8217;s also a <code>Number</code>, and each <code>Number</code> has <code>MIN_VALUE</code> and <code>MAX_VALUE</code>, and you would be right to refer to them.</p>
<p>Obvious and boring, right?</p>
<p>How about a <code>Double</code> then?</p>
<p>It&#8217;s also a <code>Number</code>, and so it has <code>Double.MAX_VALUE</code>, and yes that is the maximum. Minimum? Let me go already, obviously <code>Double.MIN_VALUE</code>!</p>
<p>Nope.</p>
<p>I only learned it today even though I&#8217;ve been programming Java for years. <code>Double.MIN_VALUE</code> is actually a positive number. Quick look at docs says it all: It is the smallest <strong>positive</strong> nonzero value of type double. If you&#8217;re really looking for the smallest value of <code>Double</code>, you need to refer to <code>Double.MIN_NORMAL</code>.</p>
<p>Yes, docs are very clear about it. Yes, it is a static constant, so <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">LSP</a> does not really apply (as if Java didn&#8217;t violate it all the time). Yet I still think <a href="http://lostechies.com/derickbailey/files/2011/03/LiskovSubtitutionPrinciple_52BB5162.jpg">it looks like a duck, it quacks like a duck, but needs batteries</a>. It has different semantics for no good reason, does not follow the principle of least surprise and is plain unintuitive. I add it to my shelf of quirks along with half of Swing, everything around <code>Dates</code> and <code>Calendars</code>, <code>equals</code> and&#8230; what am I still doing here by the way?</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/04/03/java-puzzlers-number-min_value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>33rd Degree 2012</title>
		<link>http://squirrel.pl/blog/2012/03/23/33rd-degree-2012/</link>
		<comments>http://squirrel.pl/blog/2012/03/23/33rd-degree-2012/#comments</comments>
		<pubDate>Fri, 23 Mar 2012 18:06:22 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[conferences]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=511</guid>
		<description><![CDATA[After great success of the first edition of 33rd Degree I did not really need anyone to convince me to participate this year. I can honestly say that I&#8217;ve been waiting for it for a year, and it definitely was &#8230; <a href="http://squirrel.pl/blog/2012/03/23/33rd-degree-2012/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>After great success of the <a href="http://squirrel.pl/blog/2011/04/09/what-i-got-from-33rd-degree">first edition of 33rd Degree</a> I did not really need anyone to convince me to participate this year. I can honestly say that I&#8217;ve been waiting for it for a year, and it definitely was worth it.</p>
<h1>Day 1</h1>
<p>The conference opened with three keynotes. The first speaker was <b>Raffi Krikorian</b> from Twitter who spent good deal of time explaining what Twitter really is: A gigantic event pump that consumes massive amounts of messages and broadcasts them as fast as it can. He also provided a very coarse-grained look over some pieces of their architecture, including heavy use of parallel scatter-gather algorithms even for fairly basic tasks like rendering a timeline. Another interesting bit was their own <a href="http://twitter.github.com/finagle">Finagle</a> library for asynchronous networking with all the fancy stuff of failure detection and failover/retry, service discovery, load balancing etc. Worth noting is that Raffi did not say a bad word about Rails, but only explained why it did not scale to their level.</p>
<p>The second keynote was <b>Ken Sipe</b> talking about the complexity of complexity. I am not sure who was first, but I&#8217;m under the impression that this talk was in many ways similar to Rich Hickey&#8217;s <a href="http://www.infoq.com/presentations/Simple-Made-Easy">Simple Made Easy</a>, except for that it was a lot more fluffy. Rich had a very clear point to make and he did it perfectly, with witty and merciless criticism of some flavors of agile as a little cherry on top.</p>
<p>The third keynote was <b>Venkat Subramaniam</b> on <i>Facts and Fallacies of Everyday Software Development</i>. Addressed to pointy-haired bosses (including inside each one of us), it challenged some common opinions like trusting &#8220;proven technologies&#8221; (read: fossils or large vendors) and advocated polyglot programming (he can&#8217;t help but do it even when he talks about &#8220;pure Java&#8221;). Hardly anything new, but Venkat&#8217;s beloved style still made it an entertaining talk.</p>
<p>After those keynotes we got smaller presentations in parallel tracks with some hard decisions to make. I wish I went to Matthew McCullough&#8217;s git workshop. Instead I wasted some time looking at JFrog presentation by <b>Frederic Simon</b> (I expected some interesting stuff on continuous integration &#038; delivery). <b>Sadek Drobi&#8217;s</b> talk on Play and non-blocking IO was quite OK, but I did not really buy the product. It may be because I&#8217;m not into Play, but I found the solution somewhat overengineered and much less appealing than Finagle.</p>
<p>The last technical talk of the day for me was <b>Wojciech Seliga&#8217;s</b> piece on tests around JIRA. Those guys are quality nuts, but I can honestly say I would feel really safe and comfortable in this environment. He explained all kinds of unit tests that they have: Regular &#8220;boring&#8221; unit tests, integration tests (including talking to other Atlassian products), functional tests and platform tests. Even though most of the functional tests run against an API (and only some on Selenium), testing the whole system takes many hours on a 70-worker CI cluster, and they still do it on each and every commit. That is mostly because of platform and performance tests, where they meticulously test against all kinds of platforms: combinations of OS, architecture, DB and whatnot.</p>
<p>Wojciech openly admitted that sometimes it takes them days to make a build green, but they are still very rigorous about it. He also shared some good tricks. Tests are very neatly organized in categories and you can drill down to see what exactly is failing and why. Failing tests go to quarantine in order to keep developers from assuming that there is a false negative that can be ignored while there can actually be other issues making the build fail. Once something goes into quarantine it&#8217;s either fixed or eradicated, there is zero tolerance for failure.</p>
<h1>Day 2</h1>
<p>I started the second day with <b>Barry O&#8217;Reilly&#8217;s</b> talk on agile &#038; lean startups. I expected much fluff, but I actually learned a few interesting things. We all now the agile/lean cycle of (rougly speaking) iteratively inventing, creating, testing and evaluating, and we got to hear about it here as well. What was interesting and new to me though was how much you can do in the market research field. Two good examples include: Create very detailed portraits of your potential users, to the point where you can actually imagine this person as if you walked their shoes, feel their needs, think how they may want to use your product etc, eventually leading to detailed sketches and scenarios. Consider several distinct portraits and see what functionaliy and user experience emerges. The second idea that sounds crazy to my introvertic self is actually going to the street, cafes etc. and asking strangers about their needs and opinions. Reportedly they love it (&#8220;Building new Facebook? I wanna be a part of it!&#8221;).</p>
<p>Then I listened to <b>Matthew McCullough&#8217;s</b> presentation on economic games in software (and life, actually). Perfectly prepared, rich and fluent, easily one of the best speakers I saw in action (even when he&#8217;s coding, like last year on git and hadoop). Matthew touched a few topics: Money is not the only (and not the most important) part of the equation. It may be better to live in a nice place with your family and friends around you than to be paid $300/hour and work on the South Pole. It goes the other way round as well: If you hire people, make sure you motivate them in other ways &#8211; create a great environment, listen to their needs etc. Speaking of money, he also explained some tricks that are used on us every day &#8211; such as shaping restaurant menu or software license pallette so that they have some ridiculously overpriced things that no-one would buy only to make you buy other overpriced (but cheaper) products.</p>
<p>Enough soft talks, next one was <b>Venkat Subramaniam</b> talking about concurrency, reportedly in pure Java. Started off with a seemingly trivial synchronization issue that is very hard to do right in Java and easily generates a ton of boilerplate. Then he went on to resolve it in a few lines of Clojure (surprise, surprise), explained the concept of STM and went back to Java, resolving the original problem using this little concurrency library (yes, Clojure in Java). Very witty and entertaining, and even though I know some Clojure I wasn&#8217;t aware how easy it is to get it to work for you in Java. It really can be just an accessible concurrency library!</p>
<p>Next on my schedule was <b>Sławek Sobótka&#8217;s</b> talk on basic software engineering patterns. I enjoy most of the works that he publishes on <a href="http://art-of-software.blogspot.com/">his blog</a> and the live presentations. This was no exception, even if most of the stuff wasn&#8217;t new to me. In short, it was a gentle introduction to some ideas behind DDD and modeling. From basic building blocks (value objects, entities, aggregates) up to operations (services) and customization (policies), all neatly organized in clear layers and levels. Professional, clear, fluent and to the point.</p>
<p>Then I saw <b>Ken Sipe&#8217;s</b> presentation on web security, which was basically a run through <a href="https://www.owasp.org/index.php/Top_10_2010">OWASP Top Ten</a> threats. Unlike the keynote this one was little fluff much stuff and taught me something about common security issues. I knew most of the threats, but never really went through the OWASP list myself. Very good and thorough presentation, complemented by personal stories and interesting digressions.</p>
<p><b>Venkat Subramaniam</b> showing Scala in a terribly overcrowded room was the last thing on my agenda for the day. I&#8217;ve never done anything in this language and I found this presentation a very gentle and interesting introduction. Looks like something between powerful but chaotic Groovy (that feels more like a scripting language to me) and old and baroque Java. I could actually give it a try, though I am yet to think of an applicable project.</p>
<h1>Day 3</h1>
<p>I kicked off the last day with <b>Jacek Laskowski&#8217;s</b> talk on Clojure. It clearly was not possible to show all the interesting corners of the language, but I think he did a good job at explaining the very basics as well as some concurrency concepts. It could have included more details or examples on why we would want to use those concurrency constructs, but still it managed to spark some interest (and not scare people off), and that alone is a big win.</p>
<p>Then I listened to <b>Bartosz Majsak</b> talking about Arquillian &#8211; a JBoss library for running higher level tests (demonstrated on Selenium-driven acceptance tests) using mock classes in a managed container. Quite interesting, I may give it a try when I get to play with JEE webapps.</p>
<p>The last strictly technical talk of the day was <b>Nate Schutta</b> on HTML5. Nate asked the audience which parts of the stack they are interested in, and after the introduction went over what we were most interested in: Canvas, client-side data storage and worker threads. Very good, fluent talk, explaining the foundations and history behind HTML5 and complemented by practical examples.</p>
<p>Finally we got three keynotes. The first one was <b>Nate Schutta</b> on code craft. Just like you may expect from keynote, it was a mile wide and an inch deep talk about code and work quality. Keep it simple, keep it short, write tests, don&#8217;t reinvent the wheel, get and respect feedback&#8230; you know it. Professional and interesting, but immediately forgettable. Things to take away: PMD, Clover &#8211; run them regularly, radiate information and encourage others to participate in improvement. Culture kills.</p>
<p>Second keynote was <b>Jurgen Appelo</b> telling us how to <a href="http://www.management30.com/">change the world</a>. It was very well prepared, starting with a witty and masochistic self-introduction, but then it continued to explain a 4-tier model of influencing people:</p>
<ul>
<li>Work iteratively and reflect on your progress, for example using the classic Plan-Do-Check-Act approach.</li>
<li>Understand and drive individuals. Make them aware to the idea or product. Make them desire it by making it challenging, interesting or in other ways appealing. Finally pass on knowledge and abilities.</li>
<li>Affect social interactions and culture. Understand that each successful adoption has several stages: Innovators and early adopters who are personally interested in getting your product or idea (crazy people who are ready to drive around the city looking for the last iPad). The majority or skeptics whose needs are largely different (more interested in the ability to watch a movie on the train than in having the latest and coolest hardware). Finally the laggards who can undo your efforts if you stop early.</li>
<li>Shape the environment to reinforce all of the above: Radiate information, create a strong cultural identity, use incentives, infrastructure and institutions that encourage or guard the right direction.</li>
</ul>
<p>There was much more to it than this shallow summary, and there is a reason why it fits in a 19-page booklet (downloadable).</p>
<p>The last keynote was <b>Uncle Bob Martin</b> demanding professionalism. Let me sum it up. Started off with a weird off-topic discussion on why people see more colors than dogs and les than bees. Then came a good part: Creating software resembles engineering, but not the way we popularly believe. &#8220;Regular&#8221; engineers and architects create very detailed documents and are relatively cheap compared to the manufacturing and execution. It&#8217;s often said that programmers are on the &#8220;manufacturing&#8221; stage, while actually everything they do is on engineering. They actually produce very detailed documents (source code), and that&#8217;s a huge effort compared to execution (compilation and running). So the cost model is inverted.</p>
<p>Then Uncle Bob slowly went to the point. Our computers are many orders of magnitude more powerful than those of the distant past, yet we use very similar constructs. Execution on modern hardware is practically instant and free. Uncle Bob asked where it got us, and someone replied &#8220;Angry Birds&#8221;. To this point I very much agree: It&#8217;s extremely sad how we waste all the power on bloated frameworks or worthless entertainment. But the point that Uncle Bob tried to make was quite different: Since hardware and execution is so cheap, we need to keep the model inverted by making execution as fast as possible, and that is professionalism. Write tests, don&#8217;t test through GUI, avoid database.</p>
<p>Let me repeat: Hardware is blazingly fast, so our primary concern should be to keep the build fast so that most of the time is spent on coding, not compiling deploying. Am I the only one who finds it self-conflicting? The issue is not that we create useless junk. It&#8217;s not that we miss business requirements. It&#8217;s not that we suck at estimation. It&#8217;s to keep the cost model inverted. Actually, when Uncle Bob encouraged the audience to ask questions, someone asked: &#8220;How to estimate better?&#8221; At this point he laughed and left the stage.</p>
<p>One thing worth taking away: Good architecture is what makes decisions about infrastructure deferrable to the last stages of the project. Keep expanding the core and mocking if necessary, and think of database or frameworks last.</p>
<h1>Final Word</h1>
<p>All in all, I would say this edition was as good as the last one if not better. I paid more attention to technical talks and some of them paid off. One thing that was definitely worse: It was terribly overcrowdeed! It was next to impossible to walk the halls or even the large exhibition area, not to mention lunch or bathrooms. I don&#8217;t think making it larger in the same venue was a good idea.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/03/23/33rd-degree-2012/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>&#8220;Enterprise Integration Patterns&#8221;</title>
		<link>http://squirrel.pl/blog/2012/03/06/enterprise-integration-patterns/</link>
		<comments>http://squirrel.pl/blog/2012/03/06/enterprise-integration-patterns/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 09:18:25 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Books]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=496</guid>
		<description><![CDATA[Today messaging is a common tool, but for some reason it also does not seem to be getting much attention. It seems that blogs and schools are busy with OO (how to do it (badly) &#038; let me show you &#8230; <a href="http://squirrel.pl/blog/2012/03/06/enterprise-integration-patterns/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div style="float:right; margin-left: 2em; margin-bottom:2em"><a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683/ref=sr_1_1?ie=UTF8&#038;qid=1331022156&#038;sr=8-1&#038;tag=squirs-20"><img src="http://squirrel.pl/blog/wp-content/uploads/2012/03/enterprise_integration_patterns.jpg" /></a></div>
<p>Today messaging is a common tool, but for some reason it also does not seem to be getting much attention. It seems that blogs and schools are busy with OO (how to do it (badly) &#038; let me show you how to it <i>Right</i>), languages, libraries, and other such low-level stuff. On the other hand, messaging has a very strong position on the market and potential employers are more likely to ask you about it than talk about all the 50 libraries in your CV.</p>
<p>Before plunging headfirst into coding I was looking for some solid semi-theoretical introduction that would explain what exactly messaging is, what problems it tries to solve and what exactly you can do with it. I found <a href="http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683/ref=sr_1_1?ie=UTF8&#038;qid=1331022156&#038;sr=8-1&#038;tag=squirs-20">Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions</a> by Gregory Hohpe and Bobby Woolf and decided to give it a try.</p>
<p>The book starts with a gentle introduction to enterprise integration and its challenges and compares four solutions: shared database, file exchange, RPC and messaging. It explains why messaging is sometimes superior to the alternatives (but is fair about the cost).</p>
<p>The next part presents a high-level overview of the messaging concepts: channels, messages, pipes &#038; filters, routers, translators and endpoints. It also shows a non-trivial (but very clear and interesting) example application which demonstrates where each of the pieces fits.</p>
<p>Finally, it goes through each of the concepts in detail, presenting a handful of patterns for each. This third part appears to be a very rich and complete catalog of common patterns, ranging from basic channel design (point-to-point vs. publish-subscribe, datatype channels, guaranteed delivery etc.), through message construction (command vs. document vs. event, request-reply etc.), routing (splitting and aggregation, content-based routing, dynamic routing etc.), and so on.</p>
<p>Each pattern is presented in a similar way. Authors sketch a problem, discuss possible solutions with their pros and cons, and finally present the pattern as the proposed common way to address it. After the discussion many patterns also have code examples in JMS, MSMQ in .net or TIBCO. Between the chapters there also are a few coding &#8220;interludes&#8221; with a larger application using several patterns together.</p>
<p>I loved this book. It was well thought over. It&#8217;s clear from the first to the last page that the authors knew what they want to convey and masterfully designed a book that probably reads very well on all levels, from absolute beginner to someone who has already worked with messaging. It&#8217;s not intimidating to beginners, nor is it a shallow entry-level piece that will make everyone else yawn.</p>
<p>It&#8217;s not only a &#8220;dry&#8221; catalog of patterns. Everything is provided in broader context and it really shows how those pieces work together. It&#8217;s a very comprehensive introduction to messaging that you can actually use to learn the subject (nothing like trying to learn OO from reading the Gang of Four). On the other hand, the catalog of patterns is very rich and I am quite sure it satisfies most or even all of the needs of real-world applications.</p>
<p>I haven&#8217;t read too many books on messaging, but this one seems so good that if you are even slightly interested in the topic, it is a must read.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/03/06/enterprise-integration-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sequential ID Generation in Congomongo</title>
		<link>http://squirrel.pl/blog/2012/02/29/sequential-id-generation-in-congomongo/</link>
		<comments>http://squirrel.pl/blog/2012/02/29/sequential-id-generation-in-congomongo/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 07:47:29 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=486</guid>
		<description><![CDATA[By default MongoDB uses 12-byte BSON id for objects. For some reason I wanted to use an increasing sequence of integers. The samples in documentation are in JSON and I was not sure how they translate to the Java driver. &#8230; <a href="http://squirrel.pl/blog/2012/02/29/sequential-id-generation-in-congomongo/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>By default MongoDB uses 12-byte BSON id for objects. For some reason I wanted to use an increasing sequence of integers.</p>
<p><a href="http://www.mongodb.org/display/DOCS/Object+IDs">The samples in documentation</a> are in JSON and I was not sure how they translate to the Java driver. The JSON sample looks like:</p>
<pre class="brush: jscript; title: ; notranslate">
function counter(name) {
    var ret = db.counters.findAndModify({query:{_id:name}, update:{$inc : {next:1}}, &quot;new&quot;:true, upsert:true});
    // ret == { &quot;_id&quot; : &quot;users&quot;, &quot;next&quot; : 1 }
    return ret.next;
}

db.users.insert({_id:counter(&quot;users&quot;), name:&quot;Sarah C.&quot;}) // _id : 1
db.users.insert({_id:counter(&quot;users&quot;), name:&quot;Bob D.&quot;}) // _id : 2
</pre>
<p>After some googling I found <a href="http://dev.bubblemix.net/blog/2011/04/auto-increment-for-mongodb-with-the-java-driver/">an implementation in Java</a>. Just as I expected, it&#8217;s much longer and completely different.</p>
<pre class="brush: java; title: ; notranslate">
public static String getNextId(DB db, String seq_name) {
    String sequence_collection = &quot;seq&quot;; // the name of the sequence collection
    String sequence_field = &quot;seq&quot;; // the name of the field which holds the sequence

    DBCollection seq = db.getCollection(sequence_collection); // get the collection (this will create it if needed)

    // this object represents your &quot;query&quot;, its analogous to a WHERE clause in SQL
    DBObject query = new BasicDBObject();
    query.put(&quot;_id&quot;, seq_name); // where _id = the input sequence name

    // this object represents the &quot;update&quot; or the SET blah=blah in SQL
    DBObject change = new BasicDBObject(sequence_field, 1);
    DBObject update = new BasicDBObject(&quot;$inc&quot;, change); // the $inc here is a mongodb command for increment

    // Atomically updates the sequence field and returns the value for you
    DBObject res = seq.findAndModify(query, new BasicDBObject(), new BasicDBObject(), false, update, true, true);
    return res.get(sequence_field).toString();
}
</pre>
<p>Not much later I checked docs and source code for Congomongo and discovered <code>fetch-and-modify</code>. I rewrote the Java sample above to Clojure and later polished it using <a href="https://github.com/kmagiera/congomongo/commit/ac72363235ba2215f4711ee423d71865979d0ef0">code from this commit by Krzysztof Magiera</a>. In the end my sequence generator looks like this:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn next-seq [coll]
  (with-mongo db
    (:seq
	  (fetch-and-modify :sequences {:_id coll} {:$inc {:seq 1}} :return-new? true :upsert? true))))

(with-mongo db
  (insert! :books {:author &quot;Adam Mickiewicz&quot; :title &quot;Dziady&quot; :_id (next-seq :books)}))
</pre>
<p>The raw call to <code>insert!</code> could be wrapped in a function or macro to save some boilerplate if there are more collections. For instance:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn insert-with-id [coll el]
  (insert! coll (assoc el :_id (next-seq coll))))

(with-mongo db
  (insert-with-id :books {:author &quot;Adam Mickiewicz&quot; :title &quot;Dziady&quot;}))
</pre>
<p>In some circles this probably is common knowledge, but it took me a while to figure it all out.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/02/29/sequential-id-generation-in-congomongo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Spring, Velocity and Tiles</title>
		<link>http://squirrel.pl/blog/2012/02/20/spring-velocity-tile/</link>
		<comments>http://squirrel.pl/blog/2012/02/20/spring-velocity-tile/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 12:10:28 +0000</pubDate>
		<dc:creator>Konrad Garus</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tiles]]></category>
		<category><![CDATA[Velocity]]></category>

		<guid isPermaLink="false">http://squirrel.pl/blog/?p=455</guid>
		<description><![CDATA[I like Tiles and I heard a lot about Velocity. They seem to serve different purpose and reportedly are easily married together, so I decided to give it a shot and use them both in Spring web app. The integration &#8230; <a href="http://squirrel.pl/blog/2012/02/20/spring-velocity-tile/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I like <a href="http://tiles.apache.org">Tiles</a> and I heard a lot about <a href="http://velocity.apache.org">Velocity</a>. They seem to serve different purpose and reportedly are easily married together, so I decided to give it a shot and use them both in Spring web app. The integration actually took many hours and was a real rollercoaster during which I learned a lot about all three technologies. Hopefully this post can spare someone this fun and let them focus on business.</p>
<h1>Goals</h1>
<p>When I use tiles, I don&#8217;t like the default (?) approach of <code>tiles.xml</code>. I don&#8217;t want to put imports of JS &#038; CSS, page title, navigation, body etc. each in its own file like in the snippet below, because that makes me switch between editor windows.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;definition name=&quot;hello&quot; template=&quot;/WEB-INF/templates/main.jsp&quot;&gt;
	&lt;put-attribute name=&quot;title&quot; value=&quot;Hello&quot; type=&quot;string&quot; /&gt;
	&lt;put-attribute name=&quot;head&quot; value=&quot;/WEB-INF/templates/hello-js-and-css.jsp&quot; /&gt;
	&lt;put-attribute name=&quot;nav&quot; value=&quot;/WEB-INF/templates/hello-nav.jsp&quot; /&gt;
	&lt;put-attribute name=&quot;body&quot; value=&quot;/WEB-INF/templates/hello.jsp&quot; /&gt;
&lt;/definition&gt;
</pre>
<p>Obviously I don&#8217;t want to put too much detail in <code>tiles.xml</code>, either.</p>
<p>What I really like is having one file per page, assembling the template in one place, such as this piece of JSP:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;tiles:insertTemplate template=&quot;template.jsp&quot;&gt;
	&lt;tiles:putAttribute name=&quot;title&quot; value=&quot;Hello&quot; /&gt;
	&lt;tiles:putAttribute name=&quot;head&quot;&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;/js/jQuery.js&quot; /&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;/js/hello.js&quot; /&gt;
	&lt;/tiles:putAttribute&gt;
	&lt;tiles:putAttribute name=&quot;body&quot;&gt;
		&lt;div&gt;Hello, world!&lt;/div&gt;
	&lt;/tiles:putAttribute&gt;
&lt;/tiles:insertTemplate&gt;
</pre>
<p>In Velocity, it&#8217;s supposed to <a href="http://tiles.apache.org/framework/tutorial/integration/velocity.html">look like this</a>:</p>
<pre class="brush: plain; title: ; notranslate">
#tiles_insertTemplate({&quot;template&quot;: &quot;template.vm&quot;})
	#tiles_putAttribute({&quot;name&quot;:&quot;title&quot;, &quot;value&quot;: &quot;Hello&quot;})#end
	#tiles_putAttribute({&quot;name&quot;:&quot;head&quot;})
		&lt;script type=&quot;text/javascript&quot; src=&quot;/js/jQuery.js&quot; /&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;/js/hello.js&quot; /&gt;
	#end
	#tiles_putAttribute({&quot;name&quot;:&quot;body&quot;})
		&lt;div&gt;Hello, world!&lt;/div&gt;
	#end
#end
</pre>
<p>However, the <a href="http://tiles.apache.org/framework/tutorial/integration/velocity.html">docs on integration</a> are really intended for adding some Velocity support to your Tiles-based app, while I wanted quite the opposite: Use Tiles in my rich Velocity app, with full support for spring context, macros etc.</p>
<h1>Solution</h1>
<p>In short, what we&#8217;re going to do is:</p>
<ol>
<li>Use <code>VelocityViewResolver</code> to resolve and render pages</li>
<li>Add support for Tiles macros to this Velocity rendering engine</li>
<li>Extend the Tiles renderer with full support for Velocity, including Spring context, macros etc. Ultimately we&#8217;re going to make it use the original Velocity engine created by Spring.</li>
</ol>
<p>Full source code in form of a minimal, complete web app are at <a href="https://github.com/konrad-garus/SpringVelocityTiles">github</a>. For details see below.</p>
<h2>Spring &#038; Velocity -&gt; Tiles</h2>
<p>For the first step, we define <code>viewResolver</code> and <code>velocityConfig</code> like this:</p>
<pre class="brush: java; highlight: [13]; title: ; notranslate">
@Bean
public VelocityConfig velocityConfig() {
	VelocityConfigurer cfg = new VelocityConfigurer();
	cfg.setResourceLoaderPath(&quot;/WEB-INF/velocity/&quot;);
	cfg.setConfigLocation(context
			.getResource(&quot;/WEB-INF/velocity.properties&quot;));
	return cfg;
}

@Bean
public ViewResolver viewResolver() {
	VelocityViewResolver resolver = new VelocityViewResolver();
	resolver.setViewClass(VelocityToolboxView.class);
	resolver.setSuffix(&quot;.vm&quot;);
	return resolver;
}
</pre>
<p>It&#8217;s important that we use <code>VelocityToolboxView</code> there, otherwise the tiles directives won&#8217;t work.</p>
<p>We also need to put the following in <code>velocity.properties</code>:</p>
<pre class="brush: plain; title: ; notranslate">
userdirective=org.apache.tiles.velocity.template.AddAttributeDirective,\
  org.apache.tiles.velocity.template.AddListAttributeDirective,\
  org.apache.tiles.velocity.template.DefinitionDirective,\
  org.apache.tiles.velocity.template.GetAsStringDirective,\
  org.apache.tiles.velocity.template.ImportAttributeDirective,\
  org.apache.tiles.velocity.template.InsertAttributeDirective,\
  org.apache.tiles.velocity.template.InsertDefinitionDirective,\
  org.apache.tiles.velocity.template.InsertTemplateDirective,\
  org.apache.tiles.velocity.template.PutAttributeDirective,\
  org.apache.tiles.velocity.template.PutListAttributeDirective
</pre>
<p>This adds basic support for Tiles directives to Velocity, but it&#8217;s still useless because once Velocity hands rendering over to Tiles, Tiles is unable to render Velocity and would simply ignore it (rendering syntax of <code>#directives</code> to browser.</p>
<h2>Tiles -&gt; Velocity</h2>
<p>We need to teach Tiles to use Velocity. For this we&#8217;re going to need a custom <code>TilesInitializer</code>:</p>
<pre class="brush: java; highlight: [4]; title: ; notranslate">
@Bean
public TilesConfigurer tilesConfigurer() {
	TilesConfigurer cfg = new TilesConfigurer();
	cfg.setTilesInitializer(new VelocityTilesInitializer(velocityConfig()));
	return cfg;
}
</pre>
<pre class="brush: java; highlight: [31,32]; title: ; notranslate">
public class VelocityTilesInitializer extends DefaultTilesInitializer {
	private VelocityConfig velocityConfig;

	public VelocityTilesInitializer(VelocityConfig velocityConfig) {
		this.velocityConfig = velocityConfig;
	}

	@Override
	protected AbstractTilesContainerFactory createContainerFactory(
			TilesApplicationContext context) {
		return new BasicTilesContainerFactory() {

			@Override
			protected List&lt;TilesRequestContextFactory&gt; getTilesRequestContextFactoriesToBeChained(
					ChainedTilesRequestContextFactory parent) {
				List&lt;TilesRequestContextFactory&gt; factories = super
						.getTilesRequestContextFactoriesToBeChained(parent);
				registerRequestContextFactory(
						VelocityTilesRequestContextFactory.class.getName(),
						factories, parent);
				return factories;
			}

			@Override
			protected AttributeRenderer createTemplateAttributeRenderer(
					BasicRendererFactory rendererFactory,
					TilesApplicationContext applicationContext,
					TilesRequestContextFactory contextFactory,
					TilesContainer container,
					AttributeEvaluatorFactory attributeEvaluatorFactory) {
				ContextPassingVelocityAttributeRenderer var = new ContextPassingVelocityAttributeRenderer(
						velocityConfig.getVelocityEngine());
				var.setApplicationContext(applicationContext);
				var.setRequestContextFactory(contextFactory);
				var.setAttributeEvaluatorFactory(attributeEvaluatorFactory);
				var.commit();
				return var;
			}
		};
	}
}
</pre>
<p>We&#8217;re almost there, but here&#8217;s a tricky bit. Normally in lines 31-32 you would put <code>velocityAttributeRenderer</code>. However, this renderer completely ignores the Spring-augmented Velocity context &#038; engine that Tiles received from Velocity. It creates its own <code>VelocityEngine</code> and lets it do the rendering, throwing away all the Spring and tiles directives and context objects.</p>
<p>There is no way to change this behavior in Tiles (which otherwise seems to be an interesting study in design patterns and extensibility). I even created two JIRA issues for it: <a href="https://issues.apache.org/jira/browse/TILES-541">541 for forwarding context</a> and <a href="https://issues.apache.org/jira/browse/TILES-542">542 for injecting <code>VelocityEngine</code></a>.</p>
<p>Meanwhile, we have to make do with this workaround (see <a href="https://github.com/konrad-garus/SpringVelocityTiles/blob/master/src/main/java/pl/squirrel/svt/ContextPassingVelocityAttributeRenderer.java">github</a> for full source):</p>
<pre class="brush: java; highlight: [15,23,24,25]; title: ; notranslate">
public class ContextPassingVelocityAttributeRenderer extends
		AbstractTypeDetectingAttributeRenderer {
	// ...

	private VelocityEngine engine;

	public ContextPassingVelocityAttributeRenderer(VelocityEngine engine) {
		this.engine = engine;
	}

	// ...

	public void commit() {
		velocityView = new VelocityView(new TilesApplicationContextJeeConfig());
		velocityView.setVelocityEngine(engine);
	}

	@Override
	public void write(Object value, Attribute attribute,
			TilesRequestContext request) throws IOException {
		if (value != null) {
			if (value instanceof String) {
				InternalContextAdapter adapter = (InternalContextAdapter) ((VelocityTilesRequestContext) request)
						.getRequestObjects()[0];
				Context context = adapter.getInternalUserContext();
				Template template = velocityView.getTemplate((String) value);
				velocityView.merge(template, context, request.getWriter());
			} else {
				throw new InvalidTemplateException(
						&quot;Cannot render a template that is not a string: &quot;
								+ value.toString());
			}
		} else {
			throw new InvalidTemplateException(&quot;Cannot render a null template&quot;);
		}
	}

	// ...
</pre>
<p>It works arounds both of the JIRA issues and lets us accomplish the ultimate goal:</p>
<ol>
<li>The <code>VelocityEngine</code> injected to <code>VelocityView</code> here is the original <code>VelocityEngine</code> from Spring. Among other things, it supports Spring directives and context-dependent tools.</li>
<li>The <code>TilesRequestContext</code> in <code>write</code> method still contains the original Velocity context created from Spring scaffolding. Standard implementation of <code>VelocityAttributeRenderer</code> simply throws it away. This workaround above extracts the original context and uses it for rendering.</li>
</ol>
<h1>Conclusion</h1>
<p>This journey took much more time than I thought. Documentation on such cases is nonexistent, so I spent hours debugging, reading source code, experimenting, praying and cursing. It was even more fun as I had close to zero knowledge of internals of Spring view resolution and rendering engine, as well as Tiles and Velocity.</p>
<p>It&#8217;s quite satisfying since I learned a ton about all those technologies and eventually was able to resolve it in a fairly elegant way. But it was also a frustrating and time-consuming riddle and I hope this post spares someone some trouble.</p>
]]></content:encoded>
			<wfw:commentRss>http://squirrel.pl/blog/2012/02/20/spring-velocity-tile/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

