Skip to content

Software Development Blogs: Programming, Software Testing, Agile Project Management

Methods & Tools

Subscribe to Methods & Tools
if you are not afraid to read more than one page to be a smarter software developer, software tester or project manager!

Feed aggregator

AppCompat v21 — Material Design for Pre-Lollipop Devices!

Android Developers Blog - Sat, 11/08/2014 - 03:14

By Chris Banes, Android Developer Relations

The Android 5.0 SDK was released last Friday, featuring new UI widgets and material design, our visual language focused on good design. To enable you to bring your latest designs to older Android platforms we have expanded our support libraries, including a major update to AppCompat, as well as new RecyclerView, CardView and Palette libraries.

In this post we'll take a look at what’s new in AppCompat and how you can use it to support material design in your apps.

What's new in AppCompat?

AppCompat (aka ActionBarCompat) started out as a backport of the Android 4.0 ActionBar API for devices running on Gingerbread, providing a common API layer on top of the backported implementation and the framework implementation. AppCompat v21 delivers an API and feature-set that is up-to-date with Android 5.0

In this release, Android introduces a new Toolbar widget. This is a generalization of the Action Bar pattern that gives you much more control and flexibility. Toolbar is a view in your hierarchy just like any other, making it easier to interleave with the rest of your views, animate it, and react to scroll events. You can also set it as your Activity’s action bar, meaning that your standard options menu actions will be display within it.

You’ve likely already been using the latest update to AppCompat for a while, it has been included in various Google app updates over the past few weeks, including Play Store and Play Newsstand. It has also been integrated into the Google I/O Android app, pictured above, which is open-source.

Setup

If you’re using Gradle, add appcompat as a dependency in your build.gradle file:

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}
New integration

If you are not currently using AppCompat, or you are starting from scratch, here's how to set it up:

  • All of your Activities must extend from ActionBarActivity, which extends from FragmentActivity from the v4 support library, so you can continue to use fragments.
  • All of your themes (that want an Action Bar/Toolbar) must inherit from Theme.AppCompat. There are variants available, including Light and NoActionBar.
  • When inflating anything to be displayed on the action bar (such as a SpinnerAdapter for list navigation in the toolbar), make sure you use the action bar’s themed context, retrieved via getSupportActionBar().getThemedContext().
  • You must use the static methods in MenuItemCompat for any action-related calls on a MenuItem.

For more information, see the Action Bar API guide which is a comprehensive guide on AppCompat.

Migration from previous setup

For most apps, you now only need one theme declaration, in values/:

values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- Set AppCompat’s actionBarStyle -->
    <item name="actionBarStyle">@style/MyActionBarStyle</item>

    <!-- Set AppCompat’s color theming attrs -->
    <item name=”colorPrimary”>@color/my_awesome_red</item>
    <item name=”colorPrimaryDark”>@color/my_awesome_darker_red</item>
    
    <!-- The rest of your attributes -->
</style>

You can now remove all of your values-v14+ Action Bar styles.

Theming

AppCompat has support for the new color palette theme attributes which allow you to easily customize your theme to fit your brand with primary and accent colors. For example:

values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- colorPrimary is used for the default action bar background -->
    <item name=”colorPrimary”>@color/my_awesome_color</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name=”colorPrimaryDark”>@color/my_awesome_darker_color</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name=”colorAccent”>@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->
    
</style>

When you set these attributes, AppCompat automatically propagates their values to the framework attributes on API 21+. This automatically colors the status bar and Overview (Recents) task entry.

On older platforms, AppCompat emulates the color theming where possible. At the moment this is limited to coloring the action bar and some widgets.

Widget tinting

When running on devices with Android 5.0, all of the widgets are tinted using the color theme attributes we just talked about. There are two main features which allow this on Lollipop: drawable tinting, and referencing theme attributes (of the form ?attr/foo) in drawables.

AppCompat provides similar behaviour on earlier versions of Android for a subset of UI widgets:

You don’t need to do anything special to make these work, just use these controls in your layouts as usual and AppCompat will do the rest (with some caveats; see the FAQ below).

Toolbar Widget

Toolbar is fully supported in AppCompat and has feature and API parity with the framework widget. In AppCompat, Toolbar is implemented in the android.support.v7.widget.Toolbar class. There are two ways to use Toolbar:

  • Use a Toolbar as an Action Bar when you want to use the existing Action Bar facilities (such as menu inflation and selection, ActionBarDrawerToggle, and so on) but want to have more control over its appearance.
  • Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
Action Bar

To use Toolbar as an Action Bar, first disable the decor-provided Action Bar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or its light variant).

Second, create a Toolbar instance, usually via your layout XML:

<android.support.v7.widget.Toolbar
    android:id=”@+id/my_awesome_toolbar”
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”?attr/actionBarSize”
    android:background=”?attr/colorPrimary” />

The height, width, background, and so on are totally up to you; these are just good examples. As Toolbar is just a ViewGroup, you can style and position it however you want.

Then in your Activity or Fragment, set the Toolbar to act as your Action Bar:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.

Standalone

The difference in standalone mode is that you do not set the Toolbar to act as your action bar. For this reason, you can use any AppCompat theme and you do not need to disable the decor-provided Action Bar.

In standalone mode, you need to manually populate the Toolbar with content/actions. For instance, if you want it to display actions, you need to inflate a menu into it:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);

    // Set an OnMenuItemClickListener to handle menu item clicks
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // Handle the menu item
            return true;
        }
    });

    // Inflate a menu to be displayed in the toolbar
    toolbar.inflateMenu(R.menu.your_toolbar_menu);
}

There are many other things you can do with Toolbar. For more information, see the Toolbar API reference.

Styling

Styling of Toolbar is done differently to the standard action bar, and is set directly onto the view.

Here's a basic style you should be using when you're using a Toolbar as your action bar:

<android.support.v7.widget.Toolbar  
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

The app:theme declaration will make sure that your text and items are using solid colors (i.e 100% opacity white).

DarkActionBar

You can style Toolbar instances directly using layout attributes. To achieve a Toolbar which looks like 'DarkActionBar' (dark content, light overflow menu), provide the theme and popupTheme attributes:

<android.support.v7.widget.Toolbar
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”@dimen/triple_height_toolbar”
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
SearchView Widget

AppCompat offers Lollipop’s updated SearchView API, which is far more customizable and styleable (queue the applause). We now use the Lollipop style structure instead of the old searchView* theme attributes.

Here’s how you style SearchView:

values/themes.xml:
<style name=”Theme.MyTheme” parent=”Theme.AppCompat”>
    <item name=”searchViewStyle”>@style/MySearchViewStyle</item>
</style>
<style name=”MySearchViewStyle” parent=”Widget.AppCompat.SearchView”>
    <!-- Background for the search query section (e.g. EditText) -->
    <item name="queryBackground">...</item>
    <!-- Background for the actions section (e.g. voice, submit) -->
    <item name="submitBackground">...</item>
    <!-- Close button icon -->
    <item name="closeIcon">...</item>
    <!-- Search button icon -->
    <item name="searchIcon">...</item>
    <!-- Go/commit button icon -->
    <item name="goIcon">...</item>
    <!-- Voice search button icon -->
    <item name="voiceIcon">...</item>
    <!-- Commit icon shown in the query suggestion row -->
    <item name="commitIcon">...</item>
    <!-- Layout for query suggestion rows -->
    <item name="suggestionRowLayout">...</item>
</style>

You do not need to set all (or any) of these, the defaults will work for the majority of apps.

Toolbar is coming...

Hopefully this post will help you get up and running with AppCompat and let you create some awesome material apps. Let us know in the comments/G+/Twitter if you’re have questions about AppCompat or any of the support libraries, or where we could provide more documentation.

FAQ
Why is my EditText (or other widget listed above) not being tinted correctly on my pre-Lollipop device?

The widget tinting in AppCompat works by intercepting any layout inflation and inserting a special tint-aware version of the widget in its place. For most people this will work fine, but I can think of a few scenarios where this won’t work, including:

  • You have your own custom version of the widget (i.e. you’ve extended EditText)
  • You are creating the EditText without a LayoutInflater (i.e., calling new EditText()).

The special tint-aware widgets are currently hidden as they’re an unfinished implementation detail. This may change in the future.

Why has X widget not been material-styled when running on pre-Lollipop?
Only some of the most common widgets have been updated so far. There are more coming in future releases of AppCompat.
Why does my Action Bar have a shadow on Android Lollipop? I’ve set android:windowContentOverlay to null.
On Lollipop, the action bar shadow is provided using the new elevation API. To remove it, either call getSupportActionBar().setElevation(0), or set the elevation attribute in your Action Bar style.
Why are there no ripples on pre-Lollipop?
A lot of what allows RippleDrawable to run smoothly is Android 5.0’s new RenderThread. To optimize for performance on previous versions of Android, we've left RippleDrawable out for now.
How do I use AppCompat with Preferences?
You can continue to use PreferenceFragment in your ActionBarActivity when running on an API v11+ device. For devices before that, you will need to provide a normal PreferenceActivity which is not material-styled.
Join the discussion on

+Android Developers
Categories: Programming

Implementing Material Design in Your Android app

Android Developers Blog - Sat, 11/08/2014 - 03:13
By Chris Banes and Nick Butcher, Android Developer Relations

Material design is a comprehensive approach to visual, interaction and motion design for the multi-screen world. Android 5.0 Lollipop and the updated support libraries help you to create material UIs. Here’s a rundown of some of the major elements of material design and the APIs and widgets that you can use to implement them in your app.

Tangible surfaces

In material design, UIs are composed of pieces of digital paper & ink. The surfaces and the shadows they cast provide visual cues to the structure of the application, what you can touch and how it will move. This digital material can move, expand and reform to create flexible UIs.

Shadows

A surface’s position and depth result in subtle changes in lighting and shadows. The new elevation property lets you specify a view’s position on the Z-axis and the framework then casts a real-time dynamic shadow on items behind it. You can set the elevation declaratively in your layouts, defined in dips:

<ImageView …
    android:elevation="8dp" />

You can also set this from code using getElevation()/setElevation() (with shims in ViewCompat). The shadow a view casts is defined by its outline, which by default is derived from its background. For example if you set a circular shape drawable as the background for a floating action button, then it would cast an appropriate shadow. If you need finer control of a view’s shadow, you can set a ViewOutlineProvider which can customise the Outline in getOutline().

Cards

Cards are a common pattern for creating surfaces holding a distinct piece of information. The new CardView support library allows you to create them easily, providing outlines and shadows for you (with equivalent behaviour on prior platforms).

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <!-- Your card content -->

</android.support.v7.widget.CardView>

CardView extends FrameLayout and provides default elevation and corner radius for you so that cards have a consistent appearance across the platform. You can customise these via the cardElevation and cardCornerRadius attributes, if required. Note that Cards are not the only way of achieving dimensionality and you should be wary of over-cardifying your UI!

Print-like Design

Material utilises classic principles from print design to create clean, simple layouts that put your content front and center. Bold deliberate color choices, intentional whitespace, tasteful typography and a strong baseline grid create hierarchy, meaning and focus.

Typography

Android 5.0 updates the system font Roboto to beautifully and clearly display text no matter the display size. A new medium weight has been added (android:fontFamily=”sans-serif-medium”) and new TextAppearance styles implement the recommended typographic scale for balancing content density and reading comfort. For instance you can easily use the ‘Title’ style by setting android:textAppearance=”@android:style/TextAppearance.Material.Title”. These styles are available on older platforms through the AppCompat support library, e.g. “@style/TextAppearance.AppCompat.Title”.

Color

Your application’s color palette brings branding and personality to your app so we’ve made it simple to colorize UI controls by using the following theme attributes:

  • colorPrimary. The primary branding color for the app; used as the action bar background, recents task title and in edge effects.
  • colorAccent. Vibrant complement to the primary branding color. Applied to framework controls such as EditText and Switch.
  • colorPrimaryDark. Darker variant of the primary branding color; applied to the status bar.

Further attributes give fine grained control over colorizing controls, see: colorControlNormal, colorControlActivated, colorControlHighlight, colorButtonNormal, colorSwitchThumbNormal, colorEdgeEffect, statusBarColor and navigationBarColor.

AppCompat provides a large subset of the functionality above, allowing you to colorize controls on pre-Lollipop platforms.

Dynamic color

Material Design encourages dynamic use of color, especially when you have rich images to work with. The new Palette support library lets you extract a small set of colors from an image to style your UI controls to match; creating an immersive experience. The extracted palette will include vibrant and muted tones as well as foreground text colors for optimal legibility. For example:

Palette.generateAsync(bitmap,
        new Palette.PaletteAsyncListener() {
    @Override
    public void onGenerated(Palette palette) {
         Palette.Swatch vibrant =
                 palette.getVibrantSwatch();
          if (swatch != null) {
              // If we have a vibrant color
              // update the title TextView
              titleView.setBackgroundColor(
                  vibrant.getRgb());
              titleView.setTextColor(
                  vibrant.getTitleTextColor());
          }
    }
});
Authentic Motion

Tangible surfaces don’t just appear out of nowhere like a jump-cut in a movie; they move into place helping to focus attention, establish spatial relationships and maintain continuity. Materials respond to touch to confirm your interaction and all changes radiate outward from your touch point. All motion is meaningful and intimate, aiding the user’s comprehension.

Activity + Fragment Transitions

By declaring ‘shared elements’ that are common across two screens you can create a smooth transition between the two states.

album_grid.xml
…
    <ImageView
        …
        android:transitionName="@string/transition_album_cover" />
album_details.xml
…
    <ImageView
        …
        android:transitionName="@string/transition_album_cover" />

AlbumActivity.java
Intent intent = new Intent();
String transitionName = getString(R.string.transition_album_cover);
…
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(activity,
    albumCoverImageView,   // The view which starts the transition
    transitionName    // The transitionName of the view we’re transitioning to
    );
ActivityCompat.startActivity(activity, intent, options.toBundle());

Here we define the same transitionName in two screens. When starting the new Activity and this transition is animated automatically. In addition to shared elements, you can now also choreograph entering and exiting elements.

Ripples

Materials respond to users’ touch with an ink ripple surface reaction. Interactive controls such as Buttons exhibit this behaviour by default when you use or inherit from Theme.Material (as will ?android:selectableItemBackground). You can add this feedback to your own drawables by simply wrapping them in a ripple element:

<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/accent_dark">
    <item>
        <shape
            android:shape="oval">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

Custom views should propagate touch location down to their drawables in the View#drawableHotspotChanged callback so that the ripple can start from the touch point.

StateListAnimator

Materials also respond to touch by raising up to meet your finger, like a magnetic attraction. You can achieve this effect by animating the translationZ attribute which is analogous to elevation but intended for transient use; such that Z = elevation + translationZ. The new stateListAnimator attribute allows you to easily animate the translationZ on touch (Buttons do this by default):

layout/your_layout.xml
<ImageButton …
    android:stateListAnimator="@anim/raise" />
anim/raise.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true">
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="@dimen/touch_raise"
            android:valueType="floatType" />
    </item>
    <item>
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="0dp"
            android:valueType="floatType" />
    </item>
</selector>
Reveal

A hallmark material transition for showing new content is to reveal it with an expanding circular mask. This helps to reinforce the user’s touchpoint as the start of all transitions, with its effects radiating outward radially. You can implement this using the following Animator:

Animator reveal = ViewAnimationUtils.createCircularReveal(
                    viewToReveal, // The new View to reveal
                    centerX,      // x co-ordinate to start the mask from
                    centerY,      // y co-ordinate to start the mask from
                    startRadius,  // radius of the starting mask
                    endRadius);   // radius of the final mask
reveal.start();
Interpolators

Motion should be deliberate, swift and precise. Unlike typical ease-in-ease-out transitions, in Material Design, objects tend to start quickly and ease into their final position. Over the course of the animation, the object spends more time near its final destination. As a result, the user isn’t left waiting for the animation to finish, and the negative effects of motion are minimized. A new fast-in-slow-out interpolator has been added to achieve this motion.

For elements entering and exiting the screen (which should do so at peak velocity), check out the linear-out-slow-in and fast-out-linear-in interpolators respectively.

Adaptive design

Our final core concept of material is creating a single adaptive design that works across devices of all sizes and shapes, from watches to giant TVs. Adaptive design techniques help us realize the vision that each device reflects a different view of the same underlying system. Each view is tailored to the size and interaction appropriate for that device. Colors, iconography, hierarchy, and spatial relationships remain constant. The material design system provides flexible components and patterns to help you build a design that scales.

Toolbar

The toolbar is a generalization of the action bar pattern, providing similar functionality, but much more flexibility. Unlike the standard action bar, toolbar is a view in your hierarchy just like any other, so you can place instances wherever you like, interleave them with the rest of your views, animate, react to scroll events and so on. You can make the Toolbar act as your Activity’s Action Bar by calling Activity.setActionBar().

In this example, the blue toolbar is an extended height, overlaid by the screen content and provides the navigation button. Note that two further toolbars are used in the list and detail views.

For details of implementing toolbars, see this post.

Go Forth and Materialize

Material Design helps you to build understandable, beautiful and adaptive apps, which are alive with motion. Hopefully, this post has inspired you to apply these principles to your app and signposted some of the new (and compatibility) APIs to achieve this.

Join the discussion on

+Android Developers
Categories: Programming

Material Design on Android Checklist

Android Developers Blog - Sat, 11/08/2014 - 03:13
ul.checklist { list-style-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNCIgaGVpZ2h0PSIxMC41IiB2aWV3Qm94PSIwIDYuOSAxNiAxMiI+DQogIDxwYXRoIGQ9Ik01LDE2LjRsLTMuOC0zLjhMMCwxMy45bDUsNUwxNS45LDguMWwtMS4zLTEuM0w1LDE2LjR6Ii8+DQo8L3N2Zz4NCg=='); clear: left; } .sectionintro { max-width: 400px; border: 1px solid #ccc; position: relative; padding: 10px 10px 10px 90px; font-style: italic; margin-top: 10px; margin-bottom: 10px; min-height: 75px; } .sectionintro img { position: absolute; left: 5px; top: 5px; border: 0 !important; box-shadow: 0 !important; } h3 { margin-top: 20px; font-size: 150%; } h4 { margin-top: 20px; } ul.checklist li { margin-top: 10px; } div.in-code { color: #aaa; padding-left: 20px; } div.in-code em { color: #c60; font-weight: bold; font-style: normal; }

By Roman Nurik, Design Advocate

Android 5.0 brings in material design as the new design system for the platform and system apps. Consumers will soon start getting Android 5.0 and they’re already seeing glimpses of material design with apps like Google Play Newsstand, Inbox by Gmail and Tumblr. Meanwhile, developers now have the Android 5.0 SDK, along with AppCompat for backward compatibility. And designers now have access to Photoshop, Illustrator and Sketch templates. All this means that now—yes now!—is the time to start implementing material design in your Android apps. Today, let’s talk about what implementing material design really boils down to.

Below, you’ll find a material design checklist that you can use to mark progress as you implement the new design system. The checklist is divided into 4 key sections based on the 4 key aspects of material design.

If you include a good chunk of the items in the checklist below, especially the ones indicated as signature elements, and follow traditional Android design best practices (i.e. these, these, and things we discussed on ADiA), you’ll be well on your way to material design awesomeness!

Tangible Surfaces UIs consist of surfaces (pieces of “digital paper”) arranged at varying elevations, casting shadows on surfaces behind them.
Figure 1. Surfaces and layering.
  • Signature element: Shadows are used to communicate which surfaces are in front of others, helping focus attention and establish hierarchy. Read more on depth and layering in UIs. In code: This is the android:elevation and android:translationZ attribute in Android 5.0. On earlier versions, shadows are normally provided as PNG assets.
  • Shadows and surfaces are used in a consistent and structured way. Each shadow indicates a new surface. Surfaces are created thoughtfully and carefully.
  • There are generally between 2 and 10 surfaces on the screen at once; avoid too much layering/nesting of surfaces.
  • Scrollable content either scrolls to the edges of the screen or behind another surface that casts a shadow over the content’s surface. Never clip an element against an invisible edge—elements don’t just scroll off into nowhere. Put another way, you rarely scroll the ink on a surface; you scroll the surface itself. In code: android:clipToPadding=false often helps with this when using ListView and ScrollView.
  • Surfaces have simple, single-color backgrounds.
A Bold, Print-Like Aesthetic The “digital ink” you draw on those pieces of digital paper is informed by classic print design, with an emphasis on bold use of color and type, contextual imagery, and structured whitespace.
Figure 2. Primary and accent colors.

Figure 3. Keylines.
  • Signature element: Apps use a primary color and an accent color (Figure 2) to color surface backgrounds and key UI widgets such as text fields and checkboxes. The accent color contrasts very well with the primary color (for example an app can use a dark blue primary color and a neon pink accent color). The accent color is high-contrast and is used to call attention to key UI elements, like a circular floating action button, selected tab strips, or form fields. In code: Set the android:colorPrimary and android:colorAccent attributes in your theme (drop the android prefix if using AppCompat). AppCompat automatically colors text fields, checkboxes, and more on pre-L devices.
  • Signature element: On Android 5.0, the status bar is colored to match the app’s primary color, or the current screen’s content. For full-bleed imagery, the status bar can be translucent. In code: Set the android:colorPrimaryDark or android:statusBarColor attribute in your theme (drop the android prefix if using AppCompat) or call Window.setStatusBarColor.
  • Icons, photos/images, text, and other foreground elements are colored “ink” on their surfaces. They don’t have shadows and don’t use gradients.
  • Colors extracted from images can be used to color adjacent UI elements or surfaces. In code: This can be done using the Palette support library.
  • Signature element: Icons in the app follow the system icon guidelines, and standard icons use the material design icon set.
  • Photos are generally immersive and full-bleed. For example, for detail screens, run edge-to-edge and can even appear behind the app bar or status bar. In code: The new Toolbar widget (and its AppCompat equivalent) can be transparent and placed directly in your layout. For the status bar, check this Stack Overflow post.
  • Signature element: Where appropriate, elements like body text, thumbnails, app bar titles, etc. are aligned to 3 keylines (Figure 3). On phones, those keylines are 16dp and 72dp from the left edge and 16dp from the right edge of the screen. On tablets those values are 24dp and 80dp.
  • UI elements are aligned to and sized according to an 8dp baseline grid. For example, app bars are 56dp tall on phones and 64dp tall on tablets. Padding and margins can take on values like 8dp, 16dp, 24dp, etc. More precise text positioning uses a 4dp grid.
Authentic Motion Motion helps communicate what’s happening in the UI, providing visual continuity across app contexts and states. Motion also adds delight using smaller-scale transitions. Motion isn’t employed simply for motion’s sake.
Figure 4. "Hero" transitions.
  • In general, UI and content elements don’t just appear or disappear—they animate into place, either together as a unit, or individually.
  • Signature element: When touching an item to see its details, there’s a “hero” transition (Figure 4) that moves and scales the item between its position in the browsing screen and its position in the detail screen. In code: These are called “shared element transitions” in the SDK. The support version of FragmentTransaction also includes some shared element support.
  • Signature element: Ripple effects originating from where you touched the screen are used to show touch feedback on an item. In code: The default android:selectableItemBackground and android:selectableItemBackgroundBorderless have this, or you can use RippleDrawable (<ripple>) to customize the effect. On pre-5.0 devices, ripples aren’t an expected feature, so defer to the default android:selectableItemBackground behavior.
  • Signature element: UI elements can appear using a circular “reveal” animation. In code: See this doc or the ViewAnimationUtils class for more.
  • Signature element: Animations are used in more subtle, delightful ways, such as to convey the transition between icon states or text states. For example, a “+” icon can morph into an “x” symbol, or an outlined heart icon can be filled using a paint-bucket fill effect. In code: Icon transitions can be implemented using AnimatedStateListDrawable and its XML counterpart. An example can be found in the Google I/O app source. There’s also support for animated vector icons.
  • Animations and transitions are fast—generally under 300ms.
  • Crossfades are often replaced by translate/slide transitions: vertical slides for descendant navigation and horizontal slides for lateral navigation. For slide transitions, prefer quick acceleration and gentle ease-in deceleration over simple linear moves. See the material design spec on motion for more.
Adaptive Design (and UI Patterns) Tangible surfaces, bold graphic design, and meaningful motion work together to bring a consistent experience across any screen, be it phones, tablets, laptops, desktops, TVs, wearables, or even cars. Additionally, the key UI patterns below help establish a consistent character for the app across devices.
Figure 5. The floating action button.
  • The app uses responsive design best practices to ensure screens lay themselves out appropriately on any screen size, in any orientation. See the Tablet App Quality Checklist for a list of ways to optimize for tablets, and this blog post for high-level tablet optimization tips.
    • In material design, detail screens are often presented as popups that appear using “hero” transitions (see above).
    • In multi-pane layouts, the app can use multiple toolbars to place actions contextually next to their related content.
  • Signature element: Where appropriate, the app promotes the key action on a screen using a circular floating action button (FAB). The FAB (Figure 5) is a circular surface, so it casts a shadow. It is colored with a bright, accent color (see above). It performs a primary action such as send, compose, create, add, or search. It floats in front of other surfaces, and is normally at an 8dp elevation. It frequently appears at the bottom right of the screen, or centered on an edge where two surfaces meet (a seam or a step).

App bar
  • Signature element: The app uses a standard Android app bar. The app bar doesn’t have an app icon. Color and typography are used for branding instead. The app bar casts a shadow (or has a shadow cast on it by a surface below and behind it). The app bar normally has a 4dp elevation. In code: Use the new Toolbar widget in Android 5.0 that is placed directly into the activity’s view hierarchy. AppCompat also provides android.support.v7.widget.Toolbar, which supports all modern platform versions.
  • The app bar might be for example 2 or 3 times taller than the standard height; on scroll, the app bar can smoothly collapse into its normal height.
  • The app bar might be completely transparent in some cases, with the text and actions overlaying an image behind it. For example, see the Google Play Newsstand app.
  • App bar titles align to the 2nd keyline (see more info on keylines above) In code: when using the Toolbar widget, use the android:contentInsetStart attribute.
  • Where appropriate, upon scrolling down, the app bar can scroll off the screen, leaving more vertical space for content. Upon scrolling back up, the app bar should be shown again.
Tabs
Figure 6. Tabs with material design.
  • Signature element: Tabs follow the newer material design interactions and styling (Figure 6). There are no vertical separators between tabs. If the app uses top-level tabs, tabs are visually a part of the app bar; tabs are a part of the app bar’s surface. In code: See the SlidingTabsBasic sample code in the SDK or the Google I/O app source (particularly the "My Schedule" section for phones).
  • Tabs should support a swipe gesture for moving between them. In code: All tabs should be swipeable using the ViewPager widget, which is available in the support library.
  • Selected tabs are indicated by a foreground color change and/or a small strip below the tab text (or icon) colored with an accent color. The tab strip should smoothly slide as you swipe between tabs.
Navigation drawer
Figure 7. Navigation drawers
with material design.
  • Signature element: If the app uses a navigation drawer, it follows the newer material design interactions and styling (Figure 7). The drawer appears in front of the app bar. It also appears semitransparent behind the status bar. In code: Implement drawers using the DrawerLayout widget from the support library, along with the new Toolbar widget discussed above. See this Stack Overflow post for more.
  • Signature element: The leftmost icon in the app bar is a navigation drawer indicator; the app icon is not visible in the app bar. Optionally, on earlier versions of the platform, if the app has a drawer, the top-left icon can remain the app icon and narrower drawer indicator, as in Android 4.0.
  • The drawer is a standard width: No wider than 320dp on phones and 400dp on tablets, but no narrower than the screen width minus the standard toolbar height (360dp - 56dp = 304dp on the Nexus 5)
  • Item heights in the drawer follow the baseline grid: 48dp tall rows, 8dp above list sections and 8dp above and below dividers.
  • Text and icons should follow the keylines discussed above.

More and more apps from Google and across the Google Play ecosystem will be updating with material design soon, so expect Winter 2014 to be a big quarter for design on Android. For more designer resources on material design, check out the DesignBytes series. For additional developer resources, check the Creating Apps with Material Design docs!

Join the discussion on

+Android Developers
Categories: Programming

Your Chance to be on TV!

Android Developers Blog - Sat, 11/08/2014 - 03:12

By Tarjei Vassbotn and Dan Galpin, Developer Advocates, Android TV

We’re excited to see the launch of Nexus Player, the first consumer streaming media player running Android TV. Android TV delivers an entertainment experience tailored for users, including movies, shows, games and more.
Now is a great time to develop apps for Android TV that reach a whole new audience.

Starting today, you can publish your apps for Android TV on Google Play, the largest digital store for apps and games. We’ve provided guidance on how to get started building great apps for Android TV in this post.

"Google has done an insanely good job to ease the developer’s task of creating a TV application, mainly thanks to the Leanback support library. It literally takes 2 hours to create a fully working and possibly fancy app, which is awesome."

- Sebastiano Gottardo A high bar for quality experiences

We want to offer the best possible experience for users to enjoy your apps and games. To make this possible, your Android TV app must meet the basic requirements for usability. When your app meets these requirements, users will be able to discover and download it directly on their Android TV devices.

Even if you have already uploaded your app to the Google Play Developer Console, you will need to add TV graphics and screenshots, and opt-in to distribution on TV on the Pricing & Distribution page. For complete information about the requirements and process of publishing your Android TV app for Google Play, make sure to check out the publishing documentation.

Get started!

With our Leanback Library we’ve made it easy for you to extend your existing app to the TV screen or even build a completely new app for Android TV. For a quick look at the Leanback Library, check out this DevBytes video.

We’ve only begun scratching the surface of what’s possible with this new form factor, and we are very excited to see what you will build, start developing today!

Join the discussion on

+Android Developers
Categories: Programming

The fastest route between voice search and your app

Android Developers Blog - Sat, 11/08/2014 - 02:00
By Jarek Wilkiewicz, Developer Advocate, Google Search

How many lines of code will it take to let your users say Ok Google, and search for something in your app? Hardly any. Starting today, all you need is a small addition to your AndroidManifest.xml in order to connect the Google Now SEARCH_ACTION with your searchable activity:

<activity android:name=".SearchableActivity">
    <intent-filter>
        <action android:name="com.google.android.gms.actions.SEARCH_ACTION"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

Once you make these changes, your app can receive the SEARCH_ACTION intent containing the SearchManager.QUERY extra with the search expression.

At Google, we always look for innovative ways to help you improve mobile search and drive user engagement back to your app. For example, users can now say to the Google app: “Ok Google, search pizza on Eat24” or “Ok Google, search for hotels in Maui on TripAdvisor.”

This feature is available on English locale Android devices running Jelly Bean and above with the Google app v3.5 or greater. Last but not least, users can enable the Ok Google hot-word detection from any screen, which offers them the fastest route between their search command and your app!


Join the discussion on
+Android Developers


Categories: Programming

Scaling Agile: SAFe Events

Their are meetings of all types!

Their are meetings of all types!

The Scaled Agile Framework Enterprise (SAFe) organizes work using a hierarchy of value stream, agile release train, program increment, sprint and teams. In order to make the structure work, SAFe adds a few events to the standard set of team-level Scrum meetings (sprint planning, daily stand up/Scrum meeting, demonstrations and retrospectives.  The additions include:

  1. Release Planning Meeting. The release planning meeting is used to plan and kick-off a program increment. The meeting is typically held over the course of two days and involves everyone involved with the program increment. The release planning meeting is one of the keystones of the SAFe framework.
  2. Scrum of Scrums: The Scrum of Scrums (SoS) is a meeting of the Scrum Masters using a format that is very similar to the daily stand-up meeting. The SoS is a common tool for scaling Agile and has is part of the Scrum cannon. This meeting is generally facilitated by the release train engineer.
  3. Scrum of Product Owners (optional): In a similar vein as SoS, a Scrum of product owners. The same general format of the classic three questions can be applied from a product owner perspective. The goal of the meeting is generally to keep the product owners informed and involved.
  4. Release Management Meeting: The release management meeting reviews progress toward a developing releasable product. Attributes that are reviewed include scope, quality, and progress toward the release roadmap, quality and potentially other factors.
  5. System Demo: The system demo provides a demonstration of the integrated software. This is typically a demonstration to the business and other key stakeholders. The system demo occurs at the end of each sprint generally after the sprint demo.
  6. Program Increment Solution Demo (Part of the activity SAFe calls Inspect and Adapt): The PI demo reflects everything that was developed (and is done) during the program increment. All release planning participants are part of this demo. The PI solution demo connects the loop with everyone that was involved in planning and also provides a starting point for everyone involved in the next planning event.
  7. Problem Solving Workshop (Part of the activity SAFe calls Inspect and Adapt): The problem solving workshop is a macro version of a retrospective. The workshop generates an improvement backlog that is an input into the next release planning cycle. The problem solving workshop provides all of the teams with time to identify and prioritize problems that may affect the entire Agile release train.

All of these events bear further exploration, however it is important to note that when scaling Agile so that important  large business needs are tackled in a timely fashion, scale comes with a cost. The cost is the need for control structures. Agile has many attributes that contribute to discipline and control such as short feedback loops, iterative planning, demonstration and more, but as the number of teams working toward a common goal gets larger additional mechanisms are generally needed when cadence and synchronization are not sufficient.


Categories: Process Management

Product Development Kaizen

Herding Cats - Glen Alleman - Fri, 11/07/2014 - 19:41

Much of the noise around agile is based on platitudes and words in the absence of a domain and a context in that domain. Here's a possible anchoring processes

Product development kaizen (pdk) from Glen Alleman And an example paper based on these principles. Screen Shot 2014-11-07 at 11.34.16 AM
So when you hear about the next big thing think of Carl's suggestion. Especially if that next big thing violates the principles of business and economics. Untitled
Categories: Project Management

Dual-Speed IT Drives Digital Business Transformation and Improves IT-Business Relationships

Don’t try to turn all of your traditional IT into a digital unit.  

You’ll break both, or do neither well.

Instead,  add a Digital Unit.   Meanwhile, continue to simplify and optimize your traditional IT, but, at the same time, add a Digital Unit that’s optimized to operate in a Cloud-First, Mobile-First world.

This is the Dual-Speed IT approach, and, with this way, you can choose the right approach for the job and get the best of both worlds.

Some projects involve more extensive planning because they are higher-risk and have more dependencies.

Other projects benefit from a loose learning-by-doing method, with rapid feedback loops, customer impact, and testing new business waters.

And, over time, you can shift the mix.

In the book, Leading Digital: Turning Technology into Business Transformation, George Westerman, Didier Bonnet, and Andrew McAfee, share some of their lessons learned from companies that are Digital Masters that created their digital visions and are driving business change.

Build Digital Skills Into One of Your Existing Business Units

You can grow one of your existing business units into a Digital Unit.  For example, marketing is a pretty good bet, given the customer focus and the business impact.

Via Leading Digital:

 

“Changing the IT-business relationship is well worth the effort, but doing so takes time.  Your company may not have the time to wait before starting your digital transformation.  Rather than improving the IT unit, some companies try to build digital skills into another unit, such as marketing.  They try to work around IT rather than with it.”

Don’t Mix Your Digital Unit with Your Traditional IT

Don’t throw away your existing IT or break it by turning it into something it’s not, too quickly.   Instead, leverage it for the projects where it makes sense, while also leveraging your new Digital IT unit.

Via Leading Digital:

“Although building digital skills is useful, trying to work around IT can be fraught with challenges, especially if people do not understand the reasons for IT's systematic, if sometimes ponderous, processes.  This kind of flanking action can waste money, make the digital platform more complex, and even worse, open the company to security and regulatory risks.”

Create a Dual-Speed IT to Support Both Traditional IT and Faster-Speed Digital Transformation

You can have the best of both worlds, while both evolving your traditional IT and growing your Digital Unit to thrive at Cloud speed.

Via Leading Digital:

“A better approach is to create a dual-speed IT structure, where one part of the IT unit continues to support traditional IT needs, while another takes on the challenge of operating at digital speed with the business.  Digital activities--especially in customer engagement--move faster than many traditional IT ones.  They look at design processes differently.  Where IT projects have traditionally depended on clear designs and well-structured project plans, digital activities often engage in test-and-learn strategies, trying features in real-life experiments and quickly adding or dropping them based on what they find.”

Optimize the Digital Unit for Digital World

Your Digital Unit needs to be very different from traditional IT in terms of the mindset and the approaches around the people, processes, and technology.

Via Leading Digital:

“In a dual-speed approach, the digital unit can develop processes and methods at clock-speeds more closely aligned with the digital world, without losing sight of the reasons that the old IT processes existed.  IT leaders can draw on informal relationships within the IT department to get access to legacy systems or make other changes happen.  Business leaders can use their networks to get input and resources.  Business and IT leaders can even start to work together in the kind of two-in-a-box leadership method that LBG and other companies have adopted.”

Choose the Right Leadership Both in the Business and in IT

To make it work and to make it work well, it takes partnerships on both sides.   The business and IT both need skin in the game.

Via Leading Digital:

“Building dual-speed IT units requires choosing the right leadership on both sides of the relationship.  Business executives need to be comfortable with technology and with being challenged by their IT counterparts.  IT leaders need to have a mind-set that extends beyond technology to encompass the processes and drivers of business performance.  Leaders from both sides need to be strong communicators who can slide easily between conversations with their business- or IT-focused people.”

Great IT Leaders Know When to Choose Traditional IT vs. the Digital Unit

With both options at your disposal, Great IT Leaders know how to choose the right approach for the job.   Some programs and projects will take a more traditional life-cycle or require heavier planning or more extensive governance and risk management, while other projects can be driven in a more lightweight and agile way.

Via Leading Digital:

“Dual-speed IT also requires perspective about the value of speed.  Not all digital efforts need the kind of fast-moving, constantly changing processes that digital customer-engagement processes can need.  In fact, the underlying technology elements that powered LBG's new platform, Asian Paints' operational excellence, and Nike's digital supply chain enhancements required the careful, systematic thinking that underpins traditional IT practices.  Doing these big implementations in a loose learning-by-doing method could be dangerous.  It could increase rework, waste money, and introduce security risks.  But once the strong digital platform is there, building new digital capabilities can be fast, agile, and innovative.  The key is to understand what you need in each type of project and how much room any project has to be flexible and agile.  Great IT leaders know how to do this.  If teamed with the right business leaders, they can make progress quickly and safely.”

Dual-Speed IT Requires New Processes within IT

It takes a shift in processes to do Dual-Speed IT.

Via Leading Digital:

“Dual-speed IT also takes new processes inside IT.  Few digital businesses have the luxury to wait for monthly software release cycles for all of their applications.  Digital-image hosting business Flickr, for example, aims for up to ten deployments per day, while some businesses require even more.  This continuous-deployment approach requires very tight discipline and collaboration between development, test, and operations people.  A bug in software, missed step in testing, or configuration problem in deployment can bring down a web site or affect thousands of customers.”

DevOps Makes Dual Speed IT Possible

DevOps blends development and operations into a more integrated approach that simplifies and streamlines processes to shorten cycle times and speed up fixes and feedback loops.

Via Leading Digital:

“A relatively new software-development method called DevOps aims to make this kind of disciplined speed possible.  It breaks down silos between development, operations, and quality assurance groups, allowing them to collaborate more closely and be more agile.  When done properly, DevOps improves the speed and reliability of application development and deployment by standardizing development environments.  It uses strong methods and standards, including synchronizing the tools used by each group.”

DevOps Can Help IT Release Software Better, Faster, Cheaper, and More Reliably

DevOps is the name of the game when it comes to shipping better, faster, cheaper and more reliably in a Cloud-First, Mobile-First world.

Via Leading Digital:

“DevOps relies heavily on automated tools to do tasks in testing, configuration control, and deployment—tasks that are both slow and error-prone when done manually.  Companies that use DevOps need to foster a culture where different IT groups can work together and where workers accept the rules and methods that make the process effective.  The discipline, tools, and strong processes of DevOps can help IT release software more rapidly and with fewer errors, as well as monitor performance and resolve process issues more effectively, than before.”

Driving Digital Transformation Takes a Strong Link Between Business and IT Executives

In order for your Digital Transformation to thrive, it takes building better bridges between the business leaders and the IT leaders.

Via Leading Digital:

“Whether your CIO takes it upon himself or herself to improve the IT-business relationship, or you decide to help make it happen, forging a strong link between business and IT executives is an essential part of driving digital transformation.  Strong IT-business relationships can transform the way IT works and the way the business works with it.  Through trust and shared understanding, your technology and business experts can collaborate closely, like at LBG, to innovate your business at digital speeds.  Without this kind of relationship, your company may become mired in endless requirements discussion, filing projects, and lackluster systems, while your competitors accelerate past you in the digital fast lane.”

If you want to thrive in the new digital economy while driving digital business transformation without breaking your existing business, consider adding Dual-Speed IT to your strategies and shift the mix from traditional IT to your Digital Unit over time.

You Might Also Like

10 High-Value Activities in the Enterprise

Cloud Changes the Game from Deployment to Adoption

Drive Business Transformation by Reenvisioning Operations

Drive Business Transformation by Reenvisioning Your Customer Experience

How To Improve the IT-Business Relationship

Management Innovation is at the Top of the Innovation Stack

Think in a Series of Sprints, Not Marathons

Categories: Architecture, Programming

Stuff The Internet Says On Scalability For November 7th, 2014

Hey, it's HighScalability time:


Google's new hyper efficient, hyper secure datacenters. (keynotelarge, m, o, r e)
  • 2 billion: containers started every week at Google; 86%: Apple's share of handset profits; 50: number of parallel processes in the brain; $12 million: cost for every additional second it takes customers to pay at a Walmart store; 800 terabytes: rendering for the movie Interstellar
  • Quotable Quotes:
    • @IFTTTRecipe: http://Highscalability.com  to email @ http://ift.tt/1omSSgs Send new highscalability.com articles to my mailbox
    • @chadfowler: I've decided to break up tomorrow's monolithic talk about microservices into a series of microtalks #gotober
    • Emily Balcetis: Attention can “be thought of as what you allow your eyes to look at.”
    • Adam Alter: researchers have shown that our names take root deep within our mental worlds, drawing us magnetically toward the concepts they embody
    • @mjpt777: Monitoring needs to reflect an issue within 10 seconds of it happening. Poll at 1 second granularity. - @adrianco #gotober
    • @adyranov: "Trust only benchmarks you've made yourself. All others are benchmarketing" #highload2014
    • @adrianco: #GOTOber @mjpt777 Aeron performance on a laptop - 20 million 40byte messages/sec. 90%ile latency of 7us. 100% 37us.
    • @mjpt777: Have your infrastructure optimised for speed of delivery rather than cost, stuff then gets done so fast you reduce cost. @adrianco #gotober
    • Seth Newburg: This is a first in mobile! This is a device running over an internal network, rather than just everything being connected to a CPU
    • @swardley: OpenStack vs AWS - IMHO OpenStack should have dominated but pisspoor strategic play makes it unlikely for 10-15yrs.
    • Rudiger Moller: There is another strong value in going off heap (even when using advanced collectors like Zing's): Datastructures expressed in Java frequently have a redundancy of 80-90%.
    • @zooko: Novice engineers have not yet grokked this: the number of modes or options in your system is the *exponent* in how hard it is to maintain.

  • OK Google...give me more cool functionality and lower prices. And they did. Google Cloud Platform Live: Introducing Container Engine, Cloud Networking and much more. This may take a while to process and put in some context. What Google is continuing to do is consumerize their internal services. The biggest example of this is opening up their container scheduling, management, and auto scaler services, while making it Docker compatible. If you want to run code as close as possible to your users you can now direct peer to any of Google's over 70 points of presence in 33 countries around the world. That's impressive. AWS has 14 and Azure has 11. Firebase is still behind Parse in features, but with Google's support look for it to blossom. The distributed debugger is truly impressive work. Game changing really. There's also a new improved Pub/Sub system. Slowly but surely the worm turns. 

  • A great list. I'd like to see what a similar list for the message dispatch and handlers would look like. Martin Thompson design principles for the Aeron messaging system: garbage free in steady state running; smart batching in the message path; wait-free algos in the message path; non-blocking IO in the message path; no exceptional cases in message path; apply the single writer principle; prefer unshared state; avoid unnecessary data copies. 

  • Nicely done André Staltz. The introduction to Reactive Programming you've been missing. If insight meditation has not been enough to guide your conversion from the object obsessed to the functionally enlightened then this article might be just what you are looking for. Or not.

  • This is cool, using Cassandra as an embedded database. Russian Facebook Ok.ru Utilizing Cassandra for 1 Million Operations per Second, Over 80TB in Largest Cluster: The way we use Casssandra is somewhat unusual – we don’t use thrift or netty based native protocol to communicate with Cassandra nodes remotely. Instead, we co-locate Cassandra nodes in the same JVM with business service logic, exposing not generic data manipulation, but business level interface remotely. This way we avoid extra network roundtrips within a single business transaction and use internal calls to Cassandra classes to get information faster. Also this helps us to do many little hacks on its internals, making huge gains on efficiency and ease of distributed servers development.

Don't miss all that the Internet has to say on Scalability, click below and become eventually consistent with all scalability knowledge (which means this post has many more items to read so please keep on reading)...

Categories: Architecture

“Your Book Is Expensive!” (Yes, and It’s Also Cheap)

NOOP.NL - Jurgen Appelo - Fri, 11/07/2014 - 16:30
mock-up-spread-4-wit-1024

I have started the pre-sales of Management 3.0 #Workout – Paper Edition.

The paper book looks amazing! :-)

Besides the regular print version, I offer an exclusive version with autograph, unique number, postcards, kudo cards, and a hand-drawn illustration. There are only 500 of those!

The post “Your Book Is Expensive!” (Yes, and It’s Also Cheap) appeared first on NOOP.NL.

Categories: Project Management

R: Joining multiple data frames

Mark Needham - Fri, 11/07/2014 - 02:29

I’ve been looking through the code from Martin Eastwood’s excellent talk ‘Predicting Football Using R‘ and was intrigued by the code which reshaped the data into that expected by glm.

The original looks like this:

df <- read.csv('http://www.football-data.co.uk/mmz4281/1314/E0.csv')
 
# munge data into format compatible with glm function
df <- apply(df, 1, function(row){
  data.frame(team=c(row['HomeTeam'], row['AwayTeam']),
             opponent=c(row['AwayTeam'], row['HomeTeam']),
             goals=c(row['FTHG'], row['FTAG']),
             home=c(1, 0))
})
df <- do.call(rbind, df)

The initial data frame looks like this:

> library(dplyr)
> df %>% select(HomeTeam, AwayTeam, FTHG, FTAG) %>% head(1)
  HomeTeam    AwayTeam FTHG FTAG
1  Arsenal Aston Villa    1    3

And we want to get it to look like this:

> head(df, 2)
                team    opponent goals home
HomeTeam     Arsenal Aston Villa     1    1
AwayTeam Aston Villa     Arsenal     3    0

So for each row in the initial data frame we want to have two rows: one representing each team, how many goals they scored in the match and whether they were playing at home or away.

I really like dplyr’s pipelining function so I thought I’d try and translate Martin’s code to use that and other dplyr functions.

I ended up with the following two sets of function calls:

df %>% select(team = HomeTeam, opponent = AwayTeam, goals = FTHG) %>% mutate(home = 1)
df %>% select(team = AwayTeam, opponent = HomeTeam, goals = FTAG) %>% mutate(home = 0)

I’m doing pretty much the same thing as Martin except I’ve used dplyr’s select and mutate functions to transform the data frame.

The next step was to join those two data frames together and with Nicole’s help I realised that there are many ways we can do this.

The functions that will do the job are:

We decided to benchmark them to see which was able to transform the data frame the fastest:

# load data into data.frame
dfOrig <- read.csv('http://www.football-data.co.uk/mmz4281/1314/E0.csv')
 
original = function(df) {
  df <- apply(df, 1, function(row){
    data.frame(team=c(row['HomeTeam'], row['AwayTeam']),
               opponent=c(row['AwayTeam'], row['HomeTeam']),
               goals=c(row['FTHG'], row['FTAG']),
               home=c(1, 0))
  })
  do.call(rbind, df)
}
 
newRBind = function(df) {
  rbind(df %>% select(team = HomeTeam, opponent = AwayTeam, goals = FTHG) %>% mutate(home = 1),
        df %>% select(team = AwayTeam, opponent = HomeTeam, goals = FTAG) %>% mutate(home = 0))  
}
 
newUnion = function(df) {
  union(df %>% select(team = HomeTeam, opponent = AwayTeam, goals = FTHG) %>% mutate(home = 1),
        df %>% select(team = AwayTeam, opponent = HomeTeam, goals = FTAG) %>% mutate(home = 0))  
}
 
newJoin = function(df) {
  join(df %>% select(team = HomeTeam, opponent = AwayTeam, goals = FTHG) %>% mutate(home = 1),
       df %>% select(team = AwayTeam, opponent = HomeTeam, goals = FTAG) %>% mutate(home = 0),
      type = "full")  
}
 
newMerge = function(df) {
  merge(df %>% select(team = HomeTeam, opponent = AwayTeam, goals = FTHG) %>% mutate(home = 1),
       df %>% select(team = AwayTeam, opponent = HomeTeam, goals = FTAG) %>% mutate(home = 0),
       all = TRUE)  
}
> library(microbenchmark)
 
> microbenchmark(original(dfOrig))
Unit: milliseconds
             expr   min    lq  mean median    uq max neval
 original(dfOrig) 189.4 196.8 202.5    201 205.5 284   100
 
> microbenchmark(newRBind(dfOrig))
Unit: milliseconds
             expr   min    lq  mean median    uq   max neval
 newRBind(dfOrig) 2.197 2.274 2.396  2.309 2.377 4.526   100
 
> microbenchmark(newUnion(dfOrig))
Unit: milliseconds
             expr   min    lq  mean median   uq   max neval
 newUnion(dfOrig) 2.156 2.223 2.377  2.264 2.34 4.597   100
 
> microbenchmark(newJoin(dfOrig))
 
Unit: milliseconds
            expr   min    lq  mean median   uq   max neval
 newJoin(dfOrig) 5.961 6.132 6.817  6.253 6.65 11.95   100
 
> microbenchmark(newMerge(dfOrig))
Unit: milliseconds
             expr   min    lq  mean median    uq   max neval
 newMerge(dfOrig) 7.121 7.413 8.037  7.541 7.934 13.32   100

We actually get a 100 time speed up over the original function if we use rbind or union whereas with merge or join it’s around 35 times quicker.

In this case using merge or join is a bit misleading because we’re not actually connecting the data frames together based on any particular field – we are just appending one to the other.

The code’s available as a gist if you want to have a play.

Categories: Programming

Scaling Agile: Program Increment

If you're running at a different cadence, someone is always falling behind.

If you’re running at a different cadence, someone is always falling behind.

The Scaled Agile Framework Enterprise (SAFe) uses the concept of a hierarchy to translate business strategy and needs to the work a Scrum team does on a daily basis. The hierarchy begins with value streams that are actualized by agile release trains (ART). ARTs are a long lived team of teams this is organized to deliver the support the value stream. While the value stream provides a goal and the ART the long term vehicle for the that support additional structure is needed before teams are set loose. As anyone that has watched teams interact knows, without structure shenanigans will ensue. The program increment provides a structure to connect the long term vision and the scrum teams. Program increments are similar to sprints, but at higher level.

The scrum teams within an ART use sprint cadence as a synchronization and motivational tool to develop solutions in a coordinated manner. Cadence provides short feedback cycles that provide focus. Program increments aggregate a fixed number of sprints together to peruse a common theme or goal such as a group of related features that might comprise one or more releases. The program increment process provides a framework to synchronize planning and development through group planning, group demonstrations and larger scale retrospectives. The program increment functions in much the same manner as the Sprint in Scrum. Here are the attributes of a program increment:

  1. Time-bound planning cycle. Program increments are typically 8 – 12 weeks, four two-week or three-week sprints.
  2. Common theme/goal. The program increment acts a container to focus development on the features and functions needed to deliver common theme or goal. The program increment and release plan do not have to synchronize. Using an example of a hypothetical customer facing website. A program increment could be focused of developing an integrated shopping cart solution with releases being made during the 8 – 12 weeks as major components reach done.  The mantra, “develop to cadence, release on demand.” [FRAGMENT, NO VERB] Said more bluntly, develop using sprints and program increments to provide cadence and synchronization and be ready to release when the business needs the functionality.
  3. Ceremonies demarcate program increments. Much like sprint planning and demonstrations and retrospectives mark the beginning and the ending of a sprint, program increments are bounded by ceremonies. The release planning meeting marks the beginning of the program increment and the “inspect and adapt cycle” marks the outer boundary.

A program increment is a time-boxed container with a common theme or goal that helps the multiple teams involved in an ART to stay synchronized. Teams further enhance their synchronicity by integrating frequently, participating in Scrum of Scrums, management dependencies as well as team and system-level demonstration. The duration of the program increment is often conducive to release schedules and plan [HUH?], however the two concepts do not have to be synonymous. Agile development is about building implementable functionality every sprint, the macro cadence of the program increment allows that functionality to be bundled into features which can be released as planned or as needed.


Categories: Process Management

Improved Game Testing with Google Play Games Management API

Android Developers Blog - Thu, 11/06/2014 - 23:36

By Ben Frenkel, Google Play Games team

We’re always looking to help developers improve the gaming experience for their users on Google Play. So today, we've expanded our existing suite of Management APIs to let you fully control all resources in your Google Play Games-enabled game during development and testing, with better support for alpha and beta groups.

Let’s take a quick dive into the expanded offering.

  • Reset a single tester’s state for any resource (e.g., achievements, leaderboards), or do it for all resources at once. For example, you can now completely reset a given tester’s data if they’ve ended up in a bad state due to an experimental build. You can do this for individual instances or all instances of achievements, events, quests, or leaderboards scores.
  • Reset the state of a single draft resource for all testers, or do it for all draft resources at once. You can now reset all draft leaderboards in your game before publishing with a single API call. This ensures the members of your alpha or beta communities don’t have an unfair advantage on release day. You can do this for individual instances or all instances of achievements, events, quests, or leaderboards scores.
  • Clear global match state for all real time or turn based matches composed solely of testers. You can now reset all turn-based matches on release day. This will ensure that all matches from that point on are on the release version of the game. This is available for both real-time or turn-based games.

These updates make it far less complex and error prone to manage data during testing, saving you time and improving the rate at which you can make and test changes to your games.

Play Games Management API background

The Management API is a set of tools that enable developers to do things like manage tester data and clean up bogus leaderboard score submissions. Developers can also use the API to control and manipulate resources (e.g., achievements, events, multiplayer match data). Getting started

You can get started with the latest version of the Management API right now. Review the updated API reference documentation, start with an example management interface, or download the sample client libraries to get on your way.

Join the discussion on

+Android Developers
Categories: Programming

Mutation Testing: How Good are your Unit Tests?

Xebia Blog - Thu, 11/06/2014 - 20:56

You write unit tests for every piece of code you deliver. Your test coverage is close to 100%. So when the point comes when you have to make some small changes to the existing code, you feel safe and confident that your test suite will protect you against possible mistakes.
You make your changes, and all your tests still pass. You should be fairly confident now that you can commit your new code without breaking anything, right?

Well, maybe not. Maybe your unit tests were fooling you. Sure they covered every line of your code, but they could have performed the wrong assertions.
In this post I will introduce mutation testing. Mutation testing can help you find omissions in your unit tests.

Let's begin with a small example:

package com.xebia;

public class NameParser {
  public Person findPersonWithLastName(String[] names, String lastNameToFind) {
    Person result = null;
    for(int i=0; i <= names.length; i++) { // bug 1
      String[] parts = names[i].split(" ");
      String firstName = parts[0];
      String lastName = parts[1];
      if(lastName.equals(lastNameToFind)) {
        result = new Person(firstName, lastName);
        break;
      }
    }
    return result;
  }
}

NameParser takes a list of strings which consist of a first name and a last name, searches for the entry with a given last name, instantiates a Person object out of it and returns it.
Here is the Person class:

package com.xebia;

public class Person {
  private final String firstName;
  private final String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return firstName; // bug 2
  }
}

You can see that there are two bugs in the code. The first one is in the loop in NameParser, which loops past the end of the names array. The second on is in Person, which mistakenly returns firstName in its getLastName method.

NameParser has a unit test:

package com.xebia;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class NameParserTest {
  private NameParser nameParser;
  private String[] names;

  @Before
  public void setUp() {
    nameParser = new NameParser();
    names = new String[]{"Mike Jones", "John Doe"};
  }

  @Test
  public void shouldFindPersonByLastName() {
    Person person = nameParser.findPersonWithLastName(names, "Doe");
    String firstName = person.getFirstName();
    String lastName = person.getLastName();
    assertEquals("John", firstName);
  }
}

The unit tests covers the Person and NameParser code for 100% and succeeds!
It doesn't find the bug in Person.getLastName because it simply forgets to do an assertion on it. And it doesn't find the bug in the loop in NameParser because it doesn't test the case where the names list does not contain the given last name; so the loop always terminates before it has a chance to throw an IndexOutOfBoundsException.

Especially the last case is easy to overlook, so it would be nice if there existed a tool which could detect these kinds of problems.
And there is one: actually there are a couple. For this post I have chosen PIT, down at the end are links to some alternatives.

But first: what is mutation testing?

A mutation test will make a small change to your code and then run the unit test(s). Such a change is called a 'mutant'. If a change can be made and the unit tests still succeed, it will generate a warning saying that the mutant 'survived'.
The test framework will try to apply a number of predefined mutants at every point in your code where they are applicable. The higher the percentage of the mutants that get killed by your unit tests, the better the quality of your test suite.
Examples of mutants are: negating a condition in an If statement, changing a conditional boundary in a For loop, or throwing an exception at the end of a method.

Putting NameParser's testcase to the test with PIT

PIT stands for Parallel Isolated Test, which is what the project originally was meant for. But it turned out to be a much more interesting goal to do mutation testing, which required much of the same plumbing.

PIT integrates with JUnit or TestNG and can be configured with Maven, Gradle and others. Or it can be used directly as a plugin in Eclipse or IntelliJ.
I'm choosing for the last option: the IntelliJ plugin. The setup is easy: just install PITest from the plugin manager and you are ready to go. Once you're done, you'll find a new launch configuration option in the 'edit configurations' menu called PIT.

PIT launch configuration

You have to specify the classes where PIT will makes its mutations under 'Target classes'.
When we run the mutation test, PIT creates a Html report with the results for every class.
Here are the results for the NameParser class:

NameParser mutation testing results

As you can read under 'Mutations', PIT has been able to apply five code mutations to the NameParser class. Four of them resulted in a failing NameParserTest, which is exactly what we'd like to see.
But one of them did not: when the condition boundary in line 6, the loop constraint, was changed, NameParserTest still succeeded!
PIT changes loop constraints with a predefined algorithm; in this case, when the loop constraint was i <= names.length, it changed the '<=' into a '<'. Actually this accidentally corrected the bug in NameParser, and of course that didn't break the unit test.
So PIT found an omission in our unit test here, and it turned out that this omission even left a bug undetected!

Note that this last point doesn't always need to be the case. It could be that for the correct behavior of your class, there is some room for some conditions to change.
In the case of NameParser for instance, it could have been a requirement that the names list always contained an entry with the last name that was to be found. In that case the behavior for a missing last name would be unspecified and an IndexOutOfBoundsException would have been as good a result as anything else.
So PIT can only find strong indications of omissions in your unit tests, but they don't necessarily have to be.

And here are the results for the Person class:

Person mutation test results

PIT was able to do two mutations in the Person class; one in every getter method. Both times it replaced the return value with null. And as expected, the mutation in the getLastName method went undetected by our unit test.
So PIT found the second omission as well.

Conclusion

In this case, mutation testing would have helped us a lot. But there can still be cases where possible bugs can go unnoticed. In our code for example, there is no test in NameParser test that verifies the behavior when an entry in the names list does not contain both a first name and a last name. But PIT didn't find this omission.
Still it might make good sense to integrate mutation testing in your build process. PIT can be configured to break your Maven build if too many warnings are found.
And there's a lot more that can be configured as well, but for that I recommend to bring a visit to the website of PIT at www.pitest.org.

Alternatives

PIT is not the only mutation testing framework for Java, but it is the most popular and the one most actively maintained. Others are µJava and Jumble.
Although most mutation testing frameworks are written for Java, probably because it's so easy to dynamically change its bytecode, mutation testing is possible in some other languages as well: notable are grunt-mutation-testing for Javascript and Mutator, a commercial framework which is available for a couple of languages.

Introducing a New Guide, “The Secrets to App Success on Google Play”

Android Developers Blog - Thu, 11/06/2014 - 17:31

By Dom Elliott, Google Play team

With more than 50 billion apps and games downloaded in total, Google Play is helping developers and content creators around the world build successful businesses. In fact, we paid out more than $5 billion over the last year to developers for creating incredible apps that are changing the way people communicate, live, work, and play.

Developing an app or game and distributing it on Google Play is a good start, but it’s only the first step to building a sustainable business. That’s why we’ve written “The Secrets to App Success on Google Play,” a detailed playbook on the best practices and tools you can use to maximize the reach, retention, and revenue of your new app.

The guide is separated into the following sections:

  • Publishing on Google Play — using the Google Play Developer Console to distribute your app to over 1 billion Android users worldwide.
  • Quality — The fundamentals of building a great app and an insight into the Google Play guidelines and policies.
  • Discoverability & reach — Maximizing your app's discoverability and reaching the widest audience possible.
  • Engagement & retention — Converting installations into active users and improving user retention.
  • Monetization — Monetization strategies to generate ongoing, growing revenue streams.
  • Measurement with Google Analytics — Understanding your users and improving your app experience, conversions, and marketing.
  • Going global — Launching your app in local markets around the world.

Download the guide now in English (PDF, 11MB) or get it on Google Play. We’ll release the guide in more languages in the coming months. If you’re in the US or the UK, we also have a limited number of printed copies that we are offering to send for free. Request a printed copy here.

Once you’ve checked out the guide, we’d love to hear your feedback so we can continue to improve, let us know what you think.

Join the discussion on

+Android Developers
Categories: Programming

Big Data Challenges in Regulated Industries

Software Requirements Blog - Seilevel.com - Thu, 11/06/2014 - 17:00
I have been working with a large financial services company on a “big data” project. Let me qualify the term “big data” for the purpose of this discussion. We are talking of dealing directly with about 10 million records and indirectly about 100 million records. The direct records (approximately 10 million) are those that are […]
Categories: Requirements

How To Improve the IT-Business Relationship

It’s possible to change IT from a poorly respected cost center to a high-functioning business partner.

Driving business transformation is a people, process, and technology thing.

Some people think they can change their business without IT.   The challenge is that technology is the enabler of significant business change in today’s digital landscape.  Cloud, Mobile, Social, and Big Data all bring significant capabilities to the table, and IT can hold the keys.

But the business doesn’t want to hear that.

Business Leaders Want to Hear About the WHY and WHAT of the Business

Business leaders don’t want to hear about the HOW of technology.

Business leaders want to hear about the impact on their business.   They want to hear about how predictive analytics can help them build a better pipeline, or target more relevant offers.   Business leaders want to hear about how they can create cross-sell/upsell opportunities in real-time.   And, business leaders want to hear about the business benefits and the KPI that will be impacted by choosing a particular strategy.

The reality is that the new Digital Masters of the emerging Digital Economy bring their IT with them, and in many cases, their IT even helps lead the business into the new Digital Frontier.

In the book, Leading Digital: Turning Technology into Business Transformation, George Westerman, Didier Bonnet, and Andrew McAfee, share some of their lessons learned from companies that are digital masters that created their digital visions and are driving business change.

How IT Can Change Its Game

While it takes work on both sides, IT can change it’s game by creating transparency around performance, roles, and value.  This includes helping employees think and talk differently about what they do.   IT can show very clearly how it delivers value for the money.  And IT can change the way IT and business leaders make investment decisions and assess the returns.

IT Needs to Speak Business

The CIO and everybody in IT, needs to speak the language of business.

Via Leading Digital:

“Poor relations between IT and business leaders can have many causes.  Sometimes it's the personality of the IT leader.  A common complaint among senior executives is that their CIO seems to speak a different language from the business.  Another is that the CIO doesn't seem to understand what's really important.  For example, a chemical company CIO we interviewed described how he communicates regularly with business executives about the innovative possibilities of digital technologies.  Yet none of his business executive peers (whom we interviewed separately) seemed to find the discussions credible.”

IT Needs to Deliver Better, Faster, and More Reliably than Outsourcing

It’s a competitive world and IT needs to continuously find ways to deliver solutions in a way that makes business sense.

Via Leading Digital:

“Sometimes the issue arises from IT's delivery capability.  According to Bud Mathaisel, who has served as CIO in several large companies, 'It starts with competence in delivering services reliably, economically, and at very high quality.  It is the absolute essential to be even invited into meaningful dialog about how you then build on that competence to do something very interesting with it.'  Unfortunately, some IT units today do not have this competence.  One business executive we interviewed said, 'IT is a mess.  It's costs are not acceptable.  It proposes things in nine or ten months, where external firms could do them in three to nine weeks.  We started offshoring our IT, and now our IT guys are trying to change.' A legacy of poor communication, byzantine decision processes, and broken commitments is no foundation on which to build a strong IT-business relationship.”

IT Needs a Good Digital Platform to Be High-Performing IT

In order to bet on IT, it needs to be high-performing.  And in order for IT to be high-performing, it needs to have a good digital platform.

Via Leading Digital:

“However, the fault doesn't always rest only with IT leaders.  In many cases, business executive share some of the blame ... high-performing IT requires a good digital platform, and good platforms require discipline.  If your approach to working with IT can be characterized by impatience, unreasonable expectations, or insisting on doing things your way, then you'll need to think about how to change your side of the relationship.”

CIOs Can Lead Digital Business Transformation

Key business transformation takes technology.  CIOs can help lead the business transformation, whether it's through shared goals with the business, creating a new governance mechanism, or creating a new shared digital unit.

Via Leading Digital:

“Regardless of the case, if your IT-business relationships are poor, it's essential to fix the problem.  A bank executive stated, 'IT has been brought closer to business during the last five years.  It is very important to success because man of the important transformations in our business are enabled by technology.'  With strong relationships, IT executives can help business executives meet their goals, and business executives listen when IT people suggest innovations.  Executives on both sides are willing to be flexible in creating new governance mechanisms or shared digital units.  At Codelco, Asian Paints, and P&G, the CIO even leads digital transformation for the company.”

CIOs Can Help Drive the Bus with the Executive Team

CIOs can help drive the bus, but it takes more than senior sponsorship.

Via Leading Digital:

“So, how can you start to improve your IT-business relationship?  Angela Ahrendts, CEO of Burberry, told her CIO he needed to help drive the bus with the executive team.  However, leadership changes or top-down mandates are only the start of the change.  Few CIOs can change the business by themselves, and not all business executives will climb on the bus with the CIO, even if the CEO demands it.”

Fix How You Communicate to Fix the IT-Business Relationship

Start by fixing how you communicate between the business and IT.

Via Leading Digital:

“Fixing the IT-business relationship can take time, as people learn how to trust each other and redefine the way they work together.  As with any struggling relationship, the best starting point is to fix the way you communicate.  Does IT really cost too much, or are costs reasonable, given what IT has to do? Is the IT unit really too bureaucratic, or do all of those procedures actually serve a useful purpose?  Are you a good partner to IT or a difficult one?  How can IT make it easier for you to get what you need, while still making sure things are done correctly?  What investments can help IT improve its technology, internal processes, cost-effectiveness, quality, or speed?”

Change IT from a Poorly Respected Cost Center to a High-Functioning Business Partner

It’s possible to change IT from a low performing cost center to a high-performing business partner.  Companies do it all the time, and MIT has the research.

Via Leading Digital:

“MIT research into IT turnarounds has identified a series of steps that can change IT from a poorly respected cost center to a high-functioning business partner.  The key change mechanism is transparency--around performance, roles, and value.  The first step is to help IT employees think, and talk, differently about what they do.  The second step proceeds to showing very clearly how well (or how poorly) IT delivers value for money--the right services at the right quality and right price, and where problems still exist.  And then the third step moves to changing the way IT and business leaders make investment decisions and assess the returns that projects deliver.  Through transparency around roles, performance, and investments, both sides can make smoother decisions and work together to identify and deliver innovation.”

If you’re part of a business that wants to change the world, start by reimagining how IT can help you achieve the art of the possible.

You Might Also Like

Building Better Business Cases for Digital Initiatives

Drive Business Transformation by Reenvisioning Your Customer Experience

Drive Business Transformation by Reenvisioning Your Operations

How Digital is Changing Physical Experiences

The Future of IT Leaders

Categories: Architecture, Programming

Chrome Plugins and Apps I Use Regularly

Making the Complex Simple - John Sonmez - Thu, 11/06/2014 - 16:00

In this video, I go over the Chrome Plugins and other non-developer apps I use regularly.

The post Chrome Plugins and Apps I Use Regularly appeared first on Simple Programmer.

Categories: Programming

Swift Function Currying

Xebia Blog - Thu, 11/06/2014 - 12:55

One of the lesser known features of Swift is Function Currying. When you read the Swift Language Guide you won't find anything about curried functions. Apple only describes it in their Swift Language Reference. And that's a pity, since it's a very powerful and useful feature that deserves more attention. This post will cover the basics and some scenarios in which it might be useful to use curried functions.

I assume you're already somewhat familiar with function currying since it exists in many other languages. If not, there are many articles on the Internet that explain what it is and how it works. In short: you have a function that receives one or more parameters. You then apply one or more known parameters to that function without already executing it. After that you get a function reference to a new function that will call the original function with the applied parameters.

One situation in which I find it useful to use curried functions is with completion handlers. Imagine you have a function that makes a http request and looks something like this:

func doGET(url: String, completionHandler: ([String]?, NSError?) -> ()) {
    // do a GET HTTP request and call the completion handler when receiving the response
}

This is a pretty common pattern that you see with most networking libraries as well. We can call it with some url and do a bunch of things in the completion handler:

doGET("http://someurl.com/items?all=true", completionHandler: { results, error in
    self.results = results
    self.resultLabel.text = "Got all items"
    self.tableView.reloadData()
})

The completion handler can become a lot more complex and you might want to reuse it in different places. Therefore you can extract that logic into a separate function. Luckily with Swift, functions are just closures so we can immediately pass a completion handler function to the doGET function:

func completionHandler(results: [String]?, error: NSError?) {
    self.results = results
    self.resultLabel.text = "Got all items"
    self.tableView.reloadData()
}

func getAll() {
    doGET("http://someurl.com/items?all=true", completionHandler)
}

func search(search: String) {
    doGET("http://someurl.com/items?q=" + search, completionHandler)
}

This works well, as long as the completion handler should always do exactly the same thing. But in reality, that's usually not the case. In the example above, the resultLabel will always display "Got all items". Lets change that into "Got searched items" for the search request:

func search(search: String) {
    doGET("http://someurl.com/items?q=" + search, {results, error in
        self.completionHandler(results, error: error)
        self.resultLabel.text = "Got searched items"
    })
}

This will work, but it doesn't look very nice. What we actually want is to have this dynamic behaviour in the completionHandler function. We can change the completionHandler in such a way that it accepts the text for the resultLabel as a parameter and then returns the actual completion handler as a closure.

func completionHandler(text: String) -> ([String]?, NSError?) -> () {
    return {results, error in
        self.results = results
        self.resultLabel.text = text
        self.tableView.reloadData()
    }
}

func getAll() {
    doGET("http://someurl.com/items?all=true", completionHandler("Got all items"))
}

func search(search: String) {
    doGET("http://someurl.com/items?q=" + search, completionHandler("Got searched items"))
}

And as it turns out, this is exactly what we can also do using currying. We just need to add the parameters of the actual completion handler as a second parameters group to our function:

func completionHandler(text: String)(results: [String]?, error: NSError?) {
    self.results = results
    self.resultLabel.text = text
    self.tableView.reloadData()
}

Calling this with the first text parameter will not yet execute the function. Instead it returns a new function with the [String]?, NSError? as parameters. Once that function is called the completionHandler function is finally executed.

You can create as many levels of this currying as you want. And you can also leave the last parameter group empty just to get a reference to the fully applied function. Let's look at another example. We have a simple function that sets the text of the resultLabel:

func setResultLabelText(text: String) {
    resultLabel.text = text
}

And for some reason, we need to call this method asynchronously. We can do that using the Grand Central Dispatch functions:

dispatch_async(dispatch_get_main_queue(), {
    self.setResultLabelText("Some text")
})

Since the dispatch_async function only accepts a closure without any parameters, we need to create an inner closure here. If the setResultLabelText was a curried function, we could fully apply it with the parameter and get a reference to a function without parameters:

func setResultLabelText(text: String)() { // now curried
    resultLabel.text = text
}

dispatch_async(dispatch_get_main_queue(), setResultLabelText("Some text"))

But you might not always have control over such functions, for example when you're using third party libraries. In that case you cannot change the original function into a curried function. Or you might not want to change it since you already using it at many other places and you don't want to break anything. In that case we can achieve something similar by creating a function that creates the curried function for us:

// defined in global scope
func curry<T>(f: (T) -> (), arg: T)() {
    f(arg)
}

We can now use it as following:

func setResultLabelText(text: String) {
    resultLabel.text = text
}

dispatch_async(dispatch_get_main_queue(), curry(setResultLabelText, "Some text"))

Probably in this example it might be just as easy to go with the inner closure, but being able to pass around partial applied functions is very powerful and used in many programming languages already.

Unfortunately the last example also show a great drawback about the way currying is implemented in Swift: you cannot simply curry normal functions. It would be great to be able to curry any function that takes multiple parameters instead of having to explicitly create curried functions. Another drawback is that you can only curry in the defined order of parameters. That doesn't allow you to do reverse currying (e.g. apply only the last parameter) or even apply just any parameter you want, regardless of its position. Hopefully the Swift language will evolve in this and get more powerful currying features.

20 Quotes about BDD and Agile Analysis

Good Requirements - Jeffrey Davidson - Thu, 11/06/2014 - 08:19

Kickstart Academy, a training organization where you get access to experts started a podcast series and I was privileged enough to be involved recently. Watch (click the image above or watch on Youtube) as Chris Matts interviews Kent McDonald, Jake Calabrese, and myself about the use and misuse of Given-When-Then, Behavior Driven Development (BDD), and business analysis in agile.

 

There were some great quotes (tweetable moments) and here are 20 of my favorite:

“Use Given-When-Then after the conversation, not during”

“You mean the special, princess, unicorn BA”

“BDD is here to make Eric Evans’ dream — everyone on the team understanding the domain — come to life”

“There are no BAs in agile … is an agile fairytale”

“The tools have made [BDD] into a developer focused thing, and not an ‘understanding’ tool”

“I have never seen a method for getting a BA from brand new or mediocre to competent or very good faster than BDD”

“BDD will help you [BA] do your job better!”

“The people you call ‘old-school’ are your organizations ‘tradition holders'”

“BAs are risk managers”

“Alistair Cockburn got something right when he said analysts should be called Value Managers”

“All the successful people do different things”

“The BA needs to shift from focusing on features and what to develop to what not to develop, maximizing what’s not done”

“I always start with the final THEN and then ask them what gets us to THEN”

“It’s an interview of what you’re doing”

“Can you think of an example where this outcome doesn’t happen? Can you think of a different outcome to this situation?” hat tip to @lunivore

“Where do you engage BDD in the [development] process?” “As soon as possible. And as late as possible.”

“Where do you engage BDD in the [development] process?” “Always. I don’t even understand how you can ask the question.”

“If the system’s not behaving, what is it doing?”

“I think, on the BA side, context is even more significant than it is on the software side, the technical side”

“The tools that are most effective are fairly simple, but have enough subtlety and nuance that they can be very powerful”

 

Here what you need to find and follow this great group:

 

If you are looking for more on Behavior Driven Development, then please check out my BDD Resource Page.

Categories: Requirements