<?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>Jayway Team Blog &#187; api</title>
	<atom:link href="http://blog.jayway.com/tag/api/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Rewriting a Public Cocoa Touch API</title>
		<link>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/</link>
		<comments>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/#comments</comments>
		<pubDate>Tue, 25 May 2010 14:58:07 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[cocoa touch]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5638</guid>
		<description><![CDATA[Cocoa Touch added API for presenting a view controller in a popup bubble in iPhone OS 3.2, the responsible class is named UIPopoverController. One would guess that this new class is a subclass of UIViewController, just like UINavigationController is, but that is not the case. One would also guess that in functionality many ideas for [...]]]></description>
			<content:encoded><![CDATA[<p>Cocoa Touch added API for presenting a view controller in a popup bubble in iPhone OS 3.2, the responsible class is named <code>UIPopoverController</code>. One would guess that this new class is a subclass of <code>UIViewController</code>, just like <code>UINavigationController</code> is, but that is not the case. One would also guess that in functionality many ideas for displaying a view controller as modal controller would have been moved over to displaying a view controller as a popover controller, but that is not the case either.</p>
<h3>Modal View Controllers are Easy</h3>
<p>Displaying a modal view controller is quite straight forward as this small example shows:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  [self presentModalViewController:vc animated:YES];
  [vc release];
}</pre>
<h3>Popover View Controllers Can be Complex</h3>
<p>Displaying the same details view controller in a popover on iPad is not quite as straight forward:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details fromBarButtonItem:(UIBarButtonItem*)item {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  self.popoverController = [[[UIPopoverController alloc]
                                  initWithContentViewController:vc] autorelease];
  self.popoverController.delegate = self;
  [self.popoverController presentPopoverFromBarButtonItem:item
                                 permittedArrowDirections:UIPopoverArrowDirectionAny
                                                 animated:YES];
  [vc release];
}

-(void)popoverControllerDidDismissPopover:(UIPopoverController*)popoverController {
  self.popoverController = nil;
}</pre>
<p>As you see presenting a popover requires an extra object instance, this instance is not automatically retained while presenting the popover, like a modal view controller is, so the instance must be saved somewhere. In this example I saved the instance as a property. Notice that I also register as a delegate for the popover in order to remove this instance when the popover is dismissed. Here is another detail that is not obvious; this delegate callback is <strong>only</strong> called if user action dismisses the popover, not if you programmatically dismiss the popover. In the end using popovers quite quickly introduces a lot of code, and also coupling between view controllers for no other reason but to manage the popover instance.</p>
<p>Would it not be nice if you could instead do like this, and be done with it:</p>
<pre class="brush:objc">-(void)showDetails:(CWDetails*)details fromBarButtonItem:(UIBarButtonItem*)item {
  UIViewController* vc = [[CWDetailsViewController alloc] initWithDetails:details];
  [self presentPopoverViewController:vc fromBarButtonItem:item animated:YES];
  [vc release];
}</pre>
<p>In fact what we want is to have these methods added to the public API of <code>UIViewController</code>:</p>
<pre class="brush:objc">@interface UIViewController (CWPopover)

@property (nonatomic, retain, readonly) NSSet* visiblePopoverControllers;

-(void)presentPopoverViewController:(UIViewController*)controller
                  fromBarButtonItem:(UIBarButtonItem *)item
                           animated:(BOOL)animated;
-(void)presentPopoverViewController:(UIViewController*)controller
                           fromView:(UIView *)view
                           animated:(BOOL)animated;

-(void)dismissPopoverController:(UIViewController*)controller animated:(BOOL)animated;
-(void)dismissAllPopoverControllersAnimated:(BOOL)animated;

-(void)setContentSize:(CGSize)size forViewInPopoverAnimated:(BOOL)animated;

@end
</pre>
<h3>But That Requires Rewriting Existing Classes?</h3>
<p>Yes it does, in an ideal world we want new methods and properties on the existing <code>UIViewController</code> class, and all subclasses, just as if Apple had put them there. This can easily be done thanks to the dynamic nature of Objective-C.</p>
<p>The view controller that is going to present other view controllers in a  popover needs to have access to all <code>UIPopoverController</code> instances currently visible. The view controllers that are going to be presented in a popover need to have access to their container <code>UIPopoverController</code>, and for consistency with modal view controller its parent view controller. </p>
<p>Categories can only add and replace methods on an existing class, not modify instance variables. So we need to store this information in another way. I choose to tuck them away in a helper class called <code>CWViewControllerPopoverHelper</code>. With this small interface:</p>
<pre class="brush:objc">@interface CWViewControllerPopoverHelper : NSObject {
@private
    UIViewController* parentViewController;
    UIPopoverController* containerPopoverController;
    NSMutableSet* visiblePopoverControllers;
}
@property (nonatomic, assign) UIViewController* parentViewController;
@property (nonatomic, assign) UIPopoverController* containerPopoverController;
@property (nonatomic, retain) NSMutableSet* visiblePopoverControllers;

@end</pre>
<p>The implementation is just synthesized properties, so no need to duplicate that one here.</p>
<p>So now all we do is to stuff one instance of <code>CWViewControllerPopoverHelper</code> into a global map using the <code>UIViewController</code> as key for each view controller that needs these extra <em>instance information</em>.</p>
<h3>Fetching the Popover Helper</h3>
<p>Let's implement a helper method that lazily creates a <code>CWViewControllerPopoverHelper</code> instance and puts it into the global map when needed. This way any view controller that do not need to support popovers will never be bothered, and those who do manage popovers gets one instance with no fuzz:</p>
<pre class="brush:objc">static NSMutableDictionary* popoverHelpers = nil;

-(CWViewControllerPopoverHelper*)popoverHelper;
{
    NSValue* key = [NSValue valueWithPointer:self];
    if (popoverHelpers == nil) {
        popoverHelpers = [[NSMutableDictionary alloc] initWithCapacity:16];
    }
    CWViewControllerPopoverHelper* helper = [popoverHelpers objectForKey:key];
    if (helper == nil) {
        helper = [[[CWViewControllerPopoverHelper alloc] init] autorelease];
        [popoverHelpers setObject:helper forKey:key];
    }
    return helper;
}</pre>
<h3>Proper Memory Management</h3>
<p>There is one problem with storing the extra information in a global map; no view controller would ever be released from memory, since the map will hold on to the references. No problem, lets not use the actual view controller instance as a key, but a <code>NSValue</code> with the pointer to the instance. This solves the problem of releasing objects, but also means that the map will contain dangling pointers to released objects. We need to remove the dangling pointers whenever a <code>UIViewController</code> is deallocated.</p>
<p>Subclassing is not an option, since it would defeat our purpose of requiring the public API. It turns out we can replace the <code>-[UIViewController dealloc]</code> method with our own, and still call the original implementation. Each class and category that is loaded into the Objective-C run-time will call their own method <code>+[? load]</code> method, it is the public hook for further modifying a class or category before use. We want to use this hook to replace the default deallocation method with our own:</p>
<pre class="brush:objc">+(void)load;
{
    Method m1 = class_getInstanceMethod(self, @selector(dealloc));
    Method m2 = class_getInstanceMethod(self, @selector(cwPopoverDealloc));
    method_exchangeImplementations(m1, m2);
    m1 = class_getInstanceMethod(self, @selector(parentViewController));
    m2 = class_getInstanceMethod(self, @selector(cwPopoverParentViewController));
    method_exchangeImplementations(m1, m2);
}</pre>
<p>As a bonus we also replace <code>-[UIViewController parentViewController]</code>, to return the parent as would be expected for anyone who has ever presented a modal view controller. The implementations of our overrides are just as short and sweet:</p>
<pre class="brush:objc">-(void)cwPopoverDealloc;
{
    [self dismissAllPopoverControllersAnimated:NO];
    NSValue* key = [NSValue valueWithPointer:self];
    [popoverHelpers removeObjectForKey:key];
    [self cwPopoverDealloc];
}

-(UIViewController*)cwPopoverParentViewController;
{
    UIViewController* parent = [self popoverHelper].parentViewController;
    if (parent == nil) {
        parent = [self cwPopoverParentViewController];
    }
    return parent;
}</pre>
<h3>Wrapping Up</h3>
<p>From here on it is just a tedious work to implement all 50 more lines of code needed to actually present the popovers, the first method as an example:</p>
<pre class="brush:objc">-(void)presentPopoverViewController:(UIViewController*)controller
                  fromBarButtonItem:(UIBarButtonItem *)item
                           animated:(BOOL)animated;
{
    UIPopoverController* pc = [[[UIPopoverController alloc]
                                initWithContentViewController:controller] autorelease];
	[self addPopoverViewController:pc passthroughViews:views];
    [pc presentPopoverFromBarButtonItem:item
               permittedArrowDirections:UIPopoverArrowDirectionAny
                               animated:animated];
}</pre>
<p>The rest of the implementation, and a few other nice to have methods can be <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2010/05/UIViewController+CWPopover.zip'>downloaded here</a>.</p>
<h3>Conclusions</h3>
<p>The dynamic nature of Objective-C means that you can rewrite any existing API to suit your needs, without having access to the original source code. Sometimes just to add a new utility function where it belongs; a <em>"sort by first name"</em> method should probably be added to the actual <em>people collection</em> class, not as a spurious utility class.</p>
<p>Or as shown in this example to make a public API more convenient to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/05/25/rewriting-a-public-cocoa-touch-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Google Collections</title>
		<link>http://blog.jayway.com/2009/10/22/google-collections/</link>
		<comments>http://blog.jayway.com/2009/10/22/google-collections/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 12:10:41 +0000</pubDate>
		<dc:creator>Sune Simonsen</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[bimap]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[multimap]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[ordering]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2052</guid>
		<description><![CDATA[Google Collections is a natural evolution from the standard collections API in Java, bringing a much broader range of functionality to the existing collections and also providing several new collections for its users. The library plays nice with the standard collections and uses existing functionality where possible. Here is a list of useful facts before [...]]]></description>
			<content:encoded><![CDATA[<p>
Google Collections is a natural evolution from the standard collections API in Java, bringing a much broader range of functionality to the existing collections and also providing several new collections for its users. The library plays nice with the standard collections and uses existing functionality where possible.
</p>
<p>
Here is a list of useful facts before we throw ourselves into the code.
</p>
<ul>
<li>Open Source Apache 2 library </li>
<li>Hosted at Google Code: <a title="Project page" href="http://google-collections.googlecode.com/">http://google-collections.googlecode.com/</a></li>
<li>Requires Java 1.5</li>
<li>1.0 Release Candidate 3 now</li>
<li>25,000 unit tests</li>
<li>Used by Google in production</li>
</ul>
<h3>Immutable Collections</h3>
<p>
A big part of the collections library is focused on immutability, the reason for this is the increased demand for concurrent code in order to be able to utilize the ever increasing number of cores in modern computers.
</p>
<p>
Immutable data are thread-safe because it can never be changed and can therefore be shared between multiple threads without worrying. This is a huge improvement because of the complexity involved writing thread safe code that uses mutable data. furthermore immutable data can be handed to untrusted code without worrying about the data being changed by the untrusted code, this really helps sustaining the security boundaries of your system.
</p>
<p>
Another benefit of using immutable collections is that they are in most cases more memory efficient and perform better than the regular collections.
</p>
<p>
In a way it was also possible to create immutable collections with the standard Java API, as an example a set could be made immutable the following way:
</p>
<pre class="java">&nbsp;
Set&lt;Integer&gt; numbers = <span style="color: #000000; font-weight: bold;">new</span> TreeSet&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AArrays+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Arrays</span></a>.<span style="color: #006600;">asList</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
Set&lt;Integer&gt; immutableNumbers = <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">unmodifiableSet</span><span style="color: #66cc66;">&#40;</span>numbers<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
With Google Collections it would look the following way:
</p>
<pre class="java">&nbsp;
ImmutableSet&lt;Integer&gt; immutableNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
There are several things that are better in the version using Google Collections. You only need to know about the <i>ImmutableSet</i> class, where as in the standard Java version, four classes are combined to achieve the same effect, that is just confusing. When using the <i>new</i> keyword to construct generic classes, the generic type can't be inferred from the constructor arguments, this limitation is not present for methods. Google Collections uses static factory methods to create their collections meaning the generic type will be inferred in this case and therefore turning the code noise down. The third benefit is that the immutable collections are guaranteed to be immutable where as an unmodifiable collection is just an immutable view of the collection and can be changed by code holding a reference to the actual collection. The last benefit is that the information about immutability is captured in the type and clients of this type therefore will be able to count on that the collection is immutable, which means that defensive copying is unnecessary. Be aware that it is only the collection that is promised to be immutable, if the objects contained in the collection are not immutable they can still be changed. Notice that <i>ImmutableSet</i> implements the <i>Set</i> interface so it can be used seamlessly with existing code.
</p>
<p>
Those of you who are familiar with functional programming languages, may expect, that mutating methods like <i>add</i> returns a modified copy of the collection. But in order to implement the standard Java collections interfaces, this is not possible, so instead they just throw an exception. You can of cause still combine existing immutable collections into new ones. If you for example want to create the union of two sets, you can do it the following way:
</p>
<pre class="java">&nbsp;
ImmutableSet&lt;Integer&gt; lowNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span><span style="color: #66cc66;">&#41;</span>;
ImmutableSet&lt;Integer&gt; highNumbers = ImmutableSet.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span>,<span style="color: #cc66cc;">7</span>,<span style="color: #cc66cc;">8</span>,<span style="color: #cc66cc;">9</span>,<span style="color: #cc66cc;">10</span>,<span style="color: #cc66cc;">11</span>,<span style="color: #cc66cc;">12</span>,<span style="color: #cc66cc;">13</span>,<span style="color: #cc66cc;">14</span>,<span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span>;
SetView&lt;Integer&gt; union = Sets.<span style="color: #006600;">union</span><span style="color: #66cc66;">&#40;</span>lowNumbers, highNumbers<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
Notice how we use the static <i>union</i> method on the <i>Sets</i> class to create a new <i>SetView</i> based on the two given sets. The <i>SetView</i> is an unmodifiable implementation of the standard <i>Set</i> interface but can change if the underlying collections changes. Google Collections provide similar convenience classes for working with all the popular collections interfaces from the standard Java API, improving your productivity a lot. </p>
<p>Numerous immutable collections exist in the library, for more information see the <a title="API documentation" target="blank" href="http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html">API documentation</a>.</p>
<h3>New collections types</h3>
<p>
Google Collections also provides implementations of a few collections that is not included in the standard Java. These collections can be very useful in special cases.
</p>
<h4>Multisets</h4>
<p>
Multiset is a very useful collection for collecting statistic data of some kind. The collection is basically just a set where a count of how many instances has been added of each element is maintained. So if we as an example want to count the occurrences of each number in a list of numbers it can be done the following way.
</p>
<pre class="java">&nbsp;
ImmutableList&lt;Integer&gt; numbers = ImmutableList.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#41;</span>;
Multiset&lt;Integer&gt; multiset = TreeMultiset.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span>numbers<span style="color: #66cc66;">&#41;</span>;
multiset.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Decreasing the count for 0 by 1</span>
multiset.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// Increasing the count for 1 by 4</span>
&nbsp;</pre>
<p>
The resulting multiset after adding the list of numbers contains to following information:</p>
<ul>
<li>0 has 1 occurrences</li>
<li>1 has 6 occurrences</li>
<li>2 has 3 occurrences</li>
<li>3 has 3 occurrences</li>
</ul>
<p>
Numerous implementations of the Multiset exists, so it is a good idea to match your requirement against the capabilities of the different implementations before choosing one.
</p>
<h4>Multimaps</h4>
<p>
Have you ever implemented a Map where each key could be associated to a list of values - that's exactly what a Multimap is. This is useful in many cases, for example indexing. To show the functionality I'll index fruits by colors. The <i>Fruit</i> class is just a class with a name and a color and the fruits collection contains banana, strawberry, cucumber, kiwifruit, tomato and lemon. First we create a new multimap for the color index, then we look through all the fruits and add them to the color index using the color of the fruit as index. After we have constructed the index, we get a collection of red fruits using the <i>get</i> method. And finally, we assert that a tomato is a red fruit.
</p>
<pre class="java">&nbsp;
Multimap&lt;Color, Fruit&gt; colorIndex = HashMultimap.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span>Fruit fruit : fruits<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    colorIndex.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>fruit.<span style="color: #006600;">getColor</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, fruit<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
Collection&lt;Fruit&gt; redFruits = colorIndex.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AColor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Color</span></a>.<span style="color: #006600;">RED</span><span style="color: #66cc66;">&#41;</span>;
assertTrue<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Tomato is a red fruit&quot;</span>, redFruits.<span style="color: #006600;">contains</span><span style="color: #66cc66;">&#40;</span>TOMATO<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h4>BiMap</h4>
<p>
A <i>BiMap</i> is an implementation of a bidirectional map, that is a map where a one-to-one relation between each key and value exists. The <i>BiMap</i> is special because it is capable of producing the inverse mapping using the <i>inverse</i> method. Bidirectional maps are also useful for indexing in cases where an one-to-one relationship exists and you don't want the relationship encoded in the objects. As an example we will look at mapping numbers to their names and back again.
</p>
<pre class="java">&nbsp;
ImmutableBiMap&lt;Integer, String&gt; biMap = ImmutableBiMap.<span style="color: #006600;">of</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #ff0000;">&quot;Zero&quot;</span>, <span style="color: #cc66cc;">1</span>, <span style="color: #ff0000;">&quot;One&quot;</span>,
        <span style="color: #cc66cc;">2</span>, <span style="color: #ff0000;">&quot;Two&quot;</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #ff0000;">&quot;Three&quot;</span><span style="color: #66cc66;">&#41;</span>;
assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;2 should be mapped to Two&quot;</span>, <span style="color: #ff0000;">&quot;Two&quot;</span> , biMap.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
We can easily create a mapping between the numbers and their names using the <i>of</i> method on the <i>ImmutableBiMap</i> implementation. As with the <i>Multisets</i> and <i>Multimaps</i> numerous implementations exists to fit your exact needs.
</p>
<p>
For a <i>BiMap</i> we can get the inverse <i>BiMap</i> the following way:
</p>
<pre class="java">&nbsp;
BiMap&lt;String, Integer&gt; inverseBiMap = biMap.<span style="color: #006600;">inverse</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Two should be mapped to 2&quot;</span>, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a>.<span style="color: #006600;">valueOf</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>,
        inverseBiMap.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Two&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<h3>Ordering</h3>
<p>
If you ever have struggled with implementing Java's <i>Comparator</i> interface the <i>Ordering</i> class from Google Collections is you friend. The <i>Ordering</i> class provides you with everything you need for handling ordering of collections. Furthermore the <i>Ordering</i> class implements the <i>Comparator</i> interface to handle backwards compatibility. If you, for example, want to sort the fruits earlier mentioned first by color then by name it can be done the following way.
</p>
<pre class="java">&nbsp;
Function&lt;Fruit, Color&gt; getColorFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Fruit, Color&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AColor+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Color</span></a> apply<span style="color: #66cc66;">&#40;</span>Fruit from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from.<span style="color: #006600;">getColor</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Function&lt;Fruit, String&gt; getNameFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Fruit, String&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> apply<span style="color: #66cc66;">&#40;</span>Fruit from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from.<span style="color: #006600;">getName</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Ordering&lt;Fruit&gt; colorOrdering = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">onResultOf</span><span style="color: #66cc66;">&#40;</span>getColorFunction<span style="color: #66cc66;">&#41;</span>;
Ordering&lt;Fruit&gt; nameOrdering = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">onResultOf</span><span style="color: #66cc66;">&#40;</span>getNameFunction<span style="color: #66cc66;">&#41;</span>;
&nbsp;
Ordering&lt;Fruit&gt; colorAndNameOrdering = colorOrdering.<span style="color: #006600;">compound</span><span style="color: #66cc66;">&#40;</span>nameOrdering<span style="color: #66cc66;">&#41;</span>;
&nbsp;
ImmutableSortedSet&lt;Fruit&gt; sortedFruits = ImmutableSortedSet.<span style="color: #006600;">orderedBy</span><span style="color: #66cc66;">&#40;</span>
        colorAndNameOrdering<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addAll</span><span style="color: #66cc66;">&#40;</span>fruits<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">build</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span>Joiner.<span style="color: #006600;">on</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;, &quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">join</span><span style="color: #66cc66;">&#40;</span>sortedFruits<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
Prints out:</p>
<pre>
Green Cucumber, Green Kiwifruit, Red Strawberry, Red Tomato, Yellow Banana,
Yellow Lemon
</pre>
</p>
<p>
First I create the ordering of fruits by color. The <i>Color</i> enumeration implements <i>Comparable</i>, so we just want to promote the ordering of fruits to use the natural order of the <i>Color</i> class. To do this we create a natural order on the result of the function that retrieves the color from a fruit. To verify that the ordering works, I create a new <i>ImmutableSortedSet</i> with the ordering we just created and print the result. Notice that it is necessary to used the <a href="http://en.wikipedia.org/wiki/Builder_pattern" title="Builder pattern">builder pattern</a> in order to create the <i>ImmutableSortedSet</i> with a specified order.
</p>
<p>
The ordering on fruit names is similar to the way we order by  colors except we use a function that retrieves the name of the fruit.
</p>
<p>
When we have the two orderings we can make a compound ordering by using the <i>compound</i> method on the ordering that should be applied first. A compound ordering applies each ordering in turn to achieve a hierarchical ordering. In this case the color-ordering is first applied, if the objects are equal, according to that ordering, the naming-ordering is applied.
</p>
<p>
Another use case of the <i>Ordering</i> class is sorting <i>Iterable</i> classes where elements are not guaranteed to be unique. Normally you would have to first convert the iterable to a list and then use the <i>sort</i> method on the <i>Collections</i> class to sort the elements. Consider the case of sorting an iterable of numbers in reverse order, this can be done the following way in standard Java:
</p>
<pre class="java">&nbsp;
List&lt;Integer&gt; sortedNumbers = <span style="color: #000000; font-weight: bold;">new</span> ArrayList&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span>numberIterable<span style="color: #66cc66;">&#41;</span>;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">sort</span><span style="color: #66cc66;">&#40;</span>sortedNumbers, <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ACollections+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Collections</span></a>.<span style="color: #006600;">reverseOrder</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
The same result can be achieved with Google Collections the following way:
</p>
<pre class="java">&nbsp;
List&lt;Integer&gt; sortedNumbers = Ordering.<span style="color: #006600;">natural</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">reverse</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">sortedCopy</span><span style="color: #66cc66;">&#40;</span>numberIterable<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
This doesn't seem like a big difference. But in the standard Java example involves three different classes and the generics is specified two times.
</p>
<h3>Iterables and Iterators</h3>
<p>
Iterables and iterators are a powerful abstraction that lets you handle streams of data in an uniform way. But the standard Java library doesn't provide you with  many tools to handle these types. Google Collections includes two classes with several convenience methods to work on these types. The two classes contains the  same methods so I'll only focus on iterables.
</p>
<p>
Imagine that you are given an iterable of numbers should find all the even numbers, square them and return a new iterable of the result. Of course this should be done  without reading all the numbers in the given iterable. In standard Java you would need to implement two iterators and two iterables in order to achieve this. In  Google Collection it can be done the following way:
</p>
<pre class="java">&nbsp;
Predicate&lt;Integer&gt; evenPredicate = <span style="color: #000000; font-weight: bold;">new</span> Predicate&lt;Integer&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">boolean</span> apply<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> input<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> input % <span style="color: #cc66cc;">2</span> == <span style="color: #cc66cc;">0</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Iterable&lt;Integer&gt; evenNumbers = Iterables.<span style="color: #006600;">filter</span><span style="color: #66cc66;">&#40;</span>numbers, evenPredicate<span style="color: #66cc66;">&#41;</span>;
&nbsp;
Function&lt;Integer, Integer&gt; squareFunction = <span style="color: #000000; font-weight: bold;">new</span> Function&lt;Integer, Integer&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> apply<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Integer</span></a> from<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> from * from;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
Iterable&lt;Integer&gt; squareOfEvenNumbers = Iterables.<span style="color: #006600;">transform</span><span style="color: #66cc66;">&#40;</span>evenNumbers,
        squareFunction<span style="color: #66cc66;">&#41;</span>;
&nbsp;</pre>
<p>
First we create a predicate function that only accepts even numbers and filters the given numbers by this predicate function. Notice this is done lazily so the original iterable is not touched, which means at no time is a collection containing all the results constructed and stored in memory. All the methods on <i>Iterables</i> and <i>Iterators</i> classes is as lazy as possible.
</p>
<p>
Then we create a <i>square</i> function and apply it to the iterable of even numbers giving us a new iterable with the squared even numbers.
</p>
<p>
It is important to understand that the predicate and <i>square</i> functions will first be applied when the iterable is used to iterate through the squared even numbers.
</p>
<h3>Conclusion</h3>
<p>
In my opinion Google Collection will definitely improve your code, making it more readable and save you from creating your own error-prone implementation of the functionality already provided and tested by Google. I think that it is especially good that the library extends the standard library in a non intrusive way, instead of creating a parallel collection library. This also means that you can choose to use only the convenience classes and not spreading Google specific types all over your system if that worries you.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/10/22/google-collections/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Making APIs usable</title>
		<link>http://blog.jayway.com/2006/10/01/making-apis-usable/</link>
		<comments>http://blog.jayway.com/2006/10/01/making-apis-usable/#comments</comments>
		<pubDate>Sun, 01 Oct 2006 14:56:49 +0000</pubDate>
		<dc:creator>Mattias Ask</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[User Experience]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3776</guid>
		<description><![CDATA[All APIs have end-users. How and whether these users use a certain API depends on how useful the API is to them. This in turn is determined by what problem the API solves, how easy it is to learn and understand, and how easy it is to use. This article will give some (perhaps obvious) [...]]]></description>
			<content:encoded><![CDATA[<p><strong>All APIs have end-users. How and whether these users use a certain API depends on how useful the API is to them. This in turn is determined by what problem the API solves, how easy it is to learn and understand, and how easy it is to use. This article will give some (perhaps obvious) pointers on how to improve ease-of-learning and ease-of-use of your API. </strong></p>
<p>Usability is the science of usage which means that usability rules and laws apply to rich clients, web applications, paper forms, furniture, milk cartons, tools etc. It needs to be taken into consideration whenever there is a human end-user. If not, the product will be designed to be specifically useful to the designer. </p>
<h2>Know your user </h2>
<p>The first question to ask yourself is: Who is going to use your API? If you know that<br />
then you are half way to the bank. Why? Simply because you know what your users<br />
know and want, and thus you can give them what they need.<br />
If the user has a list of objects and wants to remove objects which already exists in<br />
another list, your API could look something like this: </p>
<pre>CustomList myList = getMyList();
CustomList yourList = getYourList();
myList.removeSharedItems(yourList);
</pre>
<p>“myList.removedSharedItems(yourList);” describes what the function does to your<br />
list, and is suited for most any programmer. If, on the other hand, you <strong>know</strong> that<br />
your users are working with <strong>set theory</strong>, you would probably want to do something<br />
like this: </p>
<pre>CustomList myList = getMyList();
CustomList yourList = getYourList();
myList.toRelativeComplement(yourList);
</pre>
<h2>Let the API be self-documenting </h2>
<p>Remember that when it comes to learning or getting started with an API, many pro-<br />
grammers simply rely on the AutoCompletion-function in their IDE. If they don’t<br />
get it from looking at that, they might turn to the documentation, or simply turn to<br />
another competing API. So don’t take naming your classes and methods lightly.<br />
In the previous example both </p>
<pre>myList.removeSharedItems(yourList);</pre>
<p>..and: </p>
<pre>myList.toRelativeComplement(yourList);</pre>
<p>..mutate myList. This is visualised by using “remove” and “to” which both refer<br />
to the myList-object. If for example “myList.toRelativeComplement (yourList);”<br />
didn’t have the word “to”, the user wouldn’t know if it returns the relative comple-<br />
ment or if it mutates myList to it.<br />
In SpringFramework, self-explanatory class names such as “BatchPreparedState-<br />
mentSetter” (an interface for a prepared statement setters used during batch up-<br />
dates) are widely used. The only risk with this is that class-, interface- and method<br />
names can get rather long, resulting in poorer readability. Explain what it does but<br />
be as precise as possible and don’t take it to the extreme. </p>
<h2>Don’t present the underlying implementation </h2>
<p>The API should limit itself to what the user needs to know; no more, no less. The<br />
names of classes, interfaces and methods should describe what they do and what<br />
they are used for; not how they do it. Why force the user to know what the underly-<br />
ing implementation does if they don’t need to know? Open-source your code and<br />
give the user the choice to see how it is done instead of forcing it on them.<br />
Java.io.Properties.loadFromXML takes an InputStream. This means that to load<br />
properties from XML the following needs to be done. </p>
<pre>File myProps = new File(“.\\MyProps.xml”);
FileInputStream is = new FileInputStream(myProps);
Properties p = new Properties();
//void loadFromXML(InputStream in)
p.loadFromXML(is);
</pre>
<p>The fact that loadFromXML takes an InputStream describes what the method does.<br />
A better solution would be to look at SpringFramework’s Resource solution. There<br />
they have a common interface called “Resource” which is implemented by every-<br />
thing from FileSystemResource to InputStreamResource. If java.io.File were to im-<br />
plement such an interface, a solution could simply be: </p>
<pre>Properties p = new Properties();
//void loadFromXML(Resource xmlResource)
p.loadFromXML(new File(“.\\MyProps.xml”));</pre>
<p>In this case the user of the API doesn’t have to think about <strong>in what way</strong> the XML<br />
will be read; just that it <strong>will be</strong> read. </p>
<h2>Think of logical mapping</h2>
<p>The methods of a class (name and responsibility) must map well to the classes<br />
name; input and output of a method must map the responsibility of the method and<br />
so on. If this is done, the user will be able to use the API intuitively, and learn and<br />
understand how to use it without any documentation. </p>
<pre>//Bad mapping in Calendar
void setTime(Date date)
//Better mapping
void setTime(Time time)
</pre>
<h2>Limit the number of options </h2>
<p>If you have something in your API that can be done in two different ways, choose<br />
one. Don’t give the user an ambiguous API with features that are so similar that it is<br />
confusing, and force them to go to the documentation or choose by chance. </p>
<pre>myCalendar.add(Calendar.DAY_OF_WEEK,7);
//...differs from...
myCalendar.roll(Calendar.DAY_OF_WEEK,7);
//...in what way?
</pre>
<h2>Avoid methods and classes that do<br />
different things in different object states<br />
</h2>
<p>Separate your domain entities in such a way that they overlap as little as possible.<br />
This is basic OO and should be common sense, but it is a common problem. Java.<br />
io.File has exactly this problem. An object of java.io.File can be a File or a Directory.<br />
If the object is created from the path of a directory it is a directory. This gives the<br />
possibility to write, among other things, the following illogical code: </p>
<pre>File myFile = new File(“.\\MyFile.xml”);
boolean dirMade = myFile.mkDir();
</pre>
<p>A better solution would be if File were structured something like: </p>
<pre>interface FileSystemElement extends Resource{
   //...
}
class abstract AbstractFileSystemElement implements FileSystemElement{
   //...
} 

class File extends AbstractFileSystemElement{
   //...
} 

class Directory extends AbstractFileSystemElement{
   //...
} </pre>
<h2>Summary </h2>
<p>The most important thing to remember is that there is a human user at the other<br />
end of an API. If you remember this you will create better APIs. The pointers in this<br />
article simply scratch the surface of what could be done to improve your APIs. One<br />
thing that would result in great improvements is if you found a couple of users and<br />
user-tested the solution. (<a href="http://en.wikipedia.org/wiki/Usability_testing">http://en.wikipedia.org/wiki/Usability_testing</a>). </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2006/10/01/making-apis-usable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
