<?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>Palantir Technologies &#187; tips and tricks</title>
	<atom:link href="http:///category/tips-and-tricks/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Articles from the Engineering Group at Palantir Technologies</description>
	<lastBuildDate>Wed, 14 Dec 2011 17:48:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>The UI Design Interview</title>
		<link>http://blog.palantirtech.com/2011/12/01/the-ui-design-interview/</link>
		<comments>http://blog.palantirtech.com/2011/12/01/the-ui-design-interview/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 17:24:37 +0000</pubDate>
		<dc:creator>bdwyer</dc:creator>
				<category><![CDATA[interviewing]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[user interface]]></category>

		<guid isPermaLink="false">https://wp-admin-techblog.yojoe.local/?p=1946</guid>
		<description><![CDATA[Comic courtesy of XKCD, via Creative Commons License Our frontend engineering candidates go through many of the same types of interviews as our backend candidates, i.e., algo and coding. But because they&#8217;ll be building the user-facing parts of our system, we want to make sure candidates have some design chops as well. Hence the UI [...]]]></description>
			<content:encoded><![CDATA[<div style='text-align: center'><a href='https://www.xkcd.com/722/'><img style='width: 100%' src='http://imgs.xkcd.com/comics/computer_problems.png' alt='Compiler design dependency comic, originally from http://www.xkcd.com/722/' title='Comic originally from http://www.xkcd.com/722/' /></a>
<div style='text-align: right; font-size: 0.6em; margin-bottom: 1em;'>Comic courtesy of <a href='http://www.xkcd.com/722/'>XKCD</a>, via Creative Commons License</div>
</div>
<p>Our frontend engineering <a href="http://www.palantir.com/careers/culture">candidates</a> go through many of the same types of interviews as our backend candidates, i.e., <a href="http://blog.palantir.com/2011/09/26/how-to-rock-an-algorithms-interview/">algo</a> and <a href="http://blog.palantir.com/2011/10/03/the-coding-interview/">coding</a>. But because they&#8217;ll be building the user-facing parts of our system, we want to make sure candidates have some design chops as well. Hence the UI design interview.</p>
<h2>Why have a design interview for an engineer?</h2>
<p>Perhaps my favorite part of being on the frontend team at Palantir is that we get to work on both the design and the implementation of our own UIs, from inception to finished product. Engineers collaborate on the design of the product with other engineers as well as with designers, and we openly debate the merits of all our decisions. The UI interview simulates this kind of cooperative design and debate. Typically, this means you&#8217;ll be asked to design and/or evaluate one or two pieces of UI during the interview, while your interviewer plays both collaborator and critic.</p>
<p>Read on for some helpful points to keep in mind as you work on a design problem with your interviewer.<br />
<span id="more-1946"></span></p>
<h2>It&#8217;s all about the user</h2>
<p>The user is the ultimate arbiter of success for any interface. If users can accomplish their tasks in a simple, efficient, intuitive way, then we&#8217;re doing our job right. Therefore, we must <strong>keep the user in mind</strong> at every stage of interface design.</p>
<p>One common mistake that you can make up front is to assume YOU are the user. Because working on a computer is a solitary activity, it&#8217;s easy to forget that everyone experiences an interface in a different way. Depending on what you&#8217;re designing, the user may be a complete novice or a seasoned sysadmin.</p>
<p>It&#8217;s important to <strong>imagine what your users are like</strong>. If it helps, give the user a name, age, and occupation. Ask yourself these questions:</p>
<ul>
<li>In what context will they use this feature? At work? At home? On a TV from 10 feet away?</li>
<li>Have they used a similar interface before?</li>
<li>How savvy are they with computers in general? Do they know how to copy and paste, drag and drop, or open a context menu?</li>
</ul>
<p>When designing a feature for the interface, walk the user through the feature. <strong>Make a rough sketch</strong> of the main components (buttons, lists, text blocks) on a whiteboard or sheet of paper. Then simulate how your user might interact with the feature, by drawing in their input and selections.</p>
<p>While sketching your proposed interface, <strong>put yourself in the user&#8217;s shoes.</strong> Ask yourself these questions:</p>
<ul>
<li>What will they be doing when they want to start doing X?</li>
<li>How do they discover the feature?</li>
<li>What will they want to do after?</li>
<li>How frequently will the user do X?</li>
<li>What if X fails to complete properly?</li>
</ul>
<p>and so on. Once you&#8217;ve asked yourself those questions, consider how the answers should impact your design and modify it accordingly.</p>
<p><strong>tl;dr: The user is paramount. Each of your decisions should be justified by its impact on the user.</strong></p>
<h2>The interview is highly interactive</h2>
<p>Some candidates are reluctant to contradict the interviewer or provide alternative ideas. We want the opposite. If you have a good idea, <strong>advocate for your position.</strong> I prefer candidates who will contradict me, as long as they back up their ideas with arguments, stories, or examples. The more you can articulate the reason for your beliefs, the better.</p>
<p>Go ahead and keep throwing ideas out there. I&#8217;ll shoot down some of them, but don&#8217;t be daunted. It may take 10 ideas before we discover a gem. (This is how all design works, not just in an interview setting.)</p>
<h2>Be creative, but don&#8217;t re-invent the wheel</h2>
<p>I&#8217;ve seen many candidates jump through incredibly awkward (albeit fancy) hoops just to display some very simple data. If you have a list of data, display it as a list. In general, being familiar with UI conventions is helpful because they encode a lot of hard-earned wisdom.</p>
<p>If you&#8217;ve created an interface that will enable the user to do their task as quickly and painlessly as possible, then stop. Don&#8217;t weigh down the interface with unnecessary features. As Deiter Rams famously said, <strong>&#8220;Good design is as little as possible.&#8221;</strong> This holds true for user interface design just as well as product design. Consider Alan Cooper&#8217;s rule of thumb, &#8220;A user will take as much time to make a choice as there are choices.&#8221; If a user is inundated with options and features, they find the interface more difficult to use. A simple, direct approach is frequently the best one.</p>
<p>If you want a quick and easy measure of the simplicity of a feature, just count the number of clicks to complete the task using your interface. If the user has to switch from mouse to keyboard, count that twice. </p>
<h2>How to prepare</h2>
<p>If you&#8217;ve done some design in the past, especially in a collaborative setting, just come and be yourself &mdash; you&#8217;ll do fine. But if you&#8217;re relatively inexperienced, here are some ways you can improve your design skills:</p>
<ol>
<li>If you&#8217;re still in school, <strong>take an HCI or infoviz course,</strong> especially a project-based course. This will give you some actual design experience, as well as a rich vocabulary and set of concepts for thinking about user interfaces.</li>
<li><strong>The design mindset is a muscle, so exercise it every chance you get.</strong> Constantly ask yourself, &#8220;How could this be different? How could it be better?&#8221; The more you ask yourself these questions, the more they&#8217;ll become unconscious and automatic. Soon you&#8217;ll be wondering about <a href="http://www.amazon.com/Design-Everyday-Things-Donald-Norman/dp/0385267746">the design of everyday things</a> &mdash; in the shower, on the train, and hopefully every time you interact with a piece of software. If you develop the skills to analyze other people&#8217;s designs, you&#8217;ll be able to apply those skills to your own own.</li>
<li><strong>Actually build something</strong> and pay attention to the UI. Go through more than one design before (tentatively) settling on the one you&#8217;re going to build. Draw wireframes and/or mockups. Iterate constantly, even after you think you&#8217;re done.</li>
<li><strong>Ask someone to critique your work.</strong> If you can find someone with an HCI background (or other design skills), she&#8217;ll show you things you couldn&#8217;t see yourself. Once this has happened a few times, you&#8217;ll start internalizing your critics; you&#8217;ll start asking yourself, &#8220;What am I missing here?&#8221; If you find someone who doesn&#8217;t have a design background, treat them like a user. This means taking their feedback very seriously but leaving some room for skepticism. Notoriously, <a href="http://uxmyths.com/post/746610684/myth-21-people-can-tell-you-what-they-want">users don&#8217;t always know what they want</a>.</li>
<li><strong>Read up on UI/UX/HCI/infoviz.</strong> There are a lot of good books and blogs out there. Some of the ones that we&#8217;ve found particularly helpful are <em>About Face</em> by <a href="https://twitter.com/#!/MrAlanCooper">Alan Cooper</a>, <em>Now You See It</em> by Stephen Few, and <em>Don&#8217;t Make Me Think</em> by Steve Krug.</li>
</ol>
<p>I hope this post will help you design better interfaces, and perhaps I&#8217;ll be <a href="http://www.palantir.com/careers/culture">working with you</a> soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2011/12/01/the-ui-design-interview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Rock a Systems Design Interview</title>
		<link>http://blog.palantirtech.com/2011/10/28/how-to-rock-a-systems-design-interview/</link>
		<comments>http://blog.palantirtech.com/2011/10/28/how-to-rock-a-systems-design-interview/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 15:00:41 +0000</pubDate>
		<dc:creator>John Carrino</dc:creator>
				<category><![CDATA[development process]]></category>
		<category><![CDATA[enterprise engineering]]></category>
		<category><![CDATA[interviewing]]></category>
		<category><![CDATA[palantir]]></category>
		<category><![CDATA[softwarephilosophy]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">https://wp-admin-techblog.yojoe.local/?p=1937</guid>
		<description><![CDATA[Comic courtesy of XKCD, via Creative Commons License Note: this third installment in our series on doing your best in interviews. Previously: &#8220;How to Rock an Algorithms Interview&#8221; and &#8220;The Coding Interview&#8221;. One interview that candidates often struggle with is the systems design interview. Even if you know your algorithms and write clean code, that [...]]]></description>
			<content:encoded><![CDATA[<div style='text-align: center'><a href='https://www.xkcd.com/754/'><img style='width: 100%' src='/wp-content/uploads/2011/10/dependencies.png' alt='Compiler design dependency comic, originally from http://www.xkcd.com/754/' title='Comic originally from http://www.xkcd.com/754/' /></a>
<div style='text-align: right; font-size: 0.6em; margin-bottom: 1em;'>Comic courtesy of <a href='http://www.xkcd.com/754/'>XKCD</a>, via Creative Commons License</div>
</div>
<p>
<span style='font-size: 0.7em'><em>Note: this third installment in our series on doing your best in interviews.  Previously: <a href="/2011/09/26/how-to-rock-an-algorithms-interview/" title="How to Rock an Algorithms Interview" target="_blank">&#8220;How to Rock an Algorithms Interview&#8221;</a> and <a href="/2011/10/03/the-coding-interview/" title="The Coding Interview" target="_blank">&#8220;The Coding Interview&#8221;</a>.</em></span>
</p>
<p>One interview that candidates often struggle with is the systems design interview. Even if you know your algorithms and write clean code, that code needs to run on a computer somewhere &mdash; and then things quickly get complicated. A truly unbelievable amount of complexity lies beneath something as simple as <a href="https://plus.google.com/112218872649456413744/posts/dfydM2Cnepe">visiting Google in your browser</a>. While most of that complexity is abstracted away from the end user, as a system designer you have to face it head on, and the more you can handle, the better.</p>
<p>At Palantir, many of our teams give a systems design interview along with an <a href="http://blog.palantir.com/2011/09/26/how-to-rock-an-algorithms-interview/">algorithms interview</a> and a couple of <a href="http://blog.palantir.com/2011/10/03/the-coding-interview/">coding interviews</a>. We don’t expect anyone to be an expert at all three disciplines (although some are). We’re looking for generalists with depth &mdash; people who are good at most things, and great at some. If systems design isn&#8217;t your strength, that’s okay, but you should at least be able to talk and reason competently about a complex system.</p>
<p>Read on to learn about what we&#8217;re looking for and how you can prepare.</p>
<p><span id="more-1937"></span></p>
<h2>We’re measuring three things</h2>
<p>Nominally, this interview appears to require knowledge of <strong>systems</strong> and a knack for <strong>design</strong> &mdash; and it does. What makes it interesting, though, and sets it apart from a coding or an algorithms interview, is that whatever solution you come up with during the interview is just a side effect. What we actually care about is the process. </p>
<p>In other words, the systems design interview is all about <strong>communication</strong>. </p>
<p>This reflects what actually working at Palantir is like. As engineers we have a tremendous amount of freedom. We aren’t asked to implement fully-specced features. Instead we take ownership of <em>open-ended problems</em>, and it’s our job to come up with the best solution to each. We need people we can trust to do the right thing without a lot of supervision &mdash; people who can own large projects and take them consistently in the right direction. Invariably, this means being able to communicate effectively with the people around you. Working on <a href="http://blog.palantir.com/2009/11/06/palantir-like-an-operating-system-for-data-analysis/">problems with huge scope</a> isn&#8217;t something you can do in a vacuum.</p>
<h2>It&#8217;s an open-ended conversation</h2>
<p>Usually we’ll start by asking you to design a system that performs a given task. The prompt will be simple, but don’t be fooled &mdash; these problems are wide and bottomless, and the point of the interview is to see how much volume you can cover in 45 minutes.</p>
<p>For the most part, you’ll be steering the conversation. It’s up to you to understand the problem. That might mean asking questions, sketching diagrams on the board, and bouncing ideas off your interviewer. Do you know the constraints? What kind of inputs does your system need to handle? You have to get a sense for the scope of the problem before you start exploring the space of possible solutions. And remember, there is no single right answer to a real-world problem. Everything is a tradeoff.</p>
<h2>Topics</h2>
<p>Systems are complex, and when you’re designing a system you’re grappling with its full complexity. Given this, there are many topics you should be familiar with, such as:</p>
<ul>
<li><b>Concurrency.</b> Do you understand threads, deadlock, and starvation? Do you know how to parallelize algorithms? Do you understand consistency and coherence?</li>
<li><b>Networking.</b> Do you roughly understand <a href='https://secure.wikimedia.org/wikipedia/en/wiki/Inter-process_communication'>IPC</a> and <a href='https://secure.wikimedia.org/wikipedia/en/wiki/Internet_Protocol_Suite'>TCP/IP</a>? Do you know the difference between throughput and latency, and when each is the relevant factor?</li>
<li><b>Abstraction.</b> You should understand the systems you’re building upon. Do you know roughly how an OS, file system, and database work? Do you know about the various levels of caching in a modern OS?</li>
<li><b>Real-World Performance.</b> You should be familiar with the <a href="http://everythingisdata.wordpress.com/2009/10/17/numbers-everyone-should-know/">speed of everything</a> your computer can do, including the relative performance of RAM, disk, SSD and your network.
<li><b>Estimation.</b> Estimation, especially in the form of a back-of-the-envelope calculation, is important because it helps you narrow down the list of possible solutions to only the ones that are feasible. Then you have only a few prototypes or micro-benchmarks to write.</li>
<li><b>Availability and Reliability.</b> Are you thinking about how things can fail, especially in a <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Fallacies_of_Distributed_Computing">distributed environment</a>? Do know how to design a system to cope with network failures? Do you understand durability?</li>
</ul>
<p>Remember, we&#8217;re not looking for mastery of all these topics. We&#8217;re looking for <em>familiarity</em>. We just want to make sure you have a good lay of the land, so you know which questions to ask and when to consult an expert.</p>
<h2>How to prepare</h2>
<p>How do you get better at something? If your answer isn’t along the lines of &#8220;practice&#8221; or &#8220;hard work,&#8221; then I have a bridge to sell you. Just like you have to write a lot of code to get better at coding and do a lot of drills to get really good at basketball, you’ll need practice to get better at design. Here are some activities that can help:</p>
<ul>
<li><strong>Do mock design sessions.</strong> Grab an empty room and a fellow engineer, and ask her to give you a design problem, preferably related to something she&#8217;s worked on. Don&#8217;t think of it as an interview &mdash; just try to come up with the best solution you can. Design interviews are similar to actual design sessions, so getting better at one will make you better at the other.</li>
<li><strong>Work on an actual system</strong>. Contribute to OSS or build something with a friend. Treat your class projects as more than just academic exercises &mdash; actually focus on the architecture and the tradeoffs behind each decision. As with most things, the best way to learn is by doing.</li>
<li><strong>Do back-of-the-envelope calculations for something you&#8217;re building and then write micro-benchmarks to verify them.</strong> If your micro-benchmarks don&#8217;t match your back-of-the-envelope numbers, some part of your mental model will have to give, and you&#8217;ll learn something in the process.</li>
<li><strong>Dig into the performance characteristics of an open source system.</strong>  For example, take a look at <a href="https://code.google.com/p/leveldb/">LevelDB</a>.  It&#8217;s new and clean and small and well-documented. Read about the <a href="http://leveldb.googlecode.com/svn/trunk/doc/impl.html">implementation</a> to understand how it stores its data on disk and how it compacts the data into levels. Ask yourself questions about tradeoffs: which kinds of data and sizes are optimal, and which degrade read/write performance? <em>(Hint: think about random vs. sequential writes.)</em>
<li><strong>Learn how databases and operating systems work</strong> under the hood. These technologies are not only tools in your belt, but also a great source of design inspiration. If you can  think like a DB or an OS and understand how each solves the problems it was designed to solve, you&#8217;ll be able to apply that mindset to other systems.</li>
</ul>
<h2>Final thought: relax and be creative</h2>
<p>The systems design interview can be difficult, but it&#8217;s also a place to be creative and to take joy in the imagining of systems unbuilt. If you listen carefully, make sure you fully understand the problem, and then take a clear, straightforward approach to communicating your ideas, you should do fine.</p>
<p>Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2011/10/28/how-to-rock-a-systems-design-interview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Coding Interview</title>
		<link>http://blog.palantirtech.com/2011/10/03/the-coding-interview/</link>
		<comments>http://blog.palantirtech.com/2011/10/03/the-coding-interview/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 23:12:07 +0000</pubDate>
		<dc:creator>Allen Chang</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[interviewing]]></category>
		<category><![CDATA[palantir]]></category>
		<category><![CDATA[palantirtech]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">https://wp-admin-techblog.yojoe.local/?p=1925</guid>
		<description><![CDATA[Note: this part is part two of our series on doing your best in interviews. Part one: &#8220;How to Rock an Algorithms Interview&#8221;. Here at Palantir algorithms are important, but code is our lifeblood. We live and die by the quality of the code we ship. It’s no surprise, then, that coding ability is what [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; margin-left: 10px; margin-bottom: 10px'><img src="/wp-content/uploads/2011/09/einstein_coding_interview.jpg" alt="Einstein Coding Interview Joke Image" title="einstein_coding_interview" width="300"/></div>
<p><span style='font-size: 0.7em'><em>Note: this part is part two of our series on doing your best in interviews.  Part one: <a href="/2011/09/26/how-to-rock-an-algorithms-interview/" title="How to Rock an Algorithms Interview" target="_blank">&#8220;How to Rock an Algorithms Interview&#8221;</a>.</em></span></p>
<p>Here at Palantir algorithms are important, but code is our lifeblood. We live and die by the quality of the code we ship. It’s no surprise, then, that coding ability is what we stress the most in our interview process. A candidate can get by with mediocre algorithm skills (depending on the role), but no one can skimp on coding.</p>
<p>Suppose you&#8217;re confident in your ability to write great software. Your task in a coding interview (of which there will be several) is to show the interviewers that you in fact do have the programming chops — that you&#8217;re an experienced coder who knows how to write solid, production-quality code.</p>
<p>This is easier said than done. After all, coding in your <a href="http://eclipse.org/">favorite IDE</a> from the comfort of <code>$familiar_place</code> is very different from coding on a whiteboard (on a problem you&#8217;re totally unfamiliar with) in a pressure-filled 45-minute interview. We realize that the interview environment is not the real world, and we adjust our expectations accordingly. Nonetheless, there are a number of things you can do to put your best foot forward during the interview.</p>
<p>First, though, we&#8217;d like to give you a sense for what we look for during a coding interview. Most important is the ability to write clean <strong>and</strong> correct code &mdash; it&#8217;s not enough just to be correct. A lot of people will be interacting with your code once you&#8217;re on the job, so it should be readable, maintainable, and extensible where appropriate. If your solution is clean and correct, and you produced it in a reasonable amount of time without a lot of help, you&#8217;re in good shape. But even if you stumble a bit, there are other ways to demonstrate your ability. As you work, we also watch for debugging ability, problem-solving and analytical skills, creativity, and an understanding of the ecosystem that surrounds production code.</p>
<p>With our evaluation criteria in mind, here are some suggestions we hope will help you perform at your very best.</p>
<p><span id="more-1925"></span></p>
<h2>Before you start coding</h2>
<ul>
<li><strong>Make sure you understand the problem.</strong> Don&#8217;t hesitate to ask questions. Specifically, if any of the problem requirements seem loosely defined or otherwise unclear, ask your interviewer to make things more concrete. There is no penalty for asking for clarifications, and you don&#8217;t want to miss a key requirement or proceed on unfounded assumptions.</li>
<li><strong>Work through simple examples.</strong> This can be useful both before you begin and after you&#8217;ve finished coding. Working through simple examples before coding can give you additional clarity on the nature of the problem — it may help you notice additional cases or patterns in the problem that you would otherwise have missed had you been thinking more abstractly.</li>
<li><strong>Make a plan.</strong> Be wary of jumping into code without thinking about your program&#8217;s high-level structure. You don&#8217;t have to work out every last detail (this can be difficult for more meaty problems), but you should give the matter sufficient thought. Without proper planning, you may be forced to waste your limited time reworking significant parts of your program.</li>
<li><strong>Choose a language.</strong> At Palantir, we don&#8217;t care what languages you know as long as you have a firm grasp on the fundamentals (decomposition, object-oriented design, etc.). That said, you need to be able to communicate with your interviewer, so choose something that both of you can understand. In general, it&#8217;s easier for us if you use Java or C++, but we&#8217;ll try to accommodate other languages. If all else fails, <a href="http://lolcode.com/">devise your own pseudo-code</a>. Just make sure it&#8217;s precise (i.e. not hand-wavy) and internally consistent, and explain your choices as you go.</li>
</ul>
<h2>While you&#8217;re coding</h2>
<ul>
<li><strong>Think out loud.</strong> Explain your thought process to your interviewer as you code. This helps you more fully communicate your solution, and gives your interviewer an opportunity to correct misconceptions or otherwise provide high-level guidance.</li>
<li><strong>Break the problem down and define abstractions.</strong> One crucial skill we look for is the ability to handle complexity by breaking problems into manageable sub-problems. For anything non-trivial, you&#8217;ll want to avoid writing one giant, monolithic function. Feel free to define helper functions, helper classes, and other abstractions to reach a working solution. You can leverage design patterns or other programming idioms as well. Ideally, your solution will be well-factored and as a result easy to read, understand, and prove correct.</li>
<li><strong>Delay the implementation of your helper functions.</strong> (this serves a corollary to the previous point) Write out the signature, and make sure you understand the contract your helper will enforce, but don&#8217;t implement it right away. This serves a number of purposes: (1) it shows that you&#8217;re familiar with abstractions (by treating the method as an API); (2) it allows you to maintain momentum towards the overall solution; (3) it results in fewer context-switches for your brain (you can reason about each level of the call stack separately); and (4) your interviewer may grant you the implementation for free, if he or she considers it trivial.</li>
<li><strong>Don&#8217;t get caught up in trivialities.</strong> At Palantir we are much more interested in your general problem solving and coding abilities than your recall of library function names or obscure language syntax. If you can&#8217;t remember exactly how to do something in your chosen language, make something up and just explain to your interviewer that you would look up the specifics in the documentation. Likewise, if you utilize an abstraction or programming idiom which admits a trivial implementation, don&#8217;t be afraid to just write out the interface and omit the implementation so you can concentrate on more important aspects of the problem (e.g., &#8220;I&#8217;m going to use a circular buffer here with the following interface without writing out the full implementation&#8221;).</li>
</ul>
<h2>Once you have a solution</h2>
<ul>
<li><strong>Think about edge cases.</strong> Naturally, you should strive for a solution that&#8217;s correct in all observable aspects. Sometimes there will be a flaw in the core logic of your solution, but more often your only bugs will be in how you handle edge cases. (This is true of real-world engineering as well.) Make sure your solution works on all edge cases you can think of. One way you can search for edge-case bugs is to&#8230;</li>
<li><strong>Step through your code.</strong> One of the best ways to check your work is to simulate how your code executes against a sample input. Take one of your earlier examples and make sure your code produces the right result. Huge caveat here: when mentally simulating how your code behaves, your brain will be tempted to project what it wants to happen rather than what actually says happen. Fight this tendency by being as literal as possible. For example, if you&#8217;re calculating a string index with code like <code>str.length()-suffix.length()</code>, don&#8217;t just assume you know where that index will land; actually do the math and make sure the value is what you were hoping for.</li>
<li><strong>Explain the shortcuts you took.</strong> If you skipped things for reasons of expedience that you would otherwise do in a &#8220;real world&#8221; scenario, please let us know what you did and why. For example, &#8220;If I were writing this for production use, I would check an invariant here.&#8221; Since whiteboard coding is an artificial environment, this gives us a sense for how you&#8217;ll treat code once you&#8217;re actually on the job.</li>
</ul>
<p>As an addendum, here are a few suggestions for books we like about the art of software construction:</p>
<p><em><a href='http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882'>Clean Code: A Handbook of Agile Software Craftsmanship</a></em> &#8211; Robert C. Martin<br />
<em><a href="http://www.cc2e.com/">Code Complete: A Practical Handbook of Software Construction</a></em> &#8211; Steve McConnell<br />
<em><a href="http://cm.bell-labs.com/cm/cs/tpop/">The Practice of Programming</a></em> &#8211; Brian Kernighan, Rob Pike<br />
<em><a href="https://secure.wikimedia.org/wikipedia/en/wiki/Design_Patterns">Design Patterns: Elements of Reusable Object-Oriented Software</a></em> &#8211; Erich Gamma, et al.<br />
<em><a href="http://java.sun.com/docs/books/effective/">Effective Java</a></em> &#8211; Joshua Bloch</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2011/10/03/the-coding-interview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Rock an Algorithms Interview</title>
		<link>http://blog.palantirtech.com/2011/09/26/how-to-rock-an-algorithms-interview/</link>
		<comments>http://blog.palantirtech.com/2011/09/26/how-to-rock-an-algorithms-interview/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 17:11:54 +0000</pubDate>
		<dc:creator>Kevin Simler</dc:creator>
				<category><![CDATA[interviewing]]></category>
		<category><![CDATA[palantir]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">https://wp-admin-techblog.yojoe.local/?p=1902</guid>
		<description><![CDATA[Comic courtesy of XKCD, via Creative Commons License We do a lot of interviewing at Palantir, and let me tell you: it&#8217;s hard. I don&#8217;t mean that we ask tough questions (although we do). I mean that the task of evaluating a candidate is hard. The problem? Given a whiteboard and one hour, determine whether [...]]]></description>
			<content:encoded><![CDATA[<div style='text-align: center'><a href='http://www.xkcd.com/399/'><img style='width: 100%; margin-bottom: 20px' src='/wp-content/uploads/2011/09/travelling_salesman_problem.png' alt='Traveling salesman problem comic, originally from http://www.xkcd.com/399/' title='Traveling salesman problem comic, originally from http://www.xkcd.com/399/' /></a>
<div style='text-align: right; font-size: 0.6em; margin-bottom: 1em;'>Comic courtesy of <a href='http://www.xkcd.com/399/'>XKCD</a>, via Creative Commons License</div>
</div>
<p>We do a lot of interviewing at Palantir, and let me tell you: it&#8217;s hard. I don&#8217;t mean that we ask tough questions (although we do). I mean that the task of evaluating a candidate is hard.</p>
<p>The problem? Given a whiteboard and one hour, determine whether the person across from you is someone you&#8217;d like to work with, in the trenches, for the next n years. A candidate&#8217;s performance during an interview is only weakly correlated with his or her true potential, but we&#8217;re stuck with the problem of turning the chickenscratch on the whiteboard into an &#8216;aye&#8217; or &#8216;nay&#8217;. Sometimes it feels like a high-stakes game of reading tea leaves. Believe me we&#8217;re doing our best, but we&#8217;re often left the nagging worry that we&#8217;re passing up brilliant people who just had a bad day or who didn&#8217;t click with a particular problem.</p>
<p>In an effort to improve this situation, we wanted to write up a guide that will help candidates make sense of this process, or at least the part known as an Algorithms Interview. At Palantir we ask questions that test for a lot of different skills — coding, design, systems knowledge, etc. — but one of our staple interviews is to ask you to design an algorithm to solve a particular problem.</p>
<p>It usually starts like this:</p>
<blockquote><p>Given X, figure out an efficient way to do Y.</p></blockquote>
<p><strong>First: Make sure you understand the problem</strong>. You&#8217;re not going to lose points asking for clarifications or talking through the obvious upfront. This will also buy you time if your brain isn&#8217;t kicking in right away. Nobody expects you to solve a problem in the first 30 seconds or even the first few minutes.</p>
<p>Once you understand the problem, <strong>try to come up with a solution – any solution whatever</strong>. As long as it&#8217;s valid, it doesn&#8217;t matter if your solution is trivial or ugly or extremely inefficient. What matters is that you&#8217;ve made progress. This does two things: (1) it forces you to engage with the structure of the problem, priming your brain for improvements you can make later, and (2) it gives you something in the bank, which will in turn give you confidence. If you can achieve a brute force solution to a problem, you&#8217;ve cleared a major hurdle to solving it in a more efficient way.</p>
<p>Now comes the hard part. You&#8217;ve given an O(n^3) solution and your interviewer asks you to do it faster. You stare at the problem, but nothing&#8217;s coming to you. At this point, there are a few different moves you can make, depending on the problem at hand and your own personality. Almost all of these can help on almost any problem:</p>
<ol>
<li><strong>Start writing on the board</strong>. This may sound obvious, but I&#8217;ve had dozens of candidates get stuck while staring at a blank wall. Maybe they&#8217;re not visual people, but still I think it&#8217;s more productive to stare at some examples of the problem than to stare at nothing. If you can think of a picture that might be relevant, draw it. If there&#8217;s a medium-sized example you can work through, go for it. (Medium-sized is better than small, because sometimes the solution to a small example won&#8217;t generalize.) Or just write down some propositions that you know to be true. Anything is better than nothing.
</li>
<p><br/></p>
<li><strong>Talk it through</strong>. And don&#8217;t worry about sounding stupid. If it makes you feel better, tell your interviewer, &#8220;I&#8217;m just going to talk out loud. Don&#8217;t hold me to any of this.&#8221; I know many people prefer to quietly contemplate a problem, but if you&#8217;re stuck, talking is one way out of it. Sometimes you&#8217;ll say something that clearly communicates to your interviewer that you understand what&#8217;s going on. Even though you might not put much stock in it, your interviewer may interrupt you to tell you to pursue that line of thinking. Whatever you do, please DON&#8217;T fish for hints. If you need a hint, be honest and ask for one.
</li>
<p><br/></p>
<li><strong>Think algorithms</strong>. Sometimes it&#8217;s useful to mull over the particulars of the problem-at-hand and hope a solution jumps out at you (this would be a bottom-up approach). But you can also think about different algorithms and ask whether each of them applies to the problem in front of you (a top-down approach). Changing your frame of reference in this way can often lead to immediate insight. Here are some algorithmic techniques that can help solve more than half the problems we ask at Palantir:
<ul>
<li>Sorting (plus searching / binary search)</li>
<li>Divide-and-conquer</li>
<li>Dynamic programming / memoization</li>
<li>Greediness</li>
<li>Recursion</li>
<li>Algorithms associated with a specific data structure (which brings us to our fourth suggestion&#8230;)</li>
</ul>
</li>
<p><br/></p>
<li><strong>Think data structures</strong>. Did you know that the top 10 data structures account for 99% of all data structure use in the real world? Probably not, because I just made those numbers up — but they&#8217;re in the right ballpark. Yes, on occasion we ask a problem whose optimal solution requires a <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom filter</a> or <a href="http://en.wikipedia.org/wiki/Suffix_tree">suffix tree</a>, but even those problems tend to have a near-optimal solution that uses a much more mundane data structure. The data structures that are going to show up most frequently are:
<ul>
<li>Array</li>
<li>Stack / Queue</li>
<li>Hashset / Hashmap / Hashtable / Dictionary</li>
<li>Tree / binary tree</li>
<li>Heap</li>
<li>Graph</li>
</ul>
<p>You should know these data structures inside and out. What are the insertion/deletion/lookup characteristics? (O(log n) for a balanced binary tree, for example.) What are the common caveats? (Hashing is tricky, and usually takes O(k) time when k is the size of the object being hashed.) What algorithms tend to go along with each data structure? (<a href="https://secure.wikimedia.org/wikipedia/en/wiki/Dijkstra%27s_algorithm">Dijkstra&#8217;s</a> for a graph.) But when you understand these data structures, sometimes the solution to a problem will pop into your mind as soon as you even think about using the right one.
</li>
<p><br/></p>
<li><strong>Think about related problems you’ve seen before and how they were solved</strong>. Chances are, the problem you&#8217;ve been presented is a problem that you&#8217;ve seen before, or at least very similar.  Think about those solutions and how they can be adapted to specifics of the problem at hand.  Don&#8217;t get tripped up by the form that the problem is presented &#8211; distil it down to the core task and see if matches something you&#8217;ve solved in the past.</li>
<p><br/></p>
<li><strong>Modify the problem by breaking it up into smaller problems.</strong> Try to solve a special case or simplified version of the problem.  Looking at the corner cases is a good way to bound the complexity and scope of the problem.  A reduction of the problem into a subset of the larger problem can give a base to start from and then work your way up to the full scope at hand.
<p>Looking at the problem as a composition of smaller problems may also be helpful. For example, “find a number in a sorted array which has been shifted cyclically by an unknown constant k” can be solved by (1) first figuring out “k” and then (2) figuring out how to perform binary search on a shifted array).</li>
<p><br/></p>
<li><strong>Don&#8217;t be afraid to backtrack</strong>. If you feel like a particular approach isn&#8217;t working, it might be time to try a different approach. Of course you shouldn&#8217;t give up too easily. But if you&#8217;ve spent a few minutes on an approach that isn&#8217;t bearing any fruit and doesn&#8217;t feel promising, back up and try something else. I&#8217;ve seen more candidates who overcommit than undercommit, which means you should (all else equal) be a little more willing to abandon an unpromising approach.</li>
</ol>
<p>Incidentally, trying out a few different approaches (rather than sticking with a single approach) tends to work well in interviews, because the problems we choose for an interview usually have many different solutions. Happily, the same is true for the problems we solve on the job =)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2011/09/26/how-to-rock-an-algorithms-interview/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Decorator Pattern: Implementing decorators using forwarding classes</title>
		<link>http://blog.palantirtech.com/2011/03/01/decorator-pattern-implementing-decorators-using-forwarding-classes/</link>
		<comments>http://blog.palantirtech.com/2011/03/01/decorator-pattern-implementing-decorators-using-forwarding-classes/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 21:29:18 +0000</pubDate>
		<dc:creator>Allen Chang</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[enterprise engineering]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">https://wp-admin-techblog.yojoe.local/?p=1821</guid>
		<description><![CDATA[A forwarding class is an abstract base class which makes it easier to implement decorators for a particular interface. A forwarding class simply forwards all calls it receives to some delegate; a decorator can then be implemented by extending the forwarding class and overriding the relevant methods. Here&#8217;s an example implementation of a forwarding class [...]]]></description>
			<content:encoded><![CDATA[<p>A forwarding class is an abstract base class which makes it easier to implement decorators for a particular interface. A forwarding class simply forwards all calls it receives to some delegate; a <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Decorator_pattern">decorator</a> can then be implemented by extending the forwarding class and overriding the relevant methods. Here&#8217;s an example implementation of a forwarding class for the <code>Collection&lt;E&gt;</code> interface (from <a href="https://code.google.com/p/google-collections/">Google Collections</a>):</p>
<pre class="brush: java; title: ; notranslate">
public abstract class ForwardingCollection&lt;E&gt; extends ForwardingObject implements Collection&lt;E&gt; {
  @Override protected abstract Collection&lt;E&gt; delegate();

  public boolean add(E element) {
    return delegate().add(element);
  }

  // ... (more overridden methods) ...
}
</pre>
<p>Things worth noting:</p>
<ul>
<li>This class overrides the <code>delegate()</code> method to return a <i>more specific</i> type.</li>
<li>The class contains no instance variables and <i>does not</i> have to be marked <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html">Serializable</a>.</li>
</ul>
<p>Now, here&#8217;s an example of how to implement a decorator using a forwarding class (also from Google Collections):</p>
<pre class="brush: java; title: ; notranslate">
  public class ConstrainedCollection&lt;E&gt; extends ForwardingCollection&lt;E&gt; {
    private final Collection&lt;E&gt; delegate;
    private final Constraint&lt;? super E&gt; constraint;

    public ConstrainedCollection(Collection&lt;E&gt; delegate, Constraint constraint) {
      this.delegate = checkNotNull(delegate);
      this.constraint = checkNotNull(constraint);
    }
    @Override protected Collection&lt;E&gt; delegate() {
      return delegate;
    }
    @Override public boolean add(E element) {
      constraint.checkElement(element);
      return super.add(element);
    }
    @Override public boolean addAll(Collection&lt;? extends E&gt; elements) {
      return super.addAll(checkElements(elements, constraint));
    }
  }
</pre>
<p>This class implements a collection that checks a constraint on all elements added to the collection. Note that writing the decorator is easy given the <a href="https://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ForwardingObject.html">forwarding class</a> &#8212; only the methods relevant to the decorator need to be overridden.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2011/03/01/decorator-pattern-implementing-decorators-using-forwarding-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with jMock</title>
		<link>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/</link>
		<comments>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 21:15:08 +0000</pubDate>
		<dc:creator>Steve Downing</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[development process]]></category>
		<category><![CDATA[javatech]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=1274</guid>
		<description><![CDATA[Here at Palantir, a lot of our automatic tests are full-chain tests. A backend server is fired up, client code runs against it, and everything runs much like a production environment. This makes intuitive sense because it’s a faithful approximation of how the system will run in the field. However, there are some disadvantages to [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; width: 175px;'><a href='http://www.jmock.org/'><img src='http://www.jmock.org/logo.png' style='background-color: #000066; padding: 10px'/></a></div>
<p>Here at Palantir, a lot of our automatic tests are full-chain tests. A backend server is fired up, client code runs against it, and everything runs much like a production environment. This makes intuitive sense because it’s a faithful approximation of how the system will run in the field.</p>
<p>However, there are some disadvantages to this:</p>
<ul>
<li>Full-pass tests don’t always localize the problem. Tests on a client class might fail even if it was the service that behaved incorrectly.
</li>
<li>These full-pass tests are relatively slow. Client code is running against an actual remote service. If a client is being tested, the server code still has to do work — sometimes a lot of work — even if that isn’t the focus of the test.</li>
<li>The constraints of the test are loose. Full-chain tests can mostly only see whether the operation finished correctly. It’s much harder to figure out whether the operation was done efficiently and without making unnecessary service calls.</li>
<li>They’re very little setup flexibility. If you want an RPC to return a specific value, you have little choice but to have your test get the service into a state where it can return that value. This is easy in some cases, but prohibitively difficult in others.</li>
<li>Client tests are forced to share any non-determinism leaked from the service. For example, under real conditions, a request to call A might respond before call B, and sometimes the other way around. This can result in flaky tests or tests that don’t always simulate the conditions you want to exercise.</li>
</ul>
<p>What’s to be done? Fortunately, there’s an option that handles these cases elegantly. We also test with <a href="http://www.jmock.org/">jMock</a>, a library that dynamically generates mock objects from arbitrary interfaces. These mock objects can be configured to check that particular methods are called with particular inputs a particular number of times, and then give prescribed responses.</p>
<p>Hit the link to see a concrete example of jMock in action.<br />
<span id="more-1274"></span></p>
<h2>jMock in action</h2>
<p>Let&#8217;s say I want to test my object viewer page in Palantir Web, but I don’t want to fire up a dispatch server at all. First, I create my mock service object.</p>
<pre class="brush: java; title: ; notranslate">
Mockery context = new Mockery();
final PalantirService service = context.mock(PalantirService.class);
</pre>
<p>Then, I set the expectations of my mock object. In this case, I want to tell my mock object to expect a call to PalantirService.getObject() and PalantirService.getDataSources(). getObject() will return a specific object. Any call made to the service apart from these will make the test fail.</p>
<pre class="brush: java; title: ; notranslate">
context.checking(new Expectations() {{
        oneOf(service).getObject(realm.getId(), myObject.getId());
        will(returnValue(myObject));
        oneOf(service).getDataSources(myObject.getDataSources());
}});
</pre>
<p>Now, I create the object I want to test and inject the service.</p>
<pre class="brush: java; title: ; notranslate">
ObjectViewController controller = new ObjectViewController();
controller.setService(service);
</pre>
<p>And then we fire away.</p>
<pre class="brush: java; title: ; notranslate">
ModelMap model = new ModelMap();
controller.doGet(myObject.getId(), model);
</pre>
<p>Now that the controller (the class we’re exercising) has gone off and populated the model, we check to see that the model is populated correctly. Just like we would in any other test.</p>
<pre class="brush: java; title: ; notranslate">
assertEquals(myObject.getName(), model.get(&quot;objectName&quot;));
assertEquals(myObject, model.get(&quot;object&quot;));
</pre>
<p>But in addition, we also assert that the expectations specified above were satisfied.</p>
<pre class="brush: java; title: ; notranslate">
context.assertIsSatisfied();
</pre>
<p>Not only can we be sure that the right calls were made with the right parameters, but we can also be sure that no calls besides the expected calls were made. So the next time you want more speed or control over your tests, take a look at jMock or another framework like it. It’s a powerful tool in the effort to test your best!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/11/22/fun-with-jmock/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaInvoke allows you to spawn additional Java VMs during testing</title>
		<link>http://blog.palantirtech.com/2009/07/28/javainvoke/</link>
		<comments>http://blog.palantirtech.com/2009/07/28/javainvoke/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 22:00:30 +0000</pubDate>
		<dc:creator>Ari Gesher</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[enterprise software]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=209</guid>
		<description><![CDATA[Here at Palantir we use test-driven development (or TDD for short). Integrated tools like Eclipse and JUnit simplify writing and running unit tests. However, once you need to test a broader swath of functionality, it&#8217;s time to write functional, integration, and system tests. While technically not &#8216;unit testing&#8217;, the testing framework that JUnit provides is [...]]]></description>
			<content:encoded><![CDATA[<div style='float: right; text-align: right; width: 298px'><img src="/wp-content/uploads/2009/07/junit.png" alt="junit success" width="288" height="194" /></div>
<p>Here at Palantir we use <a href="http://en.wikipedia.org/wiki/Test-driven_development">test-driven development (or TDD for short)</a>.  Integrated tools like <a href="http://www.eclipse.org/">Eclipse </a>and <a href="http://junit.org/">JUnit</a> simplify <a href="http://open.ncsu.edu/se/tutorials/junit/">writing and running unit tests</a>.  However, once you need to test a broader swath of functionality, it&#8217;s time to write <a href="http://www.ibm.com/developerworks/library/j-test.html#h1">functional</a>, <a href='http://en.wikipedia.org/wiki/Integration_testing'>integration</a>, and <a href='http://en.wikipedia.org/wiki/System_testing'>system</a> tests.  While technically not &#8216;unit testing&#8217;, the testing framework that JUnit provides is basically the same infrastructure that you want to leverage for writing these more involved types of testing.</p>
<p>When you&#8217;re developing enterprise software, functional testing often means getting your clients to talk to your servers.  For the main <a href="http://www.palantirtech.com/government">Palantir Government</a> product, we integrate the process of bringing the server up and down with the Ant scripts that run our automated unit tests: our testing tasks bring up the server, <a href="http://ant.apache.org/manual/OptionalTasks/junit.html">run the test suite</a>, and then kill the server. This works great and produces nice results.</p>
<p>When I started working on our authentication server, the pattern that we had used before didn&#8217;t work for me.  While the Palantir Government tests ran with a single, static configuration file, I needed to run the authentication server with multiple configurations in the course of running through the all the different functional tests.  I determined that I needed a way to programmatically bring the server up and down for testing. In JUnit parlance, I needed a way to programmatically launch the server component as part of my setup() function for my unit tests and stop it in my teardown().</p>
<p>With my itch-to-scratch firmly in hand (or some other mixed metaphor), I set out to figure out how to invoke new Java processes from inside a unit test.  The solution I came up with (with source code and examples) after the jump.<br />
<span id="more-209"></span></p>
<h2>The Six Ingredients</h2>
<p>So there are six ingredients that go into spawning a new VM:</p>
<ul>
<li>The classpath to use for the new VM</li>
<li>The name of the class to run</li>
<li>The directory to be used as the current directory for the process</li>
<li>The command line arguments to pass to the process</li>
<li>The set of Java system properties to use for this process</li>
<li>The environment to pass to the process</li>
</ul>
<p>Let&#8217;s look at each item individually.</p>
<h3>Classpath</h3>
<p>The classpath will tell the spawned VM where to load classes from.  In JavaInvoke, we use the existing classpath (from the spawning VM) as a starting point and then prepend any new entries to allow overriding the classpath for the spawned VM.</p>
<p>This takes a lot of the tedium out of having to figuring out what to put in the classpath.  Most likely, you want something similar to what you already have, if not completely identical.</p>
<p>We get the classpath from <code>System.getProperty("java.class.path")</code> and can add new entries by prepending the new entry, using the value of  <code>File.pathSeparatorChar</code> as the entry delimiter.  Using <code>File.pathSeparatorChar</code> makes the code cross-platform friendly (since the path separator is &#8216;;&#8217; on Windows and &#8216;:&#8217; on Unix (Linux, Solaris, OS/X, etc.).</p>
<p>Caveat: if you change the working directory and your original classpath was constructed using relative paths, you&#8217;ll probably have trouble getting anything to run (since your classpath will no longer point to right locations).</p>
<h3>Class name</h3>
<p>Pretty simple: what do you want to run in the spawned VM?  The class must have a <code>static void main(String args[])</code> defined, and it must be available for loading via the classpath.</p>
<h3>Working Directory</h3>
<p>If it should be different from the current working directory (CWD) of the running process, then set it and JavaInvoke will change it in the environment.</p>
<h3>Command line arguments</h3>
<p>If the process needs any command line arguments, including VM options, specify them in a string array.  Note that not all of these arguments will necessarily make it to your main method, since the VM executable will parse it first and remove the VM arguments, passing through the program arguments.</p>
<h3>Java System Properties</h3>
<p>System properties can be used to control many aspects of how a VM runs.  You can set them programmatically in your code or you can set set them on the command line by passing <em>-Dkey=value</em>.  Our JavaInvoke implementation will take a Map<string,String> of properties as a convenience argument; all it does is rewrite the map into the command line.</p>
<h3>Process environment</h3>
<p>This is an operating-system level construct.  This is the set of environment variables, also in a Map<string,String> that you would like merged with the current environment.  This would be the place that you set things like LD_LIBRARY_PATH on Unix.</p>
<h2>Dealing with input and output</h2>
<p>So you might ask the question, &#8220;where does the output from the process go?&#8221;  Or more troubling, &#8220;How do I send the process some input?&#8221;  The Java <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html">Process</a> object has methods to deal with this, allowing you to get streams that give you access to the input, output, and error streams of spawned process. That API is straight-forward to deal with, just like any other use of the java.io streams.</p>
<p>However, we want to make the typical case really easy: pulling the output from the spawned process back to the parent that spawned it.  To that end, we add into the mix a class called OutputPiper.  It fires up a thread that pulls all input from the spawned process, tags it with an identifier, and then outputs to the spawner&#8217;s stdout/stderr.</p>
<h3>OutputPiper</h3>
<p>(as extracted from <a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a>)</p>
<pre class="brush: java; title: ; notranslate">
	public static class OutputPiper extends Thread  {
		InputStream in;
		PrintStream out;
		String tag = null;

		public OutputPiper(String tag, InputStream in,PrintStream out) {
			this.in = in;
			this.out = out;
			this.tag = tag;
			// make sure that we don't keep the VM alive
			this.setDaemon(true);
			this.setName(&quot;OutputPiper-&quot; + tag);
			out.println(&quot;Starting output piper for tag: &quot; + tag);
			this.start();
		}

		@Override
		public void run() {
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String line = null;
				do {
					line = reader.readLine();
					if(line != null) {
						out.println(tag + &quot;: &quot; + line);
					}
				}while(line != null);
			}
			catch (Exception e) {
				//
			}
			out.println(&quot;Output piper exiting for tag: &quot; + tag);
		}

		public static OutputPiper createOutputPiper(String tag, InputStream in, PrintStream out) {
			OutputPiper rc = new OutputPiper(tag, in,out);
			return rc;
		}
	}
</pre>
<p>Outpiper extends <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html">Thread</a> so that all the output will arrive back to the controlling process in a timely manner.  For each given process, we spawn off two OutputPipers, one for stdout and one for stderr, corresponding to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#getInputStream()">Process.getInputStream()</a> and the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#getErrorStream()">Process.getErrorStream()</a>.</p>
<h2>ProcessSpawner &#038; JavaInvoke</h2>
<p>There are two key classes in the example:</p>
<ul>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a> &#8211; Essentially a wrapper around <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html">ProcessBuilder</a>, a generic process spawner that makes it simple to invoke processes that that use OutputPipers to forward their output back to their parent. This class allows you to specify the working directory, process environment, and command line for the process to be invoked.</li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/JavaInvoke.java.html'>JavaInvoke.java</a> &#8211; a specialized subclass of ProcessSpawner, this class makes spawning new VMs a piece of cake, doing the necessary translation for Java system properties, setting the proper classpath environment variable with potential overrides, and fills in the fully qualified class name to run.</li>
</ul>
<h2>The Example &#038; Source Code</h2>
<p>I&#8217;ve put together a running example that implements a trivial client and server in JUnit test.  The setup() method spawns the server and then the tests run the client code against the server, tearing it down after each test.  It&#8217;s available in the <a href='/wp-content/uploads/2009/07/PalantirVMSpawnerExample.zip'>PalantirVMSpawnerExample.zip</a> zip file.  Unzip it, run the <i>run.sh</i> or <i>run.bat</i> script as appropriate.  It should generate output that looks like this:</p>
<pre class="console">
-----------------------------------------------------
Starting test testAck
INFO [main] JavaInvoke - CLASSPATH=./lib/devblog-vmspawner.jar
INFO [main] ProcessSpawner - Build process spawner for the following command line:
INFO [main] ProcessSpawner - /home/pteng/java/i586/jdk1.5.0_14/jre/bin/java com.palantir.blog.processspawner.Server
Starting output piper for tag: server-stdout
Starting output piper for tag: server-stderr
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler2]: Got message: some message
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler3]: Got message: SHUTDOWN
Output piper exiting for tag: server-stdout
Output piper exiting for tag: server-stderr
Finished test testAck
-----------------------------------------------------
-----------------------------------------------------
Starting test testShutdown
INFO [main] JavaInvoke - CLASSPATH=./lib/devblog-vmspawner.jar
INFO [main] ProcessSpawner - Build process spawner for the following command line:
INFO [main] ProcessSpawner - /home/pteng/java/i586/jdk1.5.0_14/jre/bin/java com.palantir.blog.processspawner.Server
Starting output piper for tag: server-stdout
Starting output piper for tag: server-stderr
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: Spawning socket handler
server-stdout: Waiting for connection
server-stdout: [Socket Handler3]: Got message: SHUTDOWN
Output piper exiting for tag: server-stdout
Output piper exiting for tag: server-stderr
Took 3 ms to send shutdown.
Took 335 ms for process to die.
Finished test testShutdown
-----------------------------------------------------
SUCCESS: all 2 tests passed
</pre>
<p>The source is included in the zip file, but if you wanted to look at it or link to it on the web, here are the classes involved:</p>
<ul>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Client.java.html'>Client.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Example.java.html'>Example.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/JavaInvoke.java.html'>JavaInvoke.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ProcessSpawner.java.html'>ProcessSpawner.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/Server.java.html'>Server.java</a></li>
<li><a href='/wp-content/uploads/vmspawner_html/com/palantir/blog/processspawner/ServerSpawningTest.java.html'>ServerSpawningTest.java</a></li>
</ul>
<p>And as an added bonus, there&#8217;s an Ant <i>build.xml</i> that will let you tweak and rebuild the demo yourself.</p>
<p>Comments and questions welcome.  Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/07/28/javainvoke/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Data Model Change Eventing</title>
		<link>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/</link>
		<comments>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/#comments</comments>
		<pubDate>Wed, 27 May 2009 20:46:42 +0000</pubDate>
		<dc:creator>Derek Cicerone</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[user interface]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=968</guid>
		<description><![CDATA[One of the early architectural challenges that we faced in building the Palantir Finance product was coming up with a good design for firing events from data models to their listeners. There are many different concepts in our product such as charts, portfolios, and indices which are all maintained by different developers. Initially, each developer [...]]]></description>
			<content:encoded><![CDATA[<p>One of the early architectural challenges that we faced in building the <a href="http://www.palantirtech.com/finance">Palantir Finance</a> product was coming up with a good design for firing events from data models to their listeners.  There are many different concepts in our product such as charts, portfolios, and indices which are all maintained by different developers.  Initially, each developer had their own system for firing events when a data model changed.  This quickly became a drag on development as tools became more integrated because we had to learn each others&#8217; event methodologies and translate between the different systems.</p>
<p>The solution was to select a single event firing system.  We wanted something that was easy-to-use yet powerful enough to express all the changes that might be made to a data model.  Java&#8217;s <a href="http://java.sun.com/docs/books/tutorial/javabeans/properties/bound.html">Property Change Support</a> (PCS) was a good fit because it can support arbitrary events in a very lightweight fashion.</p>
<p>Read on for details of our implementation&#8230;<br />
<span id="more-968"></span></p>
<h2>Property Change Support</h2>
<p>Java&#8217;s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/PropertyChangeSupport.html">PropertyChangeSupport class</a> (PCS) basically allows an object to easily fire events consisting of 4 pieces of information:</p>
<ul>
<li>source object &#8211; the thing that fired the event</li>
<li>property name &#8211; allows the listener to tell events for different things apart</li>
<li>old value &#8211; the old value for the property</li>
<li>new value &#8211; the new value for the property</li>
</ul>
<p>PCS handles all the bookkeeping for adding and removing listeners and firing events.  It is very useful for creating listenable models, but we wanted to make it just a little bit easier by having an abstract class that exposed the add/remove listener calls and took care of initializing PCS:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class AbstractListenableModel implements Serializable {

    private static final long serialVersionUID = 1L;

    private transient PropertyChangeSupport pcs;

    protected AbstractListenableModel() {
        this.init();
    }

    /**
    * Adds a property change listener to the model.
    */
    public final void addPropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.addPropertyChangeListener(listener);
    }

    /**
    * Removes a property change listener from the model.
    */
    public final void removePropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.removePropertyChangeListener(listener);
    }

    /**
    * Fires a property change event to listeners of the model.
    */
    protected final void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
        this.pcs.firePropertyChange(propertyName, oldValue, newValue);
    }

    /**
    * Initializes transient fields during deserialization.
    */
    protected Object readResolve() {
        this.init();
        return this;
    }

    /**
    * Initializes transient fields.
    */
    private void init() {
        this.pcs = new PropertyChangeSupport(this);
    }
}
</pre>
<p>AbstractListenableModel is basically just a simple wrapper for exposing the functionality of PCS.  By extending this abstract class, it&#8217;s very easy to create a listenable model:</p>
<pre class="brush: java; title: ; notranslate">
public final class MyModel extends AbstractListenableModel {

    public static final String PROP_FOO = MyClass.class.getName() + &quot;.Foo&quot;;

    private int foo;

    public int getFoo() {
        return this.foo;
    }

    public void setFoo(int foo) {
        //
        // The semantics of the following line are a little hard to unpack,
        // but it does exactly what it needs to do, and the tradeoff
        // for conciseness over immediate readability is worth it for
        // large models with lots of properties.
        //
        // First, the JVM starts to create a stack frame for the call
        // into firePropertyChange().  It begins binding parameter values
        // from the left to the right.  The pointer to the String contained
        // in PROP_FOO is passed in first, then the current value of
        // this.foo is passed in, then the expression
        //        this.foo = foo
        // is evaluated (setting this.foo to the new value of foo), which
        // returns the new value of foo.  All the parameters are then
        // passed down into firePropertyChange(), which checks whether
        // the oldValue is equal to the newValue.  If they're not equal,
        // it fires the event.  If they are equal, it ignores the event.
        //
        this.firePropertyChange(PROP_FOO, this.foo, this.foo = foo);
    }
}
</pre>
<p>In this example, MyModel contains a single property called foo.  When the value of foo is changed, a property change event will be fired to listeners of the model.</p>
<p>You may notice that the value of PROP_FOO is prefixed by the name of the class.  This ensure that naming collisions do not occur for scenarios in which the same listener is used to listen to multiple models which happen to use the same property name.  This scenario becomes much more likely in the case of event bubbling, which I&#8217;ll talk about next.</p>
<h2>Event Bubbling</h2>
<p>Imagine a scenario in which we have a nested model:</p>
<p>Normally, if a listener needs to receive events from both models A and B, it will need to add itself as a listener to each individual model.  While this solution would work, it’s a little cumbersome, especially when model B can get swapped out for model B’—the listener then has to keep itself synched to the internal state of model A.  It would be nice if model A could just automatically forward all the events from model B (or B’) via its PCS support so that a listener only needs to attach itself to one model instead of multiple models.  With a bit more code in AbstractListenableModel, this is possible:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class AbstractListenableModel implements Serializable {

    private transient PropertyChangeListener childModelListener;

    ...

    /**
    * Registers a child model to this model.
    */
    protected void registerChildModel(ListenableModel childModel, String propertyName) {
        childModel.addPropertyChangeListener(this.childModelListener);
    }

    /**
    * Initializes transient fields.
    */
    private void init() {
        ...
        this.childModelListener = new ChildModelListener();
    }

    /**
    * Listener for property change events fired from child models.
    */
    private final class ChildModelListener implements PropertyChangeListener {
        public void propertyChange(PropertyChangeEvent event) {
            // This is where the bubbling happens
            pcs.firePropertyChange(event);
        }
    }
}
</pre>
<p>Now, whenever model B fires a property change event, this event will also be fired by model A.  This makes it much easier for the listener to listen to events arbitrarily deep in the model hierarchy, because each event fired by a child model gets re-fired (bubbled) by all its ancestors.  All you have to do is attach a listener to the root model and you’ll automatically receive events from all models in the hierarchy.</p>
<p>Note that the registerChildModel method above takes an unused propertyName argument.  In the full implementation of this class, events with the provided property name are monitored.  When an event with the provided property name is fired, childModelListener is detached from the old child model and attached to any new child model.  This ensures that the listenable model is always listening to the current child models.</p>
<h2>Events for Collections</h2>
<p>Any model event support would not be complete without some consideration of how to handle collections such as sets and lists.  To solve this scenario, we created specialized collection classes called ListenableModelSet and ListenableModelList.  These collections hold AbstractListenableModels as their elements and fire events whenever their contents change.  Since the changes to collections can vary widely, the solution we came up for communicating collection changes with full fidelity is basically to fire events with a copy of the old set as the old value and the new set as the new value.  Listeners can then diff the old and new values to determine exactly what changed if necessary.  Additionally, each ListenableModelSet or List adds a ChildModelListener to all of its children (themselves AbstractListenableModels), thereby ensuring that events are bubbled from all models in the collection.</p>
<h2>Conclusion</h2>
<p>Just as we saw with the <a href="http://blog.palantirtech.com/2009/04/20/model-view-adapter/">Adapter</a> piece of the <a href="http://en.wikipedia.org/wiki/Model-view-adapter">MVA</a> triad, when we <a href="http://se.ethz.ch/~meyer/publications/patterns/visitor.pdf">componentize</a> the Model piece there are huge gains to be had.  Once we started using a base Model class and a consistent eventing infrastructure (PropertyChangeSupport), we could add features that made coding across our entire application a lot more pleasant.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/05/27/data-model-change-eventing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Model-View-Adapter</title>
		<link>http://blog.palantirtech.com/2009/04/20/model-view-adapter/</link>
		<comments>http://blog.palantirtech.com/2009/04/20/model-view-adapter/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 20:00:17 +0000</pubDate>
		<dc:creator>Kevin Simler</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javatech]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=210</guid>
		<description><![CDATA[I used to think I understood MVC. In undergraduate CS programs, MVC is taught as an off-the-shelf pattern, explained once and then ready for use in the real world. Wikipedia also makes it seem pretty simple: Model–View–Controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from [...]]]></description>
			<content:encoded><![CDATA[<p>I used to think I understood MVC.  In undergraduate CS programs, MVC is taught as an off-the-shelf pattern, explained once and then ready for use in the real world.  Wikipedia also makes it seem pretty simple:</p>
<blockquote><p><a href="http://en.wikipedia.org/wiki/Model-view-controller">Model–View–Controller (MVC)</a> is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.</p></blockquote>
<p>They go on to show the classic triangle diagram and how it&#8217;s baked into various GUI and web frameworks.  There&#8217;s only one clause in the entire article that hints at something deeper:  &#8220;Though MVC comes in different flavors…&#8221;</p>
<p>Different flavors indeed.  In fact MVC is not just <em>a</em> pattern but a whole family of patterns:  <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a>, <a href="http://en.wikipedia.org/wiki/Model-view-adapter">MVA</a>, <a href="http://en.wikipedia.org/wiki/Model_View_Presenter">MVP</a>, <a href="http://en.wikipedia.org/wiki/Presentation-abstraction-control">PAC</a>, <a href="http://c2.com/cgi/wiki?ModelDelegate">Model-Delegate</a>&#8230;.  It very quickly gets very hairy.</p>
<p>In this article I want to describe one of MVC&#8217;s lesser-known variants, the <a href="http://en.wikipedia.org/wiki/Model-view-adapter">Model-View-Adapter (MVA) pattern</a>, and talk about its advantages over traditional MVC in the context of a Java Swing application.</p>
<p><span id="more-210"></span></p>
<h2>Architecture</h2>
<p>The best place to start is with an architecture diagram.  While vanilla MVC is a triangle:</p>
<div class="postimg"><a href="/wp-content/uploads/2009/04/mvc.png"><img title="mvc" src="/wp-content/uploads/2009/04/mvc.png" alt="Model-View-Controller" /></a></div>
<p>MVA puts the Adapter in a position to strictly mediate between Model and View:</p>
<div class="postimg"><a href="/wp-content/uploads/2009/04/mva.png"><img title="mva" src="/wp-content/uploads/2009/04/mva.png" alt="Model-View-Adapter" /></a></div>
<p>Here a solid line represents a direct relationship while a dashed line represents an indirect relationship via the Observer pattern.  Put another way, the Adapter holds a pointer both to the Model and to the View and directly calls methods on both.  At the same time, it attaches itself as a listener both to the Model and to the View in order to receive events.  It receives property change events from the Model and action events (checkbox ticked, text entered, etc.) from the View, and then routes appropriate changes to the other side.  The Adapter is entirely responsible for keeping the Model and the View in sync; the Model and View are both relatively dumb structures, knowing nothing about the other.</p>
<p>The advantages to organizing code this way are:</p>
<ul>
<li>All &#8220;moving parts&#8221; are centralized in one place, the Adapter.  No worrying about where to add a listener; no hunting around to find isolated listeners.</li>
<li>Separation of concerns between the View and the Adapter.  The View is responsible for layout and visual presentation while the Adapter is responsible for synchronization and the dynamic aspects of the user interface.</li>
<li>Better decoupling between Models and Views.  Specifically, the View doesn&#8217;t need to know anything about the Model.</li>
</ul>
<p>Additionally, while it will never be possible to fully <a href="http://se.ethz.ch/~meyer/publications/patterns/visitor.pdf">componentize </a> any variant of the MVC pattern, MVA is more amenable to componentization and thus more of its implementation can be centralized (in a single class) and reused.  Once componentized, we can augment the basic functionality with things like:</p>
<ul>
<li>Automatic registration and unregistration of listeners when the View enters and exits the Swing component hierarchy, thereby preventing certain kinds of memory leaks.</li>
<li>Automatic unregistration of listeners when the program shuts down.  This can help free up resources like realtime subscriptions.</li>
<li>Method for swapping a new Model object in for an old Model object.</li>
<li>Ability to execute a task without listeners attached, to help prevent event-action-event loops.</li>
</ul>
<p>The downside to using MVA over MVC is that the Adapter tends to take on a lot of the responsibility and can get quite complicated.  But in my experience that can be mitigated by having good conventions about which pieces (M, V, A) are allowed to communicate with which other pieces and at what times.  Enforcing predictable control flow goes a long way toward managing complexity.</p>
<p>Read on for a code-level description of our implementation of the MVA pattern.</p>
<h2>Palantir MVA Implementation</h2>
<p>Our half-componentization of MVA resides in a single abstract class named Adapter:</p>
<pre class="brush: java; title: ; notranslate">
public abstract class Adapter&lt;ViewType extends Component, ModelType&gt; {
// constructor
protected Adapter(ViewType view, ModelType model); { ... }

/**
* Attach listeners to the View's subcomponents (checkboxes etc.).
* Listeners should be stored as member variables in the Adapter
* subclass.
*/
protected abstract void registerViewListeners();

/**
* Detach the same listeners (member variables) that were
* attached in registerViewListeners().
*/
protected abstract void unregisterViewListeners();

/**
* Attach listener(s) to the Model.
*/
protected abstract void registerModelListeners();

/**
* Detach the same listeners (member variables) that were
* attached in registerModelListeners().
*/
protected abstract void unregisterModelListeners();

/**
* Bring the View fully in synch with the Model.  Typically
* this involves querying state from the Model and
* reconfiguring subcomponents of the View accordingly.
*/
protected abstract void fullSynchronize();

protected ModelType getModel() { ... }
protected ViewType getView() { ... }

// other methods elided
}
</pre>
<p>New View components that want to stay synchronized with a Model must instantiate a subclass of Adapter and implement the abstract methods.  The Adapter parent class (itself an example of the Template Method design pattern) will then call into the appropriate abstract methods at the appropriate times.  For example, after the View is constructed, as soon as it&#8217;s displayed in the Swing component hierarchy the Adapter parent class will automatically call fullSynchronize() (whose implementation should bring the View in line with the Model) and then registerViewListeners() and registerModelListeners(), so the Adapter is poised to react to events.  Likewise, when the View is removed from the component hierarchy (when its containing frame is closed, say), both unregisterViewListeners() and unregisterModelListeners() will be called.  This can help ensure that no memory will be leaked when a long-life-cycle object (like a system-wide singleton) retains a pointer to a short-life-cycle object (the View) via the Observer pattern.</p>
<h2>Dealing With Listener Loops</h2>
<p>One problem that confronts UI developers is the problem of &#8220;listener loops&#8221;:  infinite loops that result when the View fires an event, the Adapter (or Controller) responds to it by setting some property on the Model, and an event is propagated from the Model back to the View, starting the whole cycle over again.</p>
<p>One way to combat this is to make sure your Model only fires events when the value that&#8217;s being set on the Model is different from the value currently stored in the Model.  (This will cut off the infinite loop after one and a half cycles.)  It&#8217;s a good practice but often isn&#8217;t enough, especially when your system is multithreaded and events start to queue up.  You can sometimes get into situations where an M-V-C triplet will thrash forever between two different values for one of the Model&#8217;s properties.</p>
<p>Our solution to this problem is a protected method (on our Adapter base class) called runWithoutViewListeners:</p>
<pre class="brush: java; title: ; notranslate">
/**
* Guarantees that the job r will be run:
*    - on the Swing thread
*    - with Model listeners attached
*    - with View listeners DEtached
*/
public final void runWithoutViewListeners(final Runnable r) { ... }
</pre>
<p>The implementation of this method checks to make sure the view listeners are attached when it&#8217;s called, detaches them via a call to unregisterViewListeners(), invokes the Runnable, then reattaches the view listeners via a call to registerViewListeners().  The code inside the Runnable can then make whatever changes it wants to the View without perturbing the Model downstream.  Listener loop averted!</p>
<h2>More To Come</h2>
<p>I hope that&#8217;s given you some sense of the territory out there in the wide world of MVC-variants.  In a week or two, Derek will show off some of the work he&#8217;s done on the M piece of the MVA triad related to &#8220;event bubbling.&#8221;  Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/04/20/model-view-adapter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Pokémon Problem: a new anti-pattern</title>
		<link>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/</link>
		<comments>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 03:59:45 +0000</pubDate>
		<dc:creator>John Carrino</dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[software engineering]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.palantirtech.com/?p=202</guid>
		<description><![CDATA[It&#8217;s always fun to release a new piece of jargon into the wild. I&#8217;ve run into a number of bugs in our codebase that caused by an anti-pattern I&#8217;d like to dub The Pokémon Problem. Much like the game of Whac-a-Mole, this is a class of bugs where fixing every occurrence does not prevent the [...]]]></description>
			<content:encoded><![CDATA[<div style="float: right; margin-left: 15px; margin-bottom: 15px;"><img src="/wp-content/uploads/2009/03/pokepic1.jpg" alt="Gotta catch 'em all!" width="220" height="245" /></div>
<p>It&#8217;s always fun to release a new piece of jargon into the wild. I&#8217;ve run into a number of bugs in our codebase that caused by an <a href="http://en.wikipedia.org/wiki/Anti-pattern">anti-pattern</a> I&#8217;d like to dub <strong>The Pokémon Problem</strong>.</p>
<p>Much like the game of <a href="http://en.wikipedia.org/wiki/Whack-a-mole">Whac-a-Mole</a>, this is a class of bugs where fixing every occurrence does not prevent the bug from returning in new code: it is easy for code delta to result in an instance of the bug being re-introduced into the code base. Even if you &#8220;<a href="http://www.youtube.com/watch?v=vZ3gPXVMWRY">catch &#8216;em all</a>&#8220;, nothing prevents someone else from introducing new Pokémon bugs later.</p>
<p>Not only is this bug easy to re-introduce, but it sometimes can be hard to find all currently existing instances of this pattern. Although tools like Eclipse make it easier to track down all the places that code is called,  sometimes you&#8217;re looking for things that happen in a certain sequence (which tools like Eclipse don&#8217;t do a good job of searching for) and dynamic invocation mechanisms like <a href="http://www.ibm.com/developerworks/library/j-dyn0603/">Java Reflection</a> can sometimes make it impossible to be exhaustive.  This type of bug is also resistant to automated refactoring: changing the protocol of dealing with this corner of your code will require you to track down all places it was touched and manually refactor them.  It generally signals a failure to use sufficient <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>.</p>
<p>In general, this anti-pattern is a result of <a href="http://en.wikipedia.org/wiki/API">APIs</a> that require the caller to be responsible for state management of resources that the API owns.  This can include things like an object that requires the caller to have run an initialization method before calling any other method on the object.  These bugs get even more insidious when a failure to do things in the right order does not cause a hard failure (like throwing an exception) but instead creates some sort of subtle corruption that may not be noticed or cause subsequent calls to fail unexpectedly.</p>
<p>Read on for some strategies on dealing with the Pokémon problem.<br />
<span id="more-202"></span></p>
<h2>Solving the Pokémon Problem</h2>
<p>How do we solve the Pokémon problem?  Sometimes it is as easy as writing a unit test to verify that no new Pokémon exist. More often than not, though, you&#8217;ll have to use better encapsulation to solve the problem.  If the Pokemon problem is the anti-pattern, <a href="http://en.wikipedia.org/wiki/Information_hiding">encapsulation</a> is its opposite.</p>
<p>For an example, I&#8217;ll turn to a real problem I ran into in the <a href="http://www.palantirtech.com/videos/">Palantir Government</a> codebase:  Let&#8217;s say I have class <em>Parser</em> and it has a method <em>getAttribute()</em>.  I want to add the ability to have shortened (obfuscated) tag names to the <em>Parser</em> class.</p>
<h3>The wrong approach</h3>
<p>One approach I can take:</p>
<ol>
<li>Create a class called <em>AttributeHandler</em> that wraps calls to <em>Parser.getAttribute()</em>. It handles detection of the short or full XML dialect and then returns the appropriate attribute value.
</li>
<li>Stick an instance of this <em>AttrbributeHandler</em> class in a member variable of <em>Parser</em> and make sure to call <em>AttributeHandler.getAttribute()</em> instead of <em>Parser.getAttribute()</em> when processing attributes.</li>
<li>Put comment on <em>Parser.getAttribute()</em> mentioning that it shouldn&#8217;t be called directly anymore.</li>
</ol>
<p>I just introduced a Pokémon problem.  The next person that edits this code may not read my comment and know that calling <em>Parser.getAttribute()</em> is a bug.  They may not test the short tag case and find the bug. How do I fix this Pokémon problem? </p>
<h3>The right approach</h3>
<p>Approaching this encapsulation problem has a number of different approaches one could take.  Here&#8217;s what I chose:</p>
<ol>
<li>Create a class called <em>AttributeHandler</em> that wraps calls to <em>Parser.getAttribute()</em>. It handles detection of the short or full XML dialect and then returns the appropriate attribute value.
</li>
<li>Stick an instance of this <em>AttrbributeHandler</em> class in a member variable of <em>Parser</em>.</li>
<li>Create a wrapper class around <em>Parser</em> that delegates the <em>getAttribute()</em> call to the <em>AttributeHandler</em> member when processing attributes.</li>
</ol>
<p>(You might ask why I used a delegate instead of sub-classing the parser and overriding the <em>getAttribute()</em> method: it didn&#8217;t fit for architectural reasons that aren&#8217;t relevant here). Now the developer no longer has access to the <em>Parser.getAttribute()</em> method that would cause the undesired behavior.</p>
<h2>In-depth Example: Resource Management</h2>
<p>Another common place you might run into the Pokémon problem is code that needs to clean up resources.  Some coders are lazy and don&#8217;t want to always write their try/finally/close blocks properly.  This can lead to resource leaks; for things like file handles, this usually isn&#8217;t a large issue, but for scarce resources like database connections, it&#8217;s critical that things get cleaned and returned to the pool.  For locks, it&#8217;s absolutely essential to avoid deadlocks.</p>
<h3>The wrong way</h3>
<p>Here&#8217;s a simple example of bad resource management.  In this (admittedly contrived) scenario, we have class that&#8217;s managing a resource for us, in this case it&#8217;s a status file.  Different parts of the app need to read the status file where, presumably, something is storing its status.</p>
<p>Here&#8217;s the naive implementation of the status manager class:</p>
<pre class="brush: java; title: ; notranslate">

public class PokemonStatusFileManager {

	final File statusFile;

	public PokemonStatusFileManager(File statusFilePath) {
		this.statusFile = statusFilePath;
	}

	public InputStream getStatusFileInputStream() throws FileNotFoundException {
		return new FileInputStream(this.statusFile);
	}
}
</pre>
<p>Based on this implementation, here&#8217;s some code that would use it.  Note that first method, <em>parseStatusFileIncorrectly()</em> does no error checking and may not close the <em>InputStream</em> properly if an exception is thrown.  The second method does proper resource handling, but it&#8217;s kind of ugly to read.</p>
<pre class="brush: java; title: ; notranslate">

public class PokemonParseStatusFile {

	/**
	 * This is not proper resource management.
	 * @param manager
	 * @throws IOException
	 */
	public static void parseStatusFileIncorrectly(PokemonStatusFileManager manager)
		throws IOException {

		InputStream statusFile = manager.getStatusFileInputStream();
		readFrom(statusFile);
		statusFile.close();

	}

	/**
	 * This is proper resource management, but it's tedious to have to write.
	 * Some coders are too lazy to always do this the right way.
	 * @param manager
	 * @throws IOException
	 */
	public static void parseStatusFileCorrectly(PokemonStatusFileManager manager)
		throws IOException {

		InputStream statusFile = null;
		try {
			statusFile = manager.getStatusFileInputStream();
			readFrom(statusFile);
		} finally {
			// carefully close the resource
			if(statusFile != null) {
				try {
					statusFile.close();
				} catch(Exception e) {
					System.err.println(&quot;Error closing statusFile!&quot;);
					e.printStackTrace(System.err);
				}
			}
		}
	}

	static void readFrom(InputStream statusFile) throws IOException {
		// do the reading here...
	}
}
</pre>
<p>So this produces a classic Pokémon problem: everyone who interacts with the StatusFileManager has to do proper resource handling.  Now imagine that this is an important lock instead of just a file handle: this Pokémon problem could cause deadlock (which would be bad).</p>
<p>So how do we fix this? <a href="http://en.wikipedia.org/wiki/Visitor_pattern">The Visitor Pattern</a>.</p>
<h3>Solving the Pokémon problem with the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a></h3>
<p>The Visitor Pattern is a potent weapon in fighting the Pokémon problem: it allows you to fully encapsulate access to a resource by injecting into the places it&#8217;s needed but preserving overall control of the resource in the code that &#8220;owns&#8221; the resource.  Classically used for controlling things like iteration order, here the visitor pattern is applied as a form of <a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> to enable lifecycle management.</p>
<p>The visitor pattern as applied to resource management is fairly straightforward:</p>
<ol>
<li>Define an interface, <em>ResourceVisitor</em> with one method, <em>visit(Resource r)</em> (where <em>Resource</em> is the type of resource we&#8217;re managing.</li>
<li>Define the resource manager with a method that takes a <em>ResourceVisitor</em> as a parameter.  Manage the lifecycle of the resource and call <em>ResourceVisitor.visit(r)</em> when appropriate, handling all initialization, error-handling and cleanup.</li>
</ol>
<p>Here&#8217;s our re-spin of the status file manager class.  You&#8217;ll notice that we&#8217;ve moved the resource handling code from the correct example above and encapsulated it in the visitor pattern:</p>
<pre class="brush: java; title: ; notranslate">

public class UnPokemonStatusFileManager {

	/**
	 * Visitor interface implemented by callers wishing to
	 * interact with the status file.
	 */
	public static interface StatusFileVisitor {
		public void visitStatusFile(InputStream statusFile) throws IOException;
	}

	final File statusFile;

	public UnPokemonStatusFileManager(File statusFilePath) {
		this.statusFile = statusFilePath;
	}

	/**
	 * Note that this method is now private.
	 */
	private InputStream getStatusFileInputStream() throws FileNotFoundException {
		return new FileInputStream(this.statusFile);
	}

	/**
	 * Here's the method that takes the visitor and
	 * fully encapsulates the lifecycle of the status file.
	 */
	public void parseStatusFile(StatusFileVisitor parser)
	throws IOException {
		InputStream statusFile = this.getStatusFileInputStream();
		try {
			parser.visitStatusFile(statusFile);
		} finally {
			// carefully close the resource
			try {
				statusFile.close();
			} catch(Exception e) {
				System.err.println(&quot;Error closing statusFile!&quot;);
				e.printStackTrace(System.err);
			}
		}
	}
}
</pre>
<p>Now that we&#8217;ve encapsulated the complexity of the resource handling the <em>UnPokemonStatusFileManager</em> class, code that needs to access the status file can be written in a highly correct manner without much work.</p>
<pre class="brush: java; title: ; notranslate">

public class UnPokemonParseStatusFile {

	public static void parseStatusFile(UnPokemonStatusFileManager statusFileManager)
		throws IOException {

		// generate anonymous visitor to do the processing
		StatusFileVisitor visitor = new StatusFileVisitor() {
			public void visitStatusFile(InputStream statusFile) throws IOException {
				readFrom(statusFile);
			}
		};
		statusFileManager.parseStatusFile(visitor);
	}

	static void readFrom(InputStream statusFile) throws IOException {
		// do the reading here...
	}
}
</pre>
<p>By encapsulating the full lifecycle of the status file in the visitor pattern, I&#8217;ve ensured that it&#8217;s always accessed properly.  If I change the place where we store status to be a database rather than a file, nothing needs to change except this one class; the calling code remains the same.</p>
<p>We now have easy re-factoring, no resource leaks, and have simplified calling code.  And finally: there are no new bugs to be introduced by callers that aren&#8217;t sure how to use our resource.  Looks like we caught &#8216;em all!</p>
<h2>Wrapping It All Up</h2>
<p>So there it is, your new piece of jargon: The Pokémon Problem anti-pattern.  You heard it here first!  Please post any other great examples to the comments section on this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.palantirtech.com/2009/03/19/the-pokemon-problem/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

