SlideShare a Scribd company logo
1 of 52
Download to read offline
Healthy CodeMay 2014 1
Healthy Code May 20142
Healthy CodeMay 2014 3
Contents
HealthyCode
May 2014
Code Less, Do More 4
Interview - Rinish KN 14
SQL INDEX!= FASTER ACCESS 18
Domain Specific Languages in Python 26
The Joy of Functional Programming 32
Interview - Shyamala Prayaga 38
Code Retreat 42
Healthy Code May 20144
Healthy CodeMay 2014 5
Greetings!
Welcome to the May 2014 issue of Healthy Code magazine.
In this issue we serve you functional programming, DSLs,
Android coding and much more.
Venkat Subramaniam continues to enthrall by taking us a
step forward from his last month’s article ‘Learn to Learn’.
He leads us to the territory of Functional Programming
with the newborn Java 8.
If you have been dabbling in Android applications, you
can read Pranay’s article on building a Movie Review
application (Code Less Do More) in Android. In his article
he simply shows us how to build this whole application
from existing libraries that are available freely without
writing much code. Then, we have our myth busters(!),
about how creating index in Oracle doesn’t really improve
the performance. Plus, Siddharta is back with Python and
talks about creating DSLs this time.
Healthy Code interviewed Shyamala, UX designer at
Amazon about the future of Android design and she has
some interesting things to say.
What do mobile applications have in store for developers?
Rinish, CTO of RapidValue Solutions shares his insights
for you to read.
We are bent upon delivering technically focussed articles.
And that’s why your comments are most important. Keep
writing to us at feedback@healthycodemagazine.com.
Enjoy reading!!!
From the Editor
Healthy Code May 20146
Let’s build great Android apps with other’s code
Code Less,
Do More
Article
“I believe Android
will be stronger
in the developing
world than it is
in the developed
world.”
– Fred Wilson
Healthy CodeMay 2014 7
Thousands of Android applications are being built
everyday. With a significant number of Android
developers out there, a large volume of code is
being churned day in, day out. I can say for sure that
someone has already created much of the code our
developers write. This ‘already-created-code’ has also
been modularized as libraries and open sourced for
others to use in their applications. So, why reinvent
the wheel?
Isn’t it possible to develop a real time Android
application by using these libraries? Can’t we just
reuse the code and tweak it a bit and build a complete
application? Sure, we can, and I’m just going to do
that. In this article, we’ll see how we can leverage
various libraries that are available to rapidly develop
anAndroidapplication.Let’sbuildanawesomemovie
review application with as less coding as possible.
The Premise:
Welovemoviesandalotusaremoviebuffs.Whenever
a new movie is released or we want to watch a movie,
we check its ratings first. Most of the times, the movie-
watching decision is based on how others feel about
the movie, right?
But every time you want to watch a movie, you don’t
want to open your laptop to find the ratings, the cast
and other details. Wouldn’t it be awesome if we can
have a mobile app that can help us decide what to
watch? How about an app having an option to search
any movie from 2014 to 1950?
Sounds interesting, right? Figure 1.0 shows how our
application will look when it’s ready.
Let’s see how we can go about building this
application. We need a Movie rating API to start
with. We love IMDB, but IMDB does not have any
official API. For our app, let’s use the API from
Rotten Tomatoes. Then, we will use several Android
concepts such as Action Bar, Drawer, Asynchronous
Data Loading, listview, etc., and libraries like
ActionBarCompat, Retrofit, Picasso, Pull-to-Refresh,
NavigationDrawer, and Card UI. While I don’t have
enough space in the magazine for showing you how to
use all these libraries, this article will focus mainly on
ActionBarCompat, RetroFit, Picasso, Pull-to-Refresh
and Card UI libraries.
Let’s use Eclipse IDE for building the application.
Launch the Eclipse IDE in your ADT bundle. Create an
Android Application project called MoviesTomatoes.
See if you can get your MoviesTomatoes app running
in emulator or phone.
ActionBarCompat
ActionBarCompat is used to add action bars. It is
similar to the ActionBarSherlock library but provided
by Google and included in the new support library.
ActionBarCompat library is backward compatible
with all Android versions and Google recommends it
as well. You have to import the support library v7 into
your workspace to work with ActionBarCompat. And
here’s how you do that.
Click on File->Import->Android and choose
Existing Android Code into workspace option.
Locate your Android SDK folder and go to sdk/
extras/android/support/v7/appcompat. Import
Figure 1.0.The application that we plan to build.
PranayAiran
Healthy Code May 20148
this project in your workspace. Note: If v7 library
shows error you need to change the Android
version
Right click on your MoviesTomatoes project,
go to properties, and add the v7 project as library
dependency in Library section.
We can now add the action bar to our application
by configuring the action bar theme in our
AndroidManifest.xml file.
android:theme=”@style/Theme.AppCompat.Light.
DarkActionBar”
Go to MainActivity.java and make your class extend
ActionBarActivity.
import android.support.v7.app.ActionBarAc-
tivity;
public class MainActivity extends Action-
BarActivity {
...
}
Figure2.0shows how ourapplicationMoviesTomatoes
will look like once the action bar is added.
The complete code for integrating ActionBar
Compat can be found at https://github.com/
pranayairan/CodeLessDoMore/tree/master/
CodeLessDoMoreHelloActionBar.
Consuming the Rotten Tomatoes Service
As we’re going to use the Rotten Tomatoes API to get
the movie ratings and other information, we need to
register with Rotten Tomatoes and create an API key.
We’ll use this API key whenever we send requests to
their service.
You can go to http://developer.rottentomatoes.com/
member/register and create an account. Note: Select
Mobile Application in the application type checkbox
provided, and enter http://www.google.com in the
application URL textbox.
You will get your API key after the registration. I have
my key 9mxxxxx that you’ll notice being used in the
application. Keep your API key handy, as we will use
it to call the API.
Rotten Tomatoes is a RESTful service that returns
JSON response. I would strongly encourage you to
read about REST and JSON, if you are not aware of
these. Now, I’m going to show you a couple of ways
of accessing the API.
in box office here’s the URL:
http://api.rottentomatoes.com/api/public/v1.0/
lists/movies/box_office.json?limit=10&country=us
&apikey=9mXXXXXX
to access the details of a movie, you can use the
following URL:
http://api.rottentomatoes.com/api/public/v1.0/
movies/770672122.json?apikey=9mXXXXXX
Let’s consume these URLs in our application and
display the returned data.
We can display the list of movies running in box office
in a listview. If you don’t know about listview you
can read more about it at http://www.mkyong.com/
android/android-listview-example/
Retrofit:
In Android applications, you can create your
own thread by using classes like AsyncTask. ButFigure 2.0 MoviesTomatoes app with action bar
Healthy CodeMay 2014 9
AsyncTask comes with its own set of problems.
it.
same time, they run sequentially with each one
depending on the previous one to finish before
running. This makes your application slow.
We can avoid these problems by using Retrofit.
Retrofit is an excellent networking library from
Square, which helps us perform concurrent network
calls and parse the results and map them to a Java
Class at the same time. You can download Retrofit
from http://square.github.io/retrofit/. You can include
Retrofit jars to the libs folder of your project. Please
note that the GSON library needs to be added to the
build path to work with Retrofit. As we’re going to
fetch data from Rotten Tomatoes we have to add the
Internet permission in the AndroidManifest.xml file.
<uses-permission android:name=”android.per-
mission.INTERNET”/>
Retrofit serializes JSON data to Java objects. In our
application, let’s create the POJO for mapping JSON
data that displays the movie list. We can use online
JSON to Java generation sites like http://jsongen.
byingtondesign.com/, http://www.jsonschema2pojo.
org/ etc., for this purpose. Let’s generate a POJO
BoxOfficeMovies. You’ll need to include the generated
POJO in the project.
In MainActivity.java, let’s connect to Rotten
Tomatoes Service and get the list of movies using the
BoxOfficeMovies POJO we created. To do this let’s
create an interface BoxOfficeRunningMovie, and map
this interface to the Rotten Tomatoes URL.
public class MainActivity extends ActionBarAc-
tivity{
interface {
@GET(“/api/public/v1.0/lists/movies/box_
)
(@Query( ) String
limit,
@Query( ) String country,
@Query( ) String apikey,
}
}
…
}
The moviesList() method accepts four arguments
with the first three arguments annotated with @Query
annotation. The three @Query arguments map to the
three query string arguments in the URL.
http://api.rottentomatoes.com/api/public/v1.0/lists/
movies/box_office.json?limit=16&country=us&apike
y=9mXXXXX
The fourth parameter is a Retrofit callback that will be
called when the response is received.
Let’s consume this interface now by creating a
RestAdapter. The RestAdapter will create an instance
of the BoxOfficeRunningMovie interface. We can
invoke the moviesList() method to get the list of all
movies.
public class MainActivity extends ActionBarAc-
tivity {
…
onCreate(Bundle savedInstan
ceState){
new -
er.Builder().setEndpoint
build
restAdapter.create
class
new
@Override
response) {
int
ies.
getMovies().
Toast.makeText(MainActivity. ,
“Number of movies running in Box
+ moviesNumber,
Toast.LENGTH_LONG
}
@Override
Healthy Code May 201410
Toast.makeText(MainActivity. ,
“Error: “+
Toast.LENGTH_LONG
}
runningMovies. ( , ,
}
The moviesList() method has the callback instance
passed, which displays the result in a Toast for the
time being. Figure 3.0 shows the output when you
execute this code. That’s it!!! We have our Retrofit
boilerplate code completed.
ThecompletecodeforintegratingRetrofitcanbefound
at https://github.com/pranayairan/CodeLessDoMore/
tree/master/CodeLessDoMoreRetrofit.
Binding results with a listview
Let’s display the movie name, movie thumbnail
image, critics rating, audience rating and MPAA
rating in a list view. Each movie will be displayed in
a listview as shown in Figure 4.0.
I’m not going to delve in detail into this topic.
I have created an XML file for the list item, a
BoxOfficeMovieAdapter class to display the above
information. While discussing Retrofit you’d have
noticed that I had displayed the response from Rotten
Tomatoes in a Toast. We have to replace that code to
display the movie list in a list view.
new
@Override
Adapter = new
ty. ,
.setAdapter (movie
}
…
}
Figure 5.0 shows the listview of the movie application.
As of now the thumbnail of the movie in our listview
is not loaded as there is no way to load images directly
from an URL.
You can view the complete code for listview at https://
github.com/pranayairan/CodeLessDoMore/tree/
master/CodeLessDoMoreListView.
Picasso
Let’s load the thumbnail of the movies using Picasso.
In Android applications, loading images is an
interesting problem. If you want to get images from a
URL, you need to download the image first and then
display it in image view. To make the application
responsive we need to download this image in
background and then load it in image view. There are
lots of chances of duplication of images, so we need to
Figure 4.0. Movie item display
Healthy CodeMay 2014 11
cache those as well. To implement these, we need to
write many lines of boilerplate code.
Enter Picasso. Picasso is an amazing library
from Square, designed to solve the image
loading issue. There are lot of similar libraries like
UniversalImageLoader, UrlImageViewHelper, and
Volley that can be used for this purpose. You can
download Picasso from http://square.github.io/
picasso/ and add it to the project.
In the BoxOfficeMovieAdapter class we have to add
these two lines of code to load the movie poster image
in background and display it in thumbnail.
Picasso.with(ctx).load(runningMovie.get-
Posters().getThumbnail())
.placeholder drawable.ic_launcher)
.error drawable.ic_launcher)
.into(movieHolder.movieThumbnail
In the code above, runningMovie refers to each movie
instance in the collection of movies fetched from the
service.
Figure 6.0 shows the app once Picasso is integrated.
You can view the complete code of integrating Picasso
at https://github.com/pranayairan/CodeLessDoMore/
tree/master/CodeLessDoMorePicasso.
Pull-to-Refresh
I want to give users a way to refresh the movie list
without closing the application. We love Twitter and
Facebook where we pull to get the latest tweets and
posts, so why not add the same pull-to-refresh option
in our movie app?
To add pull-to-refresh we will use an excellent library
from Chris Banes called ActionBar PullTo Refresh.
You can get the library from https://github.com/
chrisbanes/ActionBar-PullToRefresh. As we already
have action bar in our application, this is the most
suited library for us.
Download ActionBar PullToRefresh library
from Github and import it in Eclipse. ActionBar
PullToRefresh is dependent on another library,
SmoothProgressBar. You can download this
library from https://github.com/castorflex/Smooth
ProgressBar. Note: It’s a bit difficult to build
Figure 5.0. Movies displayed in listview Figure 6.0. Movies list after Picasso integration
Healthy Code May 201412
these libraries using Eclipse. Include ActionBar
PullToRefresh library in your movie application
as a library project. We can introduce the Pull-To-
Refresh feature in our app by configuring the list view
inside the PullToRefreshLayout. You can do this by
replacing RelativeLayout with PullToRefreshLayout
in the activity_main.xml.
xmlns:android=
android:id= >
Our listview will be inside this new
PullToRefreshLayout. This wrapper will provide
necessary UI for pull to refresh. Let’s create an instance
of PullToRefreshLayout in MainActivity.java and set
it up.
-
id.ptr_layout
from( )
// Mark All Children as pullable
.allChildrenArePullable()
.listener( )
// Finally commit the setup to our Pull
setup
You can add the RefreshListener by implementing the
onRefreshStarted() method, which has your pull-to-
refresh logic. In our movie application, we can call the
Rotten Tomatoes web service again, get the response
and create a new instance of BoxOfficeMovieAdapter
class. Finally, you need to call setRefreshComplete()
to indicate that the pull-to-refresh action is complete.
-
plete
That’s it! With this simple integration, we have a pull-
to-refresh functionality in our application.
Now let’s enhance the look and feel of our application
using Card UI.
Card UI
Do you like the new Google Play UI? Google has
introduced a nice Card UI in their applications like
Google Play, Google Plus etc. We will try to create the
same look and feel for our application.
You can use Card UI libraries like https://github.com/
gabrielemariotti/cardslib but I’m going to keep things
simple in our application and implement Card UI by
just adding and tweaking some code. Let’s create a
custom drawable with a shadow, set our list view item
with this drawable and make some minor changes;
and we’ll have the card look and feel.
Create a new drawable say cards.xml and add the
following code that gives the card-like look and feel.
<layer-list xmlns:android= -
>
<item>
<shape>
<padding android:top=
android:right= android:bottom=
android:left= />
<solid android:color= -
/>
</shape>
</item>
<item>
<shape>
<padding android:top=
android:right= android:bottom=
android:left= />
<solid android:color=
/>
<corners android:radius= />
</shape>
</item>
<item>
<shape>
<padding android:top=
android:right= android:bottom=
android:left= />
<solid android:color=
Healthy CodeMay 2014 13
/>
<corners android:radius= />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color=
/>
<corners android:radius= />
</shape>
</item>
</layer-list>
You can change the background of the list item xml to
use the card created.
xmlns:android= -
android:layout_width=
android:layout_height=
android:paddingBottom= >
…
You can tweak the list view by adding margins,
modifying space between the cards, modifying
header and footer etc. We have our card look ready,
and figure 7.0 shows the application with enhanced
UI.
Figure 7.0 Movie app with enhanced Card UI
Figure 8.0: Movie app after integrating
Navigation Drawer
Healthy Code May 201414
Engineer @ Intuit, developing web and mobile
applications, Pranayholds a Masters degree from
IIIT Bangalore. He is passionate about building
mobile applications and hacking on new web
technologies, and he helps Blrdroid as Assistant
organizer as well. Pranay has been developing
Android apps from the last 3 years and has
developed a variety of apps personally and @
Intuit. He has more than seven apps in Google
Play Store. He conducts workshops in colleges
where he likes to share his knowledge and helps
students get start with android under Blrdroid
Teach Program.
You can find the code for Card UI in https://github.
com/pranayairan/CodeLessDoMore/tree/master/
CodeLessDoMoreCardsUI.
You can enhance the application further by integrating
Navigation Drawer and the application will look
as shown in figure 8.0. The code for integrating
Navigation Drawer is available at https://github.
com/pranayairan/CodeLessDoMore/tree/master/
CodeLessDoMoreNavigationDrawer.
I have shared the complete code for the article in the
Github repository, https://github.com/pranayairan/
CodeLessDoMore.
Publisher:
T. Sivasubramanian
Editor:
S. Prabhu
Production:
New Horizon Media Private Limited
Proof Reader:
Shweta Gandhi
Publication Address:
11/6, First Floor,
Fourth Street,
Padmanabha Nagar,
Adyar, Chennai - 600020
Printer: Sakthi Scanners (P) Ltd
7, Dams Road, Chindadripet,
Chennai - 600002.
Contact Phone Number: 044-42337379
Email:
siva@healthycodemagazine.com
Web Site:
Price: Rs. 150 /-
Healthy Code
May 2014
Vol. 1 | Issue. 2
Disclaimer:
The articles and contents of the Healthy Code magazine
are sourced directly from the authors with their
permission.HealthyCodedoesn’tassumeresponsibility
for violation of any copyright issues by an author in
their respective article. We have made sure to the best
of our knowledge that the articles and code presented
here are without any errors. However, we can’t be held
liable for any damage or loss that may arise from using
these.
- Publisher
Pranay
Healthy CodeMay 2014 15
Pragmatic BookShelf’s Seven X in Seven Weeks series
is quite popular, and this is another interesting book
from their stable. In spite of being two years old,
it still serves as a fantastic introduction to NoSQL
databases even now. Jim Wilson and Eric Redmond
(also, author of, ‘Programming Google Glass’), are the
authors of this book
It talks about NoSQL databases like MongoDB,
CouchDB, Redis, Riak, HBase and Neo4J. The only
RDBMS database that’s been discussed is Post-
greSQL. The choice of the databases in the book has
been clearly explained in the introductory section.
Each chapter takes up one database, introduces it
and tells you how to set it up. The ritualistic CRUD
operations are discussed with simple code-based
examples. The chapter then explores the core fea-
tures of the database, and winds up discussing
the strengths and weaknesses. It also highlights a
number of other features, which can be explored
outside the book.
Apart from the regular exercises at the end of each
day of discussion what’s interesting is the variety of
examples covered to explain the concepts. Unlike
a lot of technical books that run through a single
problem in all the chapters, each database is ex-
talks about creating and playing with cities, Couch-
DB talks about music and so on.
My favorite read is the chapter on MongoDB be-
cause of the succinct introduction to sharding and
replication concepts.
-
ent databases, it is a treat for the experienced to un-
- Prabhu Sunderaraman
SevenDatabases
inSevenWeeks
EricRedmond,JimR.Wilson
Book Review
Healthy Code May 201416
How did you decide to start a company that
focuses on mobile technology?
In 2007, Apple came out with iPhone, and it
changed the mobile phone world dramatically.
All research at that time pointed out to a growing
mobility and cloud market. It was then that we
started RapidValue Solutions and decided to focus
on mobility and build a niche for ourselves.
What was the predominant mobile
technology at that time?
It was primarily the Apple iOS as that time.
Building a
Mobility Business
Interview
H
ealthy Code spoke to Rinish KN, Chief
Technology Officer of RapidValue
Solutions, an end-to-end enterprise
mobility services provider based out of Pleasanton,
California with offices in India (Kochi and
Bangalore). Rinish has previously worked as an
architectatOracleandWipro,buildinge-commerce
websites, before he co-founded RapidValue
Solutions with Rajesh Padinjaremadam and Sirish
Kosaraju in 2008. Here are the excerpts from that
chat.
Blackberry was also very popular. In those days,
Apple competed with Blackberry. In the Android
space, the first HTC phone was released in 2008.
What was the first opportunity that you got
for your company?
First, we had to prove to ourselves that we could
build mobile applications. So we hired a Java
developer. There were three managers and one
programmer. We built a simple expense tracking
application system for iPhone and Android to
prove our capability. After that, we started getting
interesting projects and customers.
?
?
?
Healthy CodeMay 2014 17
Was the learning curve pretty
high for your team initially?
In India, we always have more
Windows developers than Mac
developers. When iOS entered
the market, it was very new to all
of us. However it’s not difficult to
learn the platform. The developer
guide of Apple is very helpful. They
have very good videos, articles and
documentation. Their XCode editor
is awesome. We learnt most of the
technical details from their developer
portal. Even today we hire straight
Java programmers, C++ and C#
developers and train them in mobile
development using the same way.
What kind of applications did
you start building first?
We started building native
applications initially for iPhone and
Android. Native applications are the
ones that you have to download from
App Stores such as Apple’s iTunes
or Google Play Store on your mobile
before you can use them. With Native
apps, users can make use of phone
capabilities like Camera, GPS, offline
browsing etc.
We started building business to
customer (b2c) applications. A
good example of this kind would be
like media/publishing application,
music streaming applications and
retail product catalogs. These native
applications interface with the
server to access data from content
management systems and provide
you the latest information on the
phone just like your client-server
applications.
What kind of applications are you developing today?
Over the last five years, we have expanded from mobile
application development to providing end-to-end enterprise
mobility services. Our services include mobile strategy, UX/UI
design, mobile app development, enterprise system integration,
mobile testing and ongoing support and maintenance.
We are now developing a lot of applications for large enterprises
and many Fortune1000 companies. Some of the applications
include:
HR Management Service by which employees can apply for
leave, view pay slips etc.
Mobile Commerce by which consumers can view and
purchase products online.
Inventory Management App for scanning at warehouses for
receiving goods and managing inventory.
Physicians Communication and Scheduling App for doctors
to interact with their staff.
Rinish K N
?
?
?
Healthy Code May 201418
Online Class Room App for University faculty
to interact with students, and many more types of
applications across industry segments. In many
cases, we are extending the ERP systems for
access from mobile devices.
In addition to mobility services, we have recently
launched a global product ‘eQuipMeTM
’, a mobile
field service suite which connects field service
technicians and customers in real-time from any
mobile device.
Tell us a little bit about mobile websites.
How different are they different from
native applications?
The evolution of mobile websites is very similar
to the evolution of web applications. Long ago,
we moved from Mainframes to Client Server
Computing. With the advent of Internet and we
started building web applications.
Similarly in the mobile space, you can view the
native application as a client server application
interacting with a server at the backend. Mobile
websites are similar to web applications. You
simply use the browser in the mobile phone and
connect to your application on the web server.
Even though any website can be viewed from the
mobile browser, you need to build a mobile website
to leverage the features of the mobile phone and
for proper rendering.
However, now a days many are building websites
with responsive design. Responsive websites are
a notch better than mobile websites. There are so
?
Healthy CodeMay 2014 19
through the year?
Yes. Mobile development is a fast-paced business.
We typically deliver a full application in 3 months
on average. But in most cases, we continue the
client relationship for 2 to 3 years, either in the
same project or other projects. So, sustaining
development team is not an issue for us.
Is it possible to build a large-sized company
with prime focus on mobile development?
Absolutely. The enterprise mobile application
space is rapidly growing. The company budgets
for building mobile applications are increasing
every year. RapidValue currently has over 200
employees. Given that we have expanded rapidly
in the past five years (employees, offices and
customers), we are expecting 100% Y-o-Y growth.
We strongly believe we can do it!
What are your thoughts on wearable
devices and Google Glass etc.?
It certainly looks like the future. Previously, we
never thought our phones would connect to the
Internet. Now we do it every day. Cars are getting
connected to the Internet in the US. Google Glass
is another good example. Wearable devices and
connected devices is where RapidValue will focus
in the coming years.
Now that mobile technology has so many
job opportunities, where does a developer
stand in the mobile space?
Actually mobile development is quite similar to
Java development. People who have knowledge in
Java or C# can get into mobile development. For
a Java developer, learning Android is similar to
learning Spring or Hibernate Framework. Anyone
having knowledge in object oriented programming
can start on mobile application development.
Passion for learning is the key.
many types of phones in different sizes and shapes
available today. So your mobile web application
should adjust to the multiple phone sizes and
platforms. A responsive website will do that for
you.
If the requirement is to reach out to a large number
of users as in mobile commerce application, mobile
websiteisthebestoption,andifrichuserexperience
and phone capabilities need to be enabled for the
mobile app, native app development is the right
approach. Another option is the Hybrid Mobile
Web App which has some capabilities of mobile
website and some of native app.
What are Hybrid applications?
Hybrid applications are a mix of native and other
types. The UI is built with HTML 5 and JavaScript.
The same JavaScript is used for accessing native
features of the phone like Camera, Gyroscope, etc.
You use technologies like PhoneGap, Titanium
Appcelarator or RhoMobile to achieve this. These
frameworks take care of the native code that is
needed to run your application across different
platforms like iPhone and Android.
There are so many Mobile JavaScript
frameworks like jQuery mobile, Sencha
Touch, Kendo, etc. How does a developer
navigate this JavaScript land?
It is better for a developer to have multiple skills.
They should pick up HTML 5, JavaScript, iOS or
Android to begin with. There are many JavaScript
frameworks, but once you pick one up, you should
be able to switch to others. Just like if you know
Java, you can easily learn to program in Servlets,
JSP, Hibernate and Struts. It’s similar to that.
Sencha Touch is very rich in UI. jQuery Mobile is
very light-weight. All these frameworks have their
own advantages and once you know any one of
these frameworks, the switch is not very hard.
There is a perception that mobile
application projects are short term (3-4
months). How do you sustain development
?
?
?
?
?
?
Healthy Code May 201420
Article
INDEX!=
Healthy CodeMay 2014 21
= FASTER ACCESS
Ankit Kumar Katiyar & N.S.Sekar
O
ne of the frequently encountered solutions
that application developers are offered, while
dealing with performance issues with the
oracle database is: “create an index on that column”.
This may enhance the performance in some cases if
you know your index well enough. However this can
actually degrade or not have any significant impact
on the SQL performance in the application at all.
Therefore it’s important to be aware of the behavior
of index if you want to leverage its true potential. We
have identified a bunch of issues while working with
index in Oracle and discussed them in this article.
Here’s a list of concerns raised by developers and our
response to them.
Concern #1:
I have created an appropriate index on particular
column. But why is the query engine not picking up
the index?
This may happen due to bad or incomplete statistics.
In the absence of statistics, the optimizer (Cost based
optimization) may choose a full table scan (FTS) as
compared to indexed access.
Recommendations:
Prior to testing queries, just make sure you re-analyze
the table and index with dbms_stats. This provides
the optimizer with good metadata.
You can use the following queries to check the last
analyzed status.
You can use the following queries to execute the dms_
stats procedure to analyze objects.
Concern #2:
I have created an appropriate index on a particular
column and I have also verified the earlier step
discussed in Concern#1. I still see that oracle is not
using that index.
This may happen if the number of rows in that table
is less or your query is returning almost all the data
in a table.
Recommendations:
If table is small that it can be read in a single I/O call,
then a full table scan of table might be cheaper than
an index range scan. Single I/O call can be defined by
Healthy Code May 201422
DB_FILE_MULTIBLOCK_READ_COUNT parameter
and value defined by blocks.
If your query is returning the majority of the data in a
table, then a full table scan is probably going to be the
most efficient way to access the table and optimizer
may choose to decide that it would be more efficient
not to use the index.
Concern #3:
I have created proper B-Tree Index on the particular
column and have also analyzed the table and index.
I still don’t find oracle using that index.
Oracle B-TREE Indexes can surely help in improving
the query performance provided there is optimal
selectivity on that column. The ratio of the number
of distinct values in the indexed column/columns
to the number of records in the table represents the
selectivity of an index. Ideal selectivity is 1 in case of
primary key and unique key.
While optimizing, oracle takes a decision of choosing
an index based on I/O. As discussed earlier, if the
query is returning the majority of the data in a table,
then a full table scan is probably going to be the most
efficient way to access the table.
Recommendations:
We should create indexes on tables that are
often queried for less than 15% of the table’s rows.
This value may be higher in situations where all
data can be retrieved from an index, or where the
indexed columns can be used for joining to other
tables.
Please check if you have right index on that
column. In other words, in oracle while standard
B-tree indexes are most effective for columns
containing a high number of different values
(good selectivity), bitmapped indexes are most
appropriate for columns with a limited number
(poor selectivity) of possible values.
In general, B-tree indices are good for OLTP
and Bitmapped indices are good for OLAP systems.
Factor in your usage, prior to creating the index.
Concern #4:
I have a query
Healthy CodeMay 2014 23
The query engine is still not using the index.
If you are using the SQL “like” clause then it can
be tricky because the wildcard “%” operator can
invalidate the index.
Recommendations:
STRING% will do INDEX RANGE SCAN
data because optimizer knows where the string
gets started.
% STRING will do the INDEX FULL table
because LIKE expression that starts with a
wildcard.
%STRING% will perform the FULL table scan
because optimizer doesn’t know from which letter
the String get started.
Concern #5:
I have a query,
I also have a proper index on id column. Why is the
query engine still not using the index?
If you have got a WHERE clause which contains
something like “id is null” then query engine will
always perform the full-table scan because NULL
values cannot be indexed. If you have no choice, but to
have this condition in your query, consider replacing
it with a NVL function.
Recommendations:
If you have a null in your where clause you may
have to keep the following in mind:
When you have “IS NOT NULL” type
WHERE clause will use an index
When you have “IS NULL” type WHERE
doesn’t use an index
Concern #6:
I have a query,
I have proper index on name column then why is the
query engine not utilizing an index?
Healthy Code May 201424
Even though the name column has an index, the upper
functions will invalidate the index and WHERE clause
predicates might invoke FTS (unnecessary I/O).
Recommendations:
In such cases, use Function-Based index on that
column. Function-Based indexes give the ability to
index computed columns and use theses indexes in a
query as shown here.
Concern #7:
I have created a Function-based index on a table
column, yet when I check my execution plan, the
optimizer ignores the Function-based index?
Typically, function-based indexes or any index
are ignored when analyze the index has not been
performed.
Recommendations:
After creating a function-based index, don’t forget to
re-gather table statistics and get extended statistics on
the function.
Concern #8:
I have a query,
I have a proper index on these columns but no use
of the index.
This may happen if you are performing mathematical
operations on the indexed column then oracle will
invalidate the index and will go for the full table scan.
Concern #9:
I have a following query
In this case name column is indexed but oracle is not
using an index. Why?
When an indexed column appears on both sides of an
operator, the index for that column is disabled.
Recommendations:
You can rewrite the above-mentioned query as
Concern #10:
I have following query
Inspite of having a proper index on these columns
why doesn’t oracle use it?
If we use the NOT EXISTS then nested index scans
will be used in the sub query for each row in the
DEPARTMENT table. The only records that will be
returned from DEPARTMENT are those that return
no rows from the sub query, and no full table scans
are performed by the sub query.
Recommendations:
The following query statement is more efficient.
department.department_id=employee.
department_id)
Concern #11:
In my query, I have an index on a DATE column
but oracle is not using index if I fetch results using
JDBC driver?
This might happen due to data type conversion
between Date and TimeStamp. Developers, typically
use the setTimestamp method in order to set time.
When this is done, the index on the DATE column
will not be used. This is because, oracle internally
converts/casts datatypes (of date to timestamp) .
Recommendations:
You can address this problem with the following:
Healthy CodeMay 2014 25
Concern #12:
In spite of having index on “first_name” and “last_
name” columns the query
“
takes much longer than expected.
The use of ‘OR’ statements confuses the optimizer
(Cost Based Optimizer). It will rarely choose to use an
index on column referenced using an OR statement.
Recommendations:
You can work around this issue by using UNION
ALL as shown here.
Concern #13:
I have created composite index on the column but
how does it work with my query?
A composite index contains more than one key
column. Composite indexes can provide additional
advantages over single column indexes. Consider
creating a composite index on columns that are
frequently used together in WHERE clause conditions
combined with AND operators, especially if their
combined selectivity is better than the selectivity
of either column individually. Even If you do not
include the first column of a concatenated index in the
WHERE clause of your statement then also Index Skip
Scanning will be used.
Summary
This article was just a brief overview at database
indexing with some light on b-tree index, bitmap
indexes, function-based indexes, and composite
indexes. Index efficiency is hard and finding
appropriate index even harder. We hope that these
tips when used appropriately may help you debug
performance issues, even after you have created the
index on the relevant columns.
In general, when things are really slow due to a SQL
statement, in your application, use the EXPLAIN
PLAN to look at the execution plan of the statement.
Following this, make the changes in your SQL based
on cost estimation.
Remember that “FULL TABLE SCANS ARE NOT
ALWAYS BAD” and “SQL INDEX != FASTER
ACCESS” in all scenarios.
Happy indexing!!!
Ankit Kumar is currently serving Successfactors
(SAP Cloud) as a Principal Engineer. His work is
with the Employee Central (EC) product wherein
his main focus is to make EC world’s most high-
performing, scalable, and blazing fast cloud
platform. Prior to this, he worked with Oracle
as a technology lead and Hewlett Packard (HP)
as a software analyst. He holds a patent and
disclosure in database and network technologies,
respectively.
NS Sekar
Sekar is Vice President of Engineering at Success
Factors. He has previously worked as Director
at Yahoo and Informatica. He is a seasoned tech-
nology and product development executive with
experience in building and scaling distributed en-
gineering and product teams from multiple ear-
ly-stage startups to the next level. His expertise
includes Data Integration, Data Quality, Web Ana-
lytics, Internet Platforms, and SaaS
Ankit Kumar
Healthy Code May 201426
Regional Scrum
Gathering India
July 11, 12 - Hyderabad
With the theme of “Humane Scrum”, the Region-
al Scrum Gathering® India 2014 focuses on explor-
ing techniques, tools, behaviors, and experiences
that help bring about the mind-set so essential to
-
tions small and large.
Venue:
Hotel Trident,
HITEC City, Near Cyber Towers,
Madhapur, Hyderabad, AP 500 081.
http://scrumgatheringindia.in/
tiConf India will be a single day event
featuring some of the best Titanium de-
velopers and evangelists from around
the globe. We will be talking everything
about Titanium, Mobile Development,
Cloud and JavaScript.
Venue:
25 Windsor Square, Golf Course Road
Bangaluru 560 052
Karnataka, India
Website: http://ticonf.org/
Rootconf 2014
May 16-17, 2014, Bangalore
Rootconf is a conference that will help you plan
and develop a strategy map for infrastructure
and devops. It will show you the building blocks
for reaching a strategy for Continuous Integra-
tion, Deployment and Delivery.
Target audience: Organizations who need a CI
developer teams and performance of their web
stacks.
Venue:
MLR Convention Centre, J.P. Nagar
Brigade Millennium Complex, J.P. Nagar 7th Phase
Bangalore, Karnataka India.
Website:
Technology Conferences
JULY 19, 2014
Healthy CodeMay 2014 27
the art of continuous improvement
Each backed by more than a decade of
experience, our agile consultants and
coaches work with managers and teams
to address people, process and products
for a more comprehensive approach.
Lean + Agile Assessment
Agile Management Consulting
Agile Team Coaching
Lean Product Innovation
Get the real-world insight, practical advice
and experience needed to lead your team,
speed time to market, and boost morale.
We offer classes for all levels, including:
Agile Engineering
Agile Testing Workshop
Scrum Product Owner Training
ScrumMaster Training
Organizational Intro to Agile
Great teams build great products.
Achieve a state of continuous team
improvement with Sensei, a simple
retrospective tool for agile teams.
Try it for free, no obligations:
• www.lithespeed.com • 703.745.9125 • @lithespeed
Our combined customer discovery and agile
product development won’t just get you to
an MVP: It will provide your team with the
hands-on training to set up and to run
effective experiments long after the
engagement ends.
*
*
*
*
*
*
*
*
*
*
*
*
SenseiTool.com
Phase 1: Getting Started + Product Discovery
Phase 2: Accelerating Discovery + Introducing
Agile Development
Phase 3: Transition and Closeout
Healthy Code May 201428
Domain Specific
Languages in
Python
Article
Healthy CodeMay 2014 29
An interface should be designed in such a way that
the code, which a programmer writes, is almost same
as what he or she is thinking in their head. Such an
interface is termed as natural. With a natural interface,
there is less translation to do when converting from
the mental model to the actual code itself. This is
beneficial not only when writing code, but it is also
easier to understand the intent when reading the code
later on.
One way to create an interface that is as natural as
possible is via Domain Specific Languages (DSL).
Domain Specific Languages
Generally speaking, we use a general purpose
programming language to get our job done. However,
because they are a general purpose, we may
sometimes have to go through unnatural hoops to get
things done. Let us take a simple example of pattern
matching.
Suppose we want to determine if a given string
represents an IP address. The process of doing so
might involve taking the string, splitting it up on the
period, and then checking if there are exactly 4 parts,
and whether each part is a number between 0 to 255.
A Python implementation might look like this:
(ip_address):
components = ip_address_string.split( )
if len(components) != 4: False
:
int_components = [int(component) for
component in components]
except :
False
for component in int_components:
if component < or component > :
False
True
To someone looking at the code for the first time, it is
not obvious what pattern this code is matching. Also,
if we want to change the pattern that is being matched,
then it isn’t straightforward to make the change.
Using regular expressions, we can change the code to
something like this:
def is_ip(ip_address_string):
match = re.match(
,ip_address_string)
if not match: return False
for component in match.groups():
if int(component) > : return False
return True
In regular expression notation, the string “^(d{1,3}).
(d{1,3}).(d{1,3}).(d{1,3})$” amounts to matching
4 groups of digits, each group having 1-3 digits,
separated by periods.
Anyone can look at the regular expression and
understand the pattern that is being matched. If we
need to make a change to the pattern, then it is easy to
plug in the new pattern in the code.
Regular expressions are an example of a domain
specific language. It is a language that allows us to
express the pattern, rather than an implementation on
how to match the pattern. We are thinking in our head,
“I need to match four integers separated by a period,”
andtheregularexpressionallowsustoputthatdirectly
into the code. Without regular expressions, we need
to do a lot more work in translating our mental model
into the code when writing it, or understanding the
intent when reading the code, leading to unintuitive
or difficult to understand code.
There are many other DSLs that we use daily without
even realising it. For example, SQL is a domain
specific language for retrieving data from a relational
data source. By using SQL we can communicate very
clearly about what data we want to retrieve rather
than specifying how the data should be retrieved.
Now that, I have opened the doors of DSL, let’s walk
through the features of DSLs.
External v/s Internal DSL
There are two types of DSLs: External and Internal.
In an external DSL, a special syntax is used as a
language. This syntax is specified as a string or in an
external file. The regular expression interface that we
saw above is an example of an external DSL.
Internal DSLs don’t use an external syntax. Instead,
they make use of the syntactical features of the
programming language cleverly to make the interface
more natural.
Let’s discuss this External and Internal DSLs with an
example. To begin with, let us decide the public API
that we are going to use to make the calculations.
Siddharta Govindaraj
Healthy Code May 201430
There are two ways we can design the interface for the
calculator.
Internal DSL: Provide classes that we use to
create the expression that we want to evaluate.
External DSL: Use an expression syntax,
which we must parse and evaluate.
Calculator: Internal DSL way
The code snippet for the Calculator using the Internal
DSL approach looks like this.
Add( , Mul(2, 3 , 6)).evaluate()
, Add(3, 4)), ).evaluate()
We build up the expression using normal python
classes like Add, Div and Mul, which are evaluated
to give the result.
Implementing the Internal DSL syntax as shown
above is an interesting premise in Python.
Let us start with the Add class. Add should be able to
take any number of parameters in the constructor, and
return the sum when the evaluate method is called.
import operator
from functools import reduce
class Add( ):
def __init__(self
self.terms = args
def evaluate(self):
return reduce(operator.add, self.terms)
This simple implementation handles adding a series
of constants:
>>> Add( , 3).evaluate()
4
>>> Add(2, 4).evaluate()
6
But, the Add class should also be able to take other
expressions as a parameter. Add(1, Add(2, 3)) should
The words ‘static’ and ‘synchronized’ are a
menace to Test Driven Development.
Continuing to use a miserable developer tool is
like being complacent in an abusive relationship
-- why not get out for a better life?
Pragmatic
Programmer
Quotes
Healthy CodeMay 2014 31
also return 6. Our current implementation will give
an error because in the evaluate method we assume
all the terms are numbers.
There are two ways to handle this. One way is to
check for expressions and call evaluate on the sub-
expression before adding. Such an implementation
will look like this:
(self):
total =
for term in self.terms:
if isinstance(term, Add):
total += term.evaluate()
:
total += term
total
The other option is to create a Number class with an
evaluate method. A number will always evaluate to
this example.
( ):
(self, value):
self.value = value
(self):
self.value
With this class in place, we can modify the Add class
to evaluate each expression before adding the values.
( ):
(self):
reduce(operator.add, [term
evaluate() for term in self.terms])
Now we can add both numbers and sub-expressions.
When evaluate is called on a term, it will return the
number or evaluate a sub-expression, depending on
which object it is. Unfortunately, this change means
that we have to wrap numbers in the Number class
and we have to now invoke the Add class like this
>>> Add(Number( ), Number(2)).evaluate()
>>> Add(Number( ), Add(Number(2), Number(3))).
evaluate()
6
This syntax looks ugly, but we’ll get back to that
problem later. For now, we have support for sub-
expressions. Let’s go ahead and implement Sub, Mul
and Div.
( ):
(self
self.terms = args
(self):
reduce(operator.sub, [term.
evaluate() for term in self.terms])
( ):
(self
self.terms = args
(self):
reduce(operator.mul, [term.
evaluate() for term in self.terms])
( ):
(self
self.terms = args
(self):
reduce(operator.truediv, [term.
evaluate() for term in self.terms])
With these classes in place, we can now start mixing
operators.
>>> Add(Number( ), Mul(Number(2), Number(3)),
), Number(6)))
Okay, now that the basic functionality is working, let
us clean it up a bit. First, there is that annoying need to
wrap up numbers in the Number class, which makes
the interface quite ugly and verbose. Second, there is
a fair bit of duplication between the various classes.
it accepts numbers and internally wraps them in the
Number class.
import
( ):
(self
self.terms = [self.wrap_term(term)
for term in args]
(self, term):
Number(term) if isinstance(term,
term
To clean up the duplication, we create a base Operation
class and put all the common functionality in there.
After the change, the code looks like this:
Healthy Code May 201432
Operation( ):
(self
self.terms = [self.wrap_term(term) for
term in args]
(self, term):
Number(term) if isinstance(term,
term
(self):
reduce(self.operation, [term.
evaluate() for term in self.terms])
(Operation):
operation = operator.add
(Operation):
operation = operator.sub
(Operation):
operation = operator.mul
(Operation):
operation = operator.truediv
We can now use the module in a more natural way!
>>> Add( , Mul(2, 3 , 6)).evaluate()
, Add(3, 4)), ).evaluate()
>>> Add( , 3)).evaluate()
Calculator: External DSL way
calculator.evaluate(“ + 2 3 + / 6 )
calculator.evaluate(“ 3 + 4 ) / )
In the External DSL approach, we pass the input as a
parse and evaluate. We will reserve the external DSL
implementation for later article.
External and Internal DSLs.
In short, if the main users for your package are going
to be other developers (for example, if you are creating
a module that will be used like a library with other
modules), then it is worthwhile to see if the language
contains a natural syntax that you could adapt into
an Internal DSL. Otherwise, go for an external DSL
interface.
The complete code of the article can be downloaded
from
2014
External DSL Internal DSL
Can use the most natural syntax Syntax limited by syntax of programming language
Easy to understand the intent Easy, but less than an external DSL
Can be maintained by non-programmers Cannot be maintained by non-programmers
Requires that you implement parsing logic No parsing required
Siddharta Govindaraj is the founder
of Silver Stripe Software, a product
company based in Chennai. He is
active in the Chennai tech, agile and
entrepreneur communities in his free
time.
Siddharta
Healthy CodeMay 2014 33
Healthy Code May 201434
The Joy of
Functional
Programming
Article
Healthy CodeMay 2014 35
style is the one that most of us are familiar with, and
the functional style is the one that has been around for
as long, but as a well-kept secret.
Imperative v/s Functional Style
Most of us have programmed in imperative style,
maybe without realizing it. It’s not our fault that
we’ve been taught to code that way, and most of the
languages within our reach promote that style.
Imperative style is primitive; we express our ideas in
detail, telling not just what, but how to do things. At
After all, computers follow instructions, and it’s our
duty to give them.
Functional style is declarative; we express our ideas
at a higher level of abstraction and let the underlying
-
ity.
Let’s get a feel for them using a few examples.
Taking Full Control
-
visible by any number other than 1 and itself. So, we
can set out on that task, iterating through all numbers
a divisor, bingo, the number is not prime. Let’s code
that logic in Java, just the way we described:
{
( number,
divisor){
}
( number){
for( i=2
if
}
number>
}
}
We started at the value of 2 and iterated through each
number until we reach the target value. If the target
was divisible by any index, we break out of the loop
declaring that the number is not prime. If we com-
pleted the loop, we make one last check, to see if the
The Power of Expression
If we ask a fellow programmer what they under-
stand by programming, we may hear words like cod-
ing, compiling, execution, and so on. But, in essence,
it’s an act of communication, a form of expression. It’s
not just expressing ideas for execution by the comput-
ers. It’s more than that, a lot more, in fact. It’s what we
create so fellow developers, and ourselves, can main-
tain moving forward.
Much like writing in a natural language like English,
there are several ways to express ideas. Some writings
are easy to grasp while others are hard to follow. Pro-
grams are like that, and if we’re keen, it’s not hard to
A good code should read like a story, not like a
puzzle.
pick either active or passive voice. The former gives
Programming has similar styles.
What is popular or the most familiar is not necessar-
There are at least two styles of programming in use to-
day, one more widely used than the other. Imperative
Venkat Subramaniam
More than which language we pro-
in it. Almost every mainstream pro-
-
of syntax. In languages, as in love,
we have to see beyond the looks very
quickly. In this article, we will discuss
semantics of what we express. We will
also look at the key reasons to use this
style of programming and how we
Healthy Code May 201436
of primes.
That’s familiar code, but it’s primitive and low level.
A quick glance at the code, we see that the loop stands
among the numbers in range – is lost.
Focusing on the Essence
Let’s try that exercise again, this time using a more de-
clarative style of functional programming, using Java
8 (see References.).
import
{
( number,
divisor){
}
( number){
number > &&
range(2,number)
.noneMatch(index-
}
}
In this version, we raised the level of abstraction and
concisely expressed: in the range of values from 2 to
the given number (not inclusive) ensure none match
Functional code reads like the problem statement.
The focus here is on the essence – what we’re inter-
ested in rather than the mechanics of how to get that.
Imperative style feels like giving instructions to a
toddler. Functional style feels like communicating
with a responsible adult.
Let’s leave the primes examples behind for just a bit
and explore other aspects with a few more examples.
Favoring Immutability
Functional style promotes immutability. Most of us
are used to mutating variables. Sometimes it’s hard to
imagine how we could solve a problem without muta-
tion. Let’s look at an example. In the next code we use
imperative style to total all even values in a collection.
int
int result =
for(int e:values){
if 2 == )
}
}
Given a list of values, once again in this example,
we loop through the values cherry picking the even
values and accumulating them. The result is being
mutated repeatedly as we loop through the values.
This has two limitations. The for loop provides only
sequential looping and, furthermore, the mutation
makes it harder to make the computation concurrent
for a large list. Let’s rewrite this in functional style.
int
values.stream()
. 2 == )
.reduce( ,Math:
}
Let’s read that aloud to see what’s going on: Given a
reduce (sum) the values using the addExact method,
using 0 as the initial value, and return the result. This
code also begins to read like the problem statement.
Again, we focus on what instead of how. Further-
more, we avoided mutability, that leads to fewer
moving parts, and that, in turn, helps to minimize er-
rors. Later we will see how that can help with concur-
rency as well.
Favoring Functional Purity
a value of x = 5, what’s the result of the computation
below?
x++ +6 + x++;
your guess. Instead, ask yourself how you feel when
had to decipher it. The chances are we would get con-
fused and get it wrong. We don’t have to endure that,
-
ware to develop and to deliver value.
Healthy CodeMay 2014 37
2 * x + 7;
A pure function or expression does not modify or af-
outside. Pure functions are easier to understand as
they have fewer moving parts. They’re also easier to
test – for a given input, the output is always the same.
We would need fewer tests for pure code than code
is referential transparency. The compiler can replace,
where possible, the code with the result of the compu-
tation. Furthermore, the compiler can freely reorder
expressions or functions that are pure. That ability to
dynamically optimize code is very useful to exploit
concurrency on multicore processors.
We saw that functional style promotes declarative
code and favors immutability. In addition, functional
style brings higher order functions. A higher order
function can accept functions as parameters, may
create functions, and may return functions. In other
words, we can do with functions what we’re used to
do with objects. This leads to some powerful capabili-
ties, one of which is lazy evaluation.
Since we can pass functions to functions, instead of
evaluating the parameter function before the call, we
can postpone its evaluation for later (or even skip it).
faster, but avoiding things that don’t have to be done.
faster, but by avoiding those that shouldn’t be done
Let’s look into an example of laziness. In the double-
FirstEven method we take a list of values
even values, double each of them, but only pick the
(int number){
System.out.println(“isEven called for “+num-
2 ==
}
int
ues){
values.stream()
. ( ::isEven)
.map 2)
. ()
.orElse(
}
-
doubleFirstE-
ven method before we ponder further.
(1, , ,4, ,6,
7,8, ,10
We called the doubleFirstEven method with a list of
ten values. Let’s take a look at the output from this
code.
In the previous example, the method picked only
the values for which the invoked method (isEven) re-
turned true and the map method transformed the val-
ues by doubling them. Finally the method
Healthy Code May 201438
Even though we had ten values in the input list
the isEven method was evaluated only twice. This is
due to lazy evaluation of the functions presented to
the and map methods. Rather than evaluating
the argument functions right away the Stream (which
is part of Java 8, other languages have similar data
structures) postpones their evaluation. Furthermore,
the Stream fuses the methods together, optimizing
the execution to only the most essential steps. While
this involves quite a bit of complexity under the hood,
such optimization is possible due to function purity.
Easy Concurrency
Let’s revisit the isPrime example that we looked at in
the beginning of the article. If the candidate number
for prime check is small, then the time taken is not
If the number is large, we would want to employ mul-
tiple threads, especially on a multicore processor.
If we started with the imperative style code, turning
that into multithreaded code is not easy. We have to
split the results across threads, and then merge back
and error prone.
Making the function style code concurrent is almost
do that for us and we only have to give it a nod. Let’s
see how.
a function named isPrimeSequential.
( number){
number > &&
range(2,number)
.noneMatch(index-
}
We iterate on a range of values, looking for the pat-
tern of divisibility.
For large numbers, we can make the computa-
the Stream library in Java 8 does that already and all
we have to do is simply ask, like in the next example.
( number){
number > &&
range(2,number)
.parallel()
.noneMatch(index-
}
TDD is a skill; it involves a
decent amount of unlearning,
relearning, and reevaluation.
Let's not expect to get good at it
instantly.
You know it’s time to take a
break when you’re fixated to
review and fix code printed on
the back of someone’s T-shirt.
Pragmatic
Programmer
Quotes
Healthy CodeMay 2014 39
We used the parallel() method on the Stream to turn
the lazy collection into a lazy parallel collection. Un-
der the hood the library uses a special kind of iterator
called a spliterator to parallelize the execution. Let’s
measure the time for the two versions.
number =
System.out.println(TimeIt.code(()->
new MeasurePrime().
System.out.println(TimeIt.code(()->
newMeasurePrime().isPrimeConcurrent
Here’s the output from this code.
As we can see there is a substantial speed improve-
ment between the sequential and the concurrent ver-
on our part. The JDK library took care of most of the
work for us and all we had to do was provide it a few
pure functions.
Recap
of programming in this article. Overall we are able to
Declarative code keeps us focused.
The what can be varied independent of the
how.
The code begins to read like the problem
statement.
Has reduced chance of errors due to fewer
moving parts.
Easier to test due to purity.
Once we get our heads wrapped around it, it is a pure
joy to program in functional style.
You can access the code for the article from
github.com/healthycodemagazine/May2014
References
Java 8 Download:
html.
Venkat Subramaniam, Functional Programming in
Java: Harnessing the Power of Java 8 Lambda Expres-
sions. Pragmatic Bookshelf, 2014.
com/titles/vsjava8.
Dr. Venkat Subramaniam is an award-winning author, founder
of Agile Developer Inc., and an instructional professor at the
University of Houston.
He has trained and mentored thousands of software developers
in the US, Canada, Europe, and Asia, and is a regularly invited
speaker at several international conferences. Venkat helps his
software projects.
Venkat is a (co)author of multiple books, including the 2007 Jolt
Productivity award-winning book Practices of an Agile Developer.
His latest book is Functional Programming in Java: Harnessing the
Power of Java 8 Lambda Expressions.
You can reach him by email at venkats@agiledeveloper.com or on
Venkat
Healthy Code May 201440
as your calling in life?
Interesting question! Design has always been my
passion and I feel like a born designer. During
-
nal workshop on usability, which was a paradigm
shift for me. That’s when I realized designing is
not only making things beautiful, but also making
things usable irrespective of age, ability and situa-
tion. That one workshop changed the way I think
and work, and that’s when I decided to become a
UX Designer.
What was the best Android UX project you
have worked on? Why?
For any designer, all their projects are the best as
every design has a challenge and a learning experi-
ence.
Shyamala Prayaga is a seasoned
UX (User Experience) designer
at Amazon. She specializes
in mobile and web usability
standards and accessibility.
She designs and delivers cross
platform mobile-user experi-
ence across iPhone, Android,
Blackberry, Palm Pre and Win-
dows Mobile, and is passionate
about speaking at conferences
and workshops. Healthy Code
spoke to Shyamala about the
future of Android design, and
here are the excerpts:
The Future of
Android Design
Interview
Healthy CodeMay 2014 41
Jokes apart, one of my best Android UX projects
was an automotive shopping tool. When a user
decides to buy a vehicle, there's a lot of market
research, friends reviews and competitive analy-
sis. After all the research done, sometimes there's
a long waiting period to purchase the shortlisted
model, because it may not be available with the
dealer, or the desired color is not available and so
shortlisted model/color with some other dealers
with less or no waiting time and purchase them?
We were trying to solve this problem and the so-
Number) Scanning. Designing the whole UX for
this application was so challenging and fun.
What do you see as the biggest challenge in
designing for Android Mobile?
Almost every year Android comes up with a big
release of their operating system, leaving apart the
frequent patches, which brings in lot of UX and UI
changes too. Since the design principles are still not
consistently moving in one direction, it becomes
something that’s sustainable for a longer period.
This leaves designers to think in one direction and
revamps, which I think is a big challenge.
Is there such a thing as a mature design?
Before talking about mature design, we need to
ask ‘What is a design?’ In my opinion, design is
a solution to a problem that you have. There can
be many ways to solve the same problem through
various designs. Some can be very complicated,
some can be straightforward and simple, and some
can be intuitive.
I would say any design is mature, if it is able to
achieve the goal it was intended for with minimum
What does Android design have in store
for the future?
I think future Android design will include Aug-
mented Reality, Gesture Based Interaction and
Voice Based Interactions.
What do you mean by Augmented Reality?
Shyamala Prayaga
This is a very interesting concept and an emerg-
ing technology where we can map the virtual re-
ality with the actual reality and interact with the
applications. With Augmented Reality catching
interactions, so why would Android lack behind?
would be Augmented Reality based.
Imagine I am using an online shopping application
and can try products real time using the mobile’s
camera and augmenting self live, as in a mirror.
Or imagine playing cricket on a smartphone and
augmenting yourself as one of your favorite play-
ers. How much fun would it be!
You also mentioned Enhanced Gesture
Based Interactions. What is that?
Android smartphones have become a one-shop
stop for all the needs of the users right from online
banking, shopping, playing games, and reading
books. Ah, reading books, interesting!
Imagine reading e-books by just using hand ges-
tures and camera sensors, rather than swiping,
tapping, pinching etc., to turn pages, zoom pages,
Healthy Code May 201442
and more. Rather than using a touch or swipe to
scroll pages in my application, just by using ges-
tures, I can control the entire application. Wouldn’t
that be fun?
This is the future of Android design, which I fore-
see for all the reading needs.
How does Voice Based Interactions work?
Imagine how easy it would have been if you could
speak and control interactions of your smartphone,
like a robot:
By speech you could decide which applica-
tion you want to open, download, browse, inter-
act with.
By speech you could decide whom to call,
what to search for etc.
By speech you could draft a huge mail, mes-
sages, status messages of social apps like FB,
WhatsApp.
By speech you share images, videos, send
as a future concept that Android would try.
With Facebook acquiring WhatsApp, So-
cial Media and Instant Messaging have
gained lot of momentum and competition.
How do you predict the future of messag-
ing in Android?
-
quent upgrades it is making to its Hangout. I pre-
dict a universal messaging system as the future of
Android Mobile, where rather than having sepa-
rate applications for video calling, voice calling,
instant messaging and emailing, they would pro-
vide an all-in-one solution where the UI will be
slip between functionalities.
Or who knows, maybe Android mobile would
ship it as a default in-built functionality of the fu-
ture devices.
Every Android release has a unique play-
ful name. Can you guess what the next one
would be?
Looking at the past trends with Android coming
up with interesting names like KitKat, Jelly Bean,
Ice Cream Sandwich, Eclair, the interesting future
name could be chocolates like “Perk”, “Crunch”,
“Snickers” or some deserts name like “Cheese
Cakes” or “Rice Pudding.” Alphabetically, Lolli-
pop or Lemon Pie sounds perfect, but I am sure it
won’t be Apple Pie!
Healthy CodeMay 2014 43
Healthy Code May 201444
Article
Have you been to a
Code Retreat
lately?
Bharadwaj is a product
manager at Appnomic
Systems in Bangalore.
hosted by Multunus
in Bangalore and
conducted by Venkat
Subramaniam. Here’s a
sneak-peek of the event
from his eyes.
Healthy CodeMay 2014 45
What is a Code Retreat?
Code retreats are day-long coding fests. Program-
mers take a crack at solving Conway’s Game of Life
Puzzle in multiple short sessions. Each session is for
45 minutes. Developers work in pairs (miniature ex-
treme programming sessions). Every session starts
with a clean slate, that is, no carryover code at all. Test
Driven Development (TDD) is encouraged. After ev-
ery 45-minute session, a 15-minute stand-up meeting
follows where everyone gets to share his or her expe-
rience and things that they have learnt. At the end of
the stand-up, the group may decide to impose some
constraints for the next session like not using classes,
no global state, no-returns-from-any-methods, etc.
The choice of programming language, framework
and design are all left to the pair. This meet-up at Mul-
tunus had close to 25 programmers who kept on hack-
ing away the whole day.
Conway’s Game of Life
alive or dead. Every cell interacts with its eight neigh-
bors (just like the good old Tic-Tac-Toe game grid).
Any live cell with fewer than two live neigh-
bours dies, as if caused by under-population.
Any live cell with two or three live neighbours
lives on to the next generation.
Any live cell with more than three live neigh-
bours dies, as if by overcrowding.
Any dead cell with exactly three live neigh-
bours becomes a live cell, as if by reproduction.
You can learn more about the game at
en.wikipedia.org/wiki/Conway's_Game_of_Life.
solve the puzzle along with writing tests (remember,
we are using TDD) especially, if one is a newbie to ei-
ther the puzzle or the language chosen. However, the
fun is not in solving the puzzle itself, but it lies in the
One can read more about the format and structure of
Bharadwaj
Healthy Code May 201446
JS ever. That straightaway exposed our weakness! Since we did not have
time to learn a new framework we decided to hand-code the tests. I remem-
ber writing some code that seemed to solve something. Along the way I
re-discovered the right way to write inner functions in JavaScript. That was
the highlight for me!
Session III – Back to Scala
The next session had me pairing up with a Java guy who wanted a sneak-
peek into Scala. This time we used my laptop to code. In order to give him
text-editor. I wanted to stay clear of ScalaTest and Scala’s build system - so
as to give my partner a good look at some mass of code and not distract him
While coding, I had this nagging realisation that I had not understood the
problem well enough. I wanted some thinking-time away from coding and
just focus on the puzzle. We were nearing lunch time also. So I decided to
Session IV – Playing with Python
Code Retreat at the community
website -
My Experience
I, along with my partner (pair
programmer), programmed in
4 languages, namely - Scala,
JavaScript, Python and Ruby!
Here is a brief on each of my
sessions.
Session I – Dive into Scala
Programming
Both my partner and I had prior
experience with the language.
Thankfully, my partner was fa-
miliar with the problem too. We
quickly discussed and zeroed in
on a subset of the problem we
-
ing in Game of Life) and agreed
on a simple design. We started
The test part straightaway ex-
posed my poor knowledge of
the ScalaTest. Later while writ-
ing code, we got stuck in trying
to write object equality in Scala
- something I could do with my
eyes closed in Java. That was
the second time my limitations
were exposed. We programmed
on my partner’s computer, and
he used Gradle, which was a
Session II – Playing with
JavaScript
JavaScript (JS) was common
lingo with my next pair-pro-
gramming partner in the sec-
ond session. Neither of us had
used any testing frameworks in
Healthy CodeMay 2014 47
in Python. This guy had given a good thought into
the problem and the approach we came up with was
very refreshing! He coded away in Python, which I
found easy to follow, and we wrote a lot of code. We
were quite close to solving one of the situations in the
game when the time ran out. Writing so much code to
solve the problem meant that the test code was mini-
mal during this session. However, I was beginning to
appreciate the complexity and immense freedom of
design that this simple-looking puzzle posed at us.
Session V – Rolling with Ruby
There were lot of Ruby developers in the group, and
I was very curious to get a feel for this language. So I
chose a Ruby-man for the last session. This person was
much younger than me but surprised me by his thor-
ough approach to TDD. He insisted on evolving the
test code almost simultaneously with the main code,
and I must admit, it did frustrate me initially. I wanted
to write a blob of test code, write a blob of solution
code, and keep alternating between the two. However,
my partner, who was the one coding in Ruby, would
have none of it. He requested that we keep shifting
gears between the test-code and solution-code for ev-
ery few lines of code. I knew he had a good point in
what he was suggesting, and asked if he was really
able to code like that in his work. His answer was af-
-
ated the young programmer’s discipline.
Epilogue
It’s not every day that I force myself to think on good
programming problems. This was an excellent oppor-
tunity for that. That itself made me immensely happy.
I was split on approaching the problem from a bot-
tom-up or top-down approach – which had me think-
ing about an aspect of design that I had not thought
for some time. I don’t remember the last time I pair
programmed before this event. It’s a fabulous thing,
and I want to grab every opportunity of doing so in
future as well. The code retreat certainly pushed me
away from my comfort zone, and that’s a great way to
learn. Having not solved the problem still nags me.
One of these days, I will sit down to write code that
solves Conway’s Game of Life to at least some extent.
Healthy Code May 201448
Already, a few approaches are brewing in my head. I
recommend Code Retreat to all developers. Try to get
in the next time it is happening somewhere nearby in
your city.
Last but not the least, Venkat put forth some wonder-
ful thoughts on the endeavour of software develop-
ment. I also saw a great start-up in Multunus. The day
was a delight. Big thanks to all my partners in Code
Retreat, and all those who made the event possible. If
it comes around, I am going again.
Bharadwaj works as a technical product
manager at Appnomic, and was previously
with HP. He programs mostly in Scala and
JavaScript, and is also quite comfortable with
Java and Octave. He has done his MBA from
IIMB.
Bharadwaj
W
e all want to create a
simple design, but the act
of creating such a design
is not that simple.
W
e looked at this problem
and said we can solve it
using a pool of threads.
Now we have a pool of problems.
O
ur field has fundamentally
transformed in the last two
decades, from developers
fighting DLL hell to fighting
assembly and jar hell.
Pragmatic
Programmer
Quotes
Healthy CodeMay 2014 49
Healthy Code May 201450
With time developers soon realized that
JavaScript, the most used language of the
web is missing a proper build system and
JavaScript task runner. Do you want to run
your JavaScript tests? Grunt has it covered;
production? Well, Grunt takes care of that
too. This article will talk about playing
with Grunt in web applications.
and technology conference speaker gave an
exclusive interview to Healthy Code when he
about the current state of Groovy and Grails
and the issues companies face in moving
away from Java to embrace it. He discussed
the latest web favorite HTML 5 and how
it has changed the way web applications
are developed today. He also spoke about
several toolkits and libraries that are popular
among developers.
Functional programming promotes
pure functions or functions with no
hygiene while programming has a
purity with examples.
Coming up in the June issue
Functional Hygiene:
Reasons to Avoid
side effects
Get your Grunt on
- Rocky Jaiswal
Interview with
Ember-Data is a module of Ember.js that
allows us to bind our client side logic
seamlessly with backend services. It has been
coming for quite a while and needless to say,
even in its nascent stages, it managed to make
our lives much easier than what it used to be.
Now we have reached a stage where Ember-
Data 1.0 seems almost around the corner. This
article aims to familiarize the reader with
Ember-Data’s functionality and philosophy.
On the Way to
Ember - Data 1.0
– Dr. Venkat Subramaniam
– Abhimanyu Chakravarty
Owned and Published by T. Sivasubramanian. Published from 11/6, First floor, Fourth street, Padmanabha Nagar, Adyar,Chennai -
600020 and printed by M. Elumalai, at Sakthi Scanners (P) Ltd, 7, Dams Road, Chindadripet, Chennai - 600002. Editor: S.Prabhu.
Healthy CodeMay 2014 51
Healthy Code May 201452

More Related Content

What's hot

Mobile apps idea to making money
Mobile apps   idea to making moneyMobile apps   idea to making money
Mobile apps idea to making moneyDavid Bozward
 
10 Design Trends 2013
10 Design Trends 201310 Design Trends 2013
10 Design Trends 2013DMI
 
Material Design on Android
Material Design on Android Material Design on Android
Material Design on Android droidcon Dubai
 
Textpert UI Report and Problem
Textpert UI Report and ProblemTextpert UI Report and Problem
Textpert UI Report and ProblemQing Jasmine Ye
 
Android Design Guidelines 1.1
Android Design Guidelines 1.1Android Design Guidelines 1.1
Android Design Guidelines 1.1Mutual Mobile
 
Productivity Apps and Tools for Workplace version (0.8.2)
Productivity Apps and Tools for Workplace version (0.8.2)Productivity Apps and Tools for Workplace version (0.8.2)
Productivity Apps and Tools for Workplace version (0.8.2)DreamKonnect Consulting
 
QuiZone Mobile Application
QuiZone Mobile ApplicationQuiZone Mobile Application
QuiZone Mobile ApplicationAyush Kanoongo
 
UI-UX Practical Talking - Mohamed Shehata
UI-UX Practical Talking - Mohamed ShehataUI-UX Practical Talking - Mohamed Shehata
UI-UX Practical Talking - Mohamed ShehataMohamed Shehata
 
UX / UI Mobile Trends
UX / UI Mobile TrendsUX / UI Mobile Trends
UX / UI Mobile TrendsMark N Swaine
 
Portfolio_UX Designer Miona Bojanovic
Portfolio_UX Designer Miona BojanovicPortfolio_UX Designer Miona Bojanovic
Portfolio_UX Designer Miona Bojanovicmiona bojanovic
 
Session 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationSession 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationVu Tran Lam
 
Mobile UI Design Patterns 2014
Mobile UI Design Patterns 2014Mobile UI Design Patterns 2014
Mobile UI Design Patterns 2014Lewis Lin 🦊
 
Uxpin mobile UI Design Patterns 2014
Uxpin mobile UI Design Patterns 2014Uxpin mobile UI Design Patterns 2014
Uxpin mobile UI Design Patterns 2014Jessie Doan
 
UX, UI design portfolio for mobile and tablet applications
UX, UI design portfolio for mobile and tablet applicationsUX, UI design portfolio for mobile and tablet applications
UX, UI design portfolio for mobile and tablet applicationsPrasad Coorg
 

What's hot (19)

Mobile apps idea to making money
Mobile apps   idea to making moneyMobile apps   idea to making money
Mobile apps idea to making money
 
Android UI Design Tips
Android UI Design TipsAndroid UI Design Tips
Android UI Design Tips
 
10 Design Trends 2013
10 Design Trends 201310 Design Trends 2013
10 Design Trends 2013
 
Material Design on Android
Material Design on Android Material Design on Android
Material Design on Android
 
Textpert UI Report and Problem
Textpert UI Report and ProblemTextpert UI Report and Problem
Textpert UI Report and Problem
 
Android Design Guidelines 1.1
Android Design Guidelines 1.1Android Design Guidelines 1.1
Android Design Guidelines 1.1
 
transcend viewer
 transcend viewer transcend viewer
transcend viewer
 
Productivity Apps and Tools for Workplace version (0.8.2)
Productivity Apps and Tools for Workplace version (0.8.2)Productivity Apps and Tools for Workplace version (0.8.2)
Productivity Apps and Tools for Workplace version (0.8.2)
 
QuiZone Mobile Application
QuiZone Mobile ApplicationQuiZone Mobile Application
QuiZone Mobile Application
 
Responsive Web Design Whitepaper
Responsive Web Design WhitepaperResponsive Web Design Whitepaper
Responsive Web Design Whitepaper
 
UI-UX Practical Talking - Mohamed Shehata
UI-UX Practical Talking - Mohamed ShehataUI-UX Practical Talking - Mohamed Shehata
UI-UX Practical Talking - Mohamed Shehata
 
UX / UI Mobile Trends
UX / UI Mobile TrendsUX / UI Mobile Trends
UX / UI Mobile Trends
 
Portfolio_UX Designer Miona Bojanovic
Portfolio_UX Designer Miona BojanovicPortfolio_UX Designer Miona Bojanovic
Portfolio_UX Designer Miona Bojanovic
 
Session 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationSession 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 application
 
UX & UI Design 101
UX & UI Design 101UX & UI Design 101
UX & UI Design 101
 
Mobile Monday
Mobile MondayMobile Monday
Mobile Monday
 
Mobile UI Design Patterns 2014
Mobile UI Design Patterns 2014Mobile UI Design Patterns 2014
Mobile UI Design Patterns 2014
 
Uxpin mobile UI Design Patterns 2014
Uxpin mobile UI Design Patterns 2014Uxpin mobile UI Design Patterns 2014
Uxpin mobile UI Design Patterns 2014
 
UX, UI design portfolio for mobile and tablet applications
UX, UI design portfolio for mobile and tablet applicationsUX, UI design portfolio for mobile and tablet applications
UX, UI design portfolio for mobile and tablet applications
 

Similar to HealthyCodeMay2014

Why big organizations like tesla, facebook, walmart, skype are using react na...
Why big organizations like tesla, facebook, walmart, skype are using react na...Why big organizations like tesla, facebook, walmart, skype are using react na...
Why big organizations like tesla, facebook, walmart, skype are using react na...MoonTechnolabsPvtLtd
 
React Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfReact Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfTechugo
 
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...Laura Miller
 
Where All Libraries & Data Required For Android App Development Are Present
Where All Libraries & Data Required For Android App Development Are PresentWhere All Libraries & Data Required For Android App Development Are Present
Where All Libraries & Data Required For Android App Development Are PresentTechugo
 
Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Katy Slemon
 
Comparisons react native vs. flutter vs. ionic vs. xamarin vs. native script
Comparisons  react native vs. flutter vs. ionic vs. xamarin vs. native scriptComparisons  react native vs. flutter vs. ionic vs. xamarin vs. native script
Comparisons react native vs. flutter vs. ionic vs. xamarin vs. native scriptMoonTechnolabsPvtLtd
 
the benefits of react native to developing ios and android application from s...
the benefits of react native to developing ios and android application from s...the benefits of react native to developing ios and android application from s...
the benefits of react native to developing ios and android application from s...Whitelotus Corporation
 
10 Advantages Of Using Django For Web Development.pdf
10 Advantages Of Using Django For Web Development.pdf10 Advantages Of Using Django For Web Development.pdf
10 Advantages Of Using Django For Web Development.pdfSatawareTechnologies6
 
9 reasons why programmers should learn react native
9 reasons why programmers should learn react native9 reasons why programmers should learn react native
9 reasons why programmers should learn react nativeReact Sharing
 
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...Katy Slemon
 
React Native for React Developers v.2.0.pdf
React Native for React Developers v.2.0.pdfReact Native for React Developers v.2.0.pdf
React Native for React Developers v.2.0.pdfNikolaGorgiev
 
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023Pedro Vicente
 
React Native- The Future of Mobile App Development.
React Native- The Future of Mobile App Development.React Native- The Future of Mobile App Development.
React Native- The Future of Mobile App Development.Techugo
 
React Native Market Overview for Cross-Platform App Development.pdf
React Native Market Overview for Cross-Platform App Development.pdfReact Native Market Overview for Cross-Platform App Development.pdf
React Native Market Overview for Cross-Platform App Development.pdfTechugo
 
Reactjs Vs React Native – Key Difference, Advantages, And Disadvantages
Reactjs Vs React Native – Key Difference, Advantages, And DisadvantagesReactjs Vs React Native – Key Difference, Advantages, And Disadvantages
Reactjs Vs React Native – Key Difference, Advantages, And DisadvantagesAndolasoft Inc
 
What is React Native and When to Choose It For Your Project.pdf
What is React Native and When to Choose It For Your Project.pdfWhat is React Native and When to Choose It For Your Project.pdf
What is React Native and When to Choose It For Your Project.pdfNarola Infotech
 
Write Your iOS App in Swift with a Graph Database
Write Your iOS App in Swift with a Graph DatabaseWrite Your iOS App in Swift with a Graph Database
Write Your iOS App in Swift with a Graph DatabaseAnthony Blatner
 
Top 10 React Development Tools to Choose in 2023.pptx
Top 10 React Development Tools to Choose in 2023.pptxTop 10 React Development Tools to Choose in 2023.pptx
Top 10 React Development Tools to Choose in 2023.pptx75waytechnologies
 
What to choose for Mobile app development- React Native vs Native.
What to choose for Mobile app development- React Native vs Native.What to choose for Mobile app development- React Native vs Native.
What to choose for Mobile app development- React Native vs Native.Techugo
 
15 android libraries for app development
15 android libraries for app development15 android libraries for app development
15 android libraries for app developmentConcetto Labs
 

Similar to HealthyCodeMay2014 (20)

Why big organizations like tesla, facebook, walmart, skype are using react na...
Why big organizations like tesla, facebook, walmart, skype are using react na...Why big organizations like tesla, facebook, walmart, skype are using react na...
Why big organizations like tesla, facebook, walmart, skype are using react na...
 
React Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdfReact Native App Development in 2023-Tips to Practice.pdf
React Native App Development in 2023-Tips to Practice.pdf
 
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...
IONIC VS. REACT NATIVE – WHICH FRAMEWORK IS BETTER FOR CROSS-PLATFORM MOBILE ...
 
Where All Libraries & Data Required For Android App Development Are Present
Where All Libraries & Data Required For Android App Development Are PresentWhere All Libraries & Data Required For Android App Development Are Present
Where All Libraries & Data Required For Android App Development Are Present
 
Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021Top mobile app development frameworks to consider in 2021
Top mobile app development frameworks to consider in 2021
 
Comparisons react native vs. flutter vs. ionic vs. xamarin vs. native script
Comparisons  react native vs. flutter vs. ionic vs. xamarin vs. native scriptComparisons  react native vs. flutter vs. ionic vs. xamarin vs. native script
Comparisons react native vs. flutter vs. ionic vs. xamarin vs. native script
 
the benefits of react native to developing ios and android application from s...
the benefits of react native to developing ios and android application from s...the benefits of react native to developing ios and android application from s...
the benefits of react native to developing ios and android application from s...
 
10 Advantages Of Using Django For Web Development.pdf
10 Advantages Of Using Django For Web Development.pdf10 Advantages Of Using Django For Web Development.pdf
10 Advantages Of Using Django For Web Development.pdf
 
9 reasons why programmers should learn react native
9 reasons why programmers should learn react native9 reasons why programmers should learn react native
9 reasons why programmers should learn react native
 
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...
React Native Adoption at Bacancy Technology: The Journey from Beginners to Be...
 
React Native for React Developers v.2.0.pdf
React Native for React Developers v.2.0.pdfReact Native for React Developers v.2.0.pdf
React Native for React Developers v.2.0.pdf
 
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
 
React Native- The Future of Mobile App Development.
React Native- The Future of Mobile App Development.React Native- The Future of Mobile App Development.
React Native- The Future of Mobile App Development.
 
React Native Market Overview for Cross-Platform App Development.pdf
React Native Market Overview for Cross-Platform App Development.pdfReact Native Market Overview for Cross-Platform App Development.pdf
React Native Market Overview for Cross-Platform App Development.pdf
 
Reactjs Vs React Native – Key Difference, Advantages, And Disadvantages
Reactjs Vs React Native – Key Difference, Advantages, And DisadvantagesReactjs Vs React Native – Key Difference, Advantages, And Disadvantages
Reactjs Vs React Native – Key Difference, Advantages, And Disadvantages
 
What is React Native and When to Choose It For Your Project.pdf
What is React Native and When to Choose It For Your Project.pdfWhat is React Native and When to Choose It For Your Project.pdf
What is React Native and When to Choose It For Your Project.pdf
 
Write Your iOS App in Swift with a Graph Database
Write Your iOS App in Swift with a Graph DatabaseWrite Your iOS App in Swift with a Graph Database
Write Your iOS App in Swift with a Graph Database
 
Top 10 React Development Tools to Choose in 2023.pptx
Top 10 React Development Tools to Choose in 2023.pptxTop 10 React Development Tools to Choose in 2023.pptx
Top 10 React Development Tools to Choose in 2023.pptx
 
What to choose for Mobile app development- React Native vs Native.
What to choose for Mobile app development- React Native vs Native.What to choose for Mobile app development- React Native vs Native.
What to choose for Mobile app development- React Native vs Native.
 
15 android libraries for app development
15 android libraries for app development15 android libraries for app development
15 android libraries for app development
 

More from Shyamala Prayaga

Leveraging Augmented Reality Capability for enhancing the shopping experience
Leveraging Augmented Reality Capability for enhancing the shopping experienceLeveraging Augmented Reality Capability for enhancing the shopping experience
Leveraging Augmented Reality Capability for enhancing the shopping experienceShyamala Prayaga
 
Interaction design workshop
Interaction design workshopInteraction design workshop
Interaction design workshopShyamala Prayaga
 
Mobile accessibility challenges and best practices v2
Mobile accessibility   challenges and best practices v2Mobile accessibility   challenges and best practices v2
Mobile accessibility challenges and best practices v2Shyamala Prayaga
 
MOBILE INTERACTION PATTERNS AND NON PATTERNS
MOBILE INTERACTION PATTERNS AND NON PATTERNSMOBILE INTERACTION PATTERNS AND NON PATTERNS
MOBILE INTERACTION PATTERNS AND NON PATTERNSShyamala Prayaga
 
Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Shyamala Prayaga
 
Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Shyamala Prayaga
 
Mobile UI and Usability Guidelines V1
Mobile UI and Usability Guidelines V1Mobile UI and Usability Guidelines V1
Mobile UI and Usability Guidelines V1Shyamala Prayaga
 
iPhone application development training day 1
iPhone application development training day 1iPhone application development training day 1
iPhone application development training day 1Shyamala Prayaga
 
Improving Site Performace Using Css Sprite
Improving Site Performace Using Css SpriteImproving Site Performace Using Css Sprite
Improving Site Performace Using Css SpriteShyamala Prayaga
 

More from Shyamala Prayaga (20)

Leveraging Augmented Reality Capability for enhancing the shopping experience
Leveraging Augmented Reality Capability for enhancing the shopping experienceLeveraging Augmented Reality Capability for enhancing the shopping experience
Leveraging Augmented Reality Capability for enhancing the shopping experience
 
Ticketing Application
Ticketing ApplicationTicketing Application
Ticketing Application
 
Interaction design workshop
Interaction design workshopInteraction design workshop
Interaction design workshop
 
Mobile accessibility challenges and best practices v2
Mobile accessibility   challenges and best practices v2Mobile accessibility   challenges and best practices v2
Mobile accessibility challenges and best practices v2
 
Mobile Prototyping
Mobile PrototypingMobile Prototyping
Mobile Prototyping
 
MOBILE INTERACTION PATTERNS AND NON PATTERNS
MOBILE INTERACTION PATTERNS AND NON PATTERNSMOBILE INTERACTION PATTERNS AND NON PATTERNS
MOBILE INTERACTION PATTERNS AND NON PATTERNS
 
Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2
 
Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2Adobe Flex - Developing Rich Internet Application Workshop Day 2
Adobe Flex - Developing Rich Internet Application Workshop Day 2
 
Accessibility and ucd
Accessibility and ucdAccessibility and ucd
Accessibility and ucd
 
Android Design
Android DesignAndroid Design
Android Design
 
Mobile UI and Usability Guidelines V1
Mobile UI and Usability Guidelines V1Mobile UI and Usability Guidelines V1
Mobile UI and Usability Guidelines V1
 
Mobile Web Frameworks
Mobile Web FrameworksMobile Web Frameworks
Mobile Web Frameworks
 
iPhone application development training day 1
iPhone application development training day 1iPhone application development training day 1
iPhone application development training day 1
 
Usability Testing
Usability TestingUsability Testing
Usability Testing
 
Json
JsonJson
Json
 
Ethenographic research
Ethenographic researchEthenographic research
Ethenographic research
 
Improving Site Performace Using Css Sprite
Improving Site Performace Using Css SpriteImproving Site Performace Using Css Sprite
Improving Site Performace Using Css Sprite
 
Universal Design
Universal DesignUniversal Design
Universal Design
 
Ajax Backbone
Ajax BackboneAjax Backbone
Ajax Backbone
 
Javascript Library
Javascript LibraryJavascript Library
Javascript Library
 

HealthyCodeMay2014

  • 3. Healthy CodeMay 2014 3 Contents HealthyCode May 2014 Code Less, Do More 4 Interview - Rinish KN 14 SQL INDEX!= FASTER ACCESS 18 Domain Specific Languages in Python 26 The Joy of Functional Programming 32 Interview - Shyamala Prayaga 38 Code Retreat 42
  • 5. Healthy CodeMay 2014 5 Greetings! Welcome to the May 2014 issue of Healthy Code magazine. In this issue we serve you functional programming, DSLs, Android coding and much more. Venkat Subramaniam continues to enthrall by taking us a step forward from his last month’s article ‘Learn to Learn’. He leads us to the territory of Functional Programming with the newborn Java 8. If you have been dabbling in Android applications, you can read Pranay’s article on building a Movie Review application (Code Less Do More) in Android. In his article he simply shows us how to build this whole application from existing libraries that are available freely without writing much code. Then, we have our myth busters(!), about how creating index in Oracle doesn’t really improve the performance. Plus, Siddharta is back with Python and talks about creating DSLs this time. Healthy Code interviewed Shyamala, UX designer at Amazon about the future of Android design and she has some interesting things to say. What do mobile applications have in store for developers? Rinish, CTO of RapidValue Solutions shares his insights for you to read. We are bent upon delivering technically focussed articles. And that’s why your comments are most important. Keep writing to us at feedback@healthycodemagazine.com. Enjoy reading!!! From the Editor
  • 6. Healthy Code May 20146 Let’s build great Android apps with other’s code Code Less, Do More Article “I believe Android will be stronger in the developing world than it is in the developed world.” – Fred Wilson
  • 7. Healthy CodeMay 2014 7 Thousands of Android applications are being built everyday. With a significant number of Android developers out there, a large volume of code is being churned day in, day out. I can say for sure that someone has already created much of the code our developers write. This ‘already-created-code’ has also been modularized as libraries and open sourced for others to use in their applications. So, why reinvent the wheel? Isn’t it possible to develop a real time Android application by using these libraries? Can’t we just reuse the code and tweak it a bit and build a complete application? Sure, we can, and I’m just going to do that. In this article, we’ll see how we can leverage various libraries that are available to rapidly develop anAndroidapplication.Let’sbuildanawesomemovie review application with as less coding as possible. The Premise: Welovemoviesandalotusaremoviebuffs.Whenever a new movie is released or we want to watch a movie, we check its ratings first. Most of the times, the movie- watching decision is based on how others feel about the movie, right? But every time you want to watch a movie, you don’t want to open your laptop to find the ratings, the cast and other details. Wouldn’t it be awesome if we can have a mobile app that can help us decide what to watch? How about an app having an option to search any movie from 2014 to 1950? Sounds interesting, right? Figure 1.0 shows how our application will look when it’s ready. Let’s see how we can go about building this application. We need a Movie rating API to start with. We love IMDB, but IMDB does not have any official API. For our app, let’s use the API from Rotten Tomatoes. Then, we will use several Android concepts such as Action Bar, Drawer, Asynchronous Data Loading, listview, etc., and libraries like ActionBarCompat, Retrofit, Picasso, Pull-to-Refresh, NavigationDrawer, and Card UI. While I don’t have enough space in the magazine for showing you how to use all these libraries, this article will focus mainly on ActionBarCompat, RetroFit, Picasso, Pull-to-Refresh and Card UI libraries. Let’s use Eclipse IDE for building the application. Launch the Eclipse IDE in your ADT bundle. Create an Android Application project called MoviesTomatoes. See if you can get your MoviesTomatoes app running in emulator or phone. ActionBarCompat ActionBarCompat is used to add action bars. It is similar to the ActionBarSherlock library but provided by Google and included in the new support library. ActionBarCompat library is backward compatible with all Android versions and Google recommends it as well. You have to import the support library v7 into your workspace to work with ActionBarCompat. And here’s how you do that. Click on File->Import->Android and choose Existing Android Code into workspace option. Locate your Android SDK folder and go to sdk/ extras/android/support/v7/appcompat. Import Figure 1.0.The application that we plan to build. PranayAiran
  • 8. Healthy Code May 20148 this project in your workspace. Note: If v7 library shows error you need to change the Android version Right click on your MoviesTomatoes project, go to properties, and add the v7 project as library dependency in Library section. We can now add the action bar to our application by configuring the action bar theme in our AndroidManifest.xml file. android:theme=”@style/Theme.AppCompat.Light. DarkActionBar” Go to MainActivity.java and make your class extend ActionBarActivity. import android.support.v7.app.ActionBarAc- tivity; public class MainActivity extends Action- BarActivity { ... } Figure2.0shows how ourapplicationMoviesTomatoes will look like once the action bar is added. The complete code for integrating ActionBar Compat can be found at https://github.com/ pranayairan/CodeLessDoMore/tree/master/ CodeLessDoMoreHelloActionBar. Consuming the Rotten Tomatoes Service As we’re going to use the Rotten Tomatoes API to get the movie ratings and other information, we need to register with Rotten Tomatoes and create an API key. We’ll use this API key whenever we send requests to their service. You can go to http://developer.rottentomatoes.com/ member/register and create an account. Note: Select Mobile Application in the application type checkbox provided, and enter http://www.google.com in the application URL textbox. You will get your API key after the registration. I have my key 9mxxxxx that you’ll notice being used in the application. Keep your API key handy, as we will use it to call the API. Rotten Tomatoes is a RESTful service that returns JSON response. I would strongly encourage you to read about REST and JSON, if you are not aware of these. Now, I’m going to show you a couple of ways of accessing the API. in box office here’s the URL: http://api.rottentomatoes.com/api/public/v1.0/ lists/movies/box_office.json?limit=10&country=us &apikey=9mXXXXXX to access the details of a movie, you can use the following URL: http://api.rottentomatoes.com/api/public/v1.0/ movies/770672122.json?apikey=9mXXXXXX Let’s consume these URLs in our application and display the returned data. We can display the list of movies running in box office in a listview. If you don’t know about listview you can read more about it at http://www.mkyong.com/ android/android-listview-example/ Retrofit: In Android applications, you can create your own thread by using classes like AsyncTask. ButFigure 2.0 MoviesTomatoes app with action bar
  • 9. Healthy CodeMay 2014 9 AsyncTask comes with its own set of problems. it. same time, they run sequentially with each one depending on the previous one to finish before running. This makes your application slow. We can avoid these problems by using Retrofit. Retrofit is an excellent networking library from Square, which helps us perform concurrent network calls and parse the results and map them to a Java Class at the same time. You can download Retrofit from http://square.github.io/retrofit/. You can include Retrofit jars to the libs folder of your project. Please note that the GSON library needs to be added to the build path to work with Retrofit. As we’re going to fetch data from Rotten Tomatoes we have to add the Internet permission in the AndroidManifest.xml file. <uses-permission android:name=”android.per- mission.INTERNET”/> Retrofit serializes JSON data to Java objects. In our application, let’s create the POJO for mapping JSON data that displays the movie list. We can use online JSON to Java generation sites like http://jsongen. byingtondesign.com/, http://www.jsonschema2pojo. org/ etc., for this purpose. Let’s generate a POJO BoxOfficeMovies. You’ll need to include the generated POJO in the project. In MainActivity.java, let’s connect to Rotten Tomatoes Service and get the list of movies using the BoxOfficeMovies POJO we created. To do this let’s create an interface BoxOfficeRunningMovie, and map this interface to the Rotten Tomatoes URL. public class MainActivity extends ActionBarAc- tivity{ interface { @GET(“/api/public/v1.0/lists/movies/box_ ) (@Query( ) String limit, @Query( ) String country, @Query( ) String apikey, } } … } The moviesList() method accepts four arguments with the first three arguments annotated with @Query annotation. The three @Query arguments map to the three query string arguments in the URL. http://api.rottentomatoes.com/api/public/v1.0/lists/ movies/box_office.json?limit=16&country=us&apike y=9mXXXXX The fourth parameter is a Retrofit callback that will be called when the response is received. Let’s consume this interface now by creating a RestAdapter. The RestAdapter will create an instance of the BoxOfficeRunningMovie interface. We can invoke the moviesList() method to get the list of all movies. public class MainActivity extends ActionBarAc- tivity { … onCreate(Bundle savedInstan ceState){ new - er.Builder().setEndpoint build restAdapter.create class new @Override response) { int ies. getMovies(). Toast.makeText(MainActivity. , “Number of movies running in Box + moviesNumber, Toast.LENGTH_LONG } @Override
  • 10. Healthy Code May 201410 Toast.makeText(MainActivity. , “Error: “+ Toast.LENGTH_LONG } runningMovies. ( , , } The moviesList() method has the callback instance passed, which displays the result in a Toast for the time being. Figure 3.0 shows the output when you execute this code. That’s it!!! We have our Retrofit boilerplate code completed. ThecompletecodeforintegratingRetrofitcanbefound at https://github.com/pranayairan/CodeLessDoMore/ tree/master/CodeLessDoMoreRetrofit. Binding results with a listview Let’s display the movie name, movie thumbnail image, critics rating, audience rating and MPAA rating in a list view. Each movie will be displayed in a listview as shown in Figure 4.0. I’m not going to delve in detail into this topic. I have created an XML file for the list item, a BoxOfficeMovieAdapter class to display the above information. While discussing Retrofit you’d have noticed that I had displayed the response from Rotten Tomatoes in a Toast. We have to replace that code to display the movie list in a list view. new @Override Adapter = new ty. , .setAdapter (movie } … } Figure 5.0 shows the listview of the movie application. As of now the thumbnail of the movie in our listview is not loaded as there is no way to load images directly from an URL. You can view the complete code for listview at https:// github.com/pranayairan/CodeLessDoMore/tree/ master/CodeLessDoMoreListView. Picasso Let’s load the thumbnail of the movies using Picasso. In Android applications, loading images is an interesting problem. If you want to get images from a URL, you need to download the image first and then display it in image view. To make the application responsive we need to download this image in background and then load it in image view. There are lots of chances of duplication of images, so we need to Figure 4.0. Movie item display
  • 11. Healthy CodeMay 2014 11 cache those as well. To implement these, we need to write many lines of boilerplate code. Enter Picasso. Picasso is an amazing library from Square, designed to solve the image loading issue. There are lot of similar libraries like UniversalImageLoader, UrlImageViewHelper, and Volley that can be used for this purpose. You can download Picasso from http://square.github.io/ picasso/ and add it to the project. In the BoxOfficeMovieAdapter class we have to add these two lines of code to load the movie poster image in background and display it in thumbnail. Picasso.with(ctx).load(runningMovie.get- Posters().getThumbnail()) .placeholder drawable.ic_launcher) .error drawable.ic_launcher) .into(movieHolder.movieThumbnail In the code above, runningMovie refers to each movie instance in the collection of movies fetched from the service. Figure 6.0 shows the app once Picasso is integrated. You can view the complete code of integrating Picasso at https://github.com/pranayairan/CodeLessDoMore/ tree/master/CodeLessDoMorePicasso. Pull-to-Refresh I want to give users a way to refresh the movie list without closing the application. We love Twitter and Facebook where we pull to get the latest tweets and posts, so why not add the same pull-to-refresh option in our movie app? To add pull-to-refresh we will use an excellent library from Chris Banes called ActionBar PullTo Refresh. You can get the library from https://github.com/ chrisbanes/ActionBar-PullToRefresh. As we already have action bar in our application, this is the most suited library for us. Download ActionBar PullToRefresh library from Github and import it in Eclipse. ActionBar PullToRefresh is dependent on another library, SmoothProgressBar. You can download this library from https://github.com/castorflex/Smooth ProgressBar. Note: It’s a bit difficult to build Figure 5.0. Movies displayed in listview Figure 6.0. Movies list after Picasso integration
  • 12. Healthy Code May 201412 these libraries using Eclipse. Include ActionBar PullToRefresh library in your movie application as a library project. We can introduce the Pull-To- Refresh feature in our app by configuring the list view inside the PullToRefreshLayout. You can do this by replacing RelativeLayout with PullToRefreshLayout in the activity_main.xml. xmlns:android= android:id= > Our listview will be inside this new PullToRefreshLayout. This wrapper will provide necessary UI for pull to refresh. Let’s create an instance of PullToRefreshLayout in MainActivity.java and set it up. - id.ptr_layout from( ) // Mark All Children as pullable .allChildrenArePullable() .listener( ) // Finally commit the setup to our Pull setup You can add the RefreshListener by implementing the onRefreshStarted() method, which has your pull-to- refresh logic. In our movie application, we can call the Rotten Tomatoes web service again, get the response and create a new instance of BoxOfficeMovieAdapter class. Finally, you need to call setRefreshComplete() to indicate that the pull-to-refresh action is complete. - plete That’s it! With this simple integration, we have a pull- to-refresh functionality in our application. Now let’s enhance the look and feel of our application using Card UI. Card UI Do you like the new Google Play UI? Google has introduced a nice Card UI in their applications like Google Play, Google Plus etc. We will try to create the same look and feel for our application. You can use Card UI libraries like https://github.com/ gabrielemariotti/cardslib but I’m going to keep things simple in our application and implement Card UI by just adding and tweaking some code. Let’s create a custom drawable with a shadow, set our list view item with this drawable and make some minor changes; and we’ll have the card look and feel. Create a new drawable say cards.xml and add the following code that gives the card-like look and feel. <layer-list xmlns:android= - > <item> <shape> <padding android:top= android:right= android:bottom= android:left= /> <solid android:color= - /> </shape> </item> <item> <shape> <padding android:top= android:right= android:bottom= android:left= /> <solid android:color= /> <corners android:radius= /> </shape> </item> <item> <shape> <padding android:top= android:right= android:bottom= android:left= /> <solid android:color=
  • 13. Healthy CodeMay 2014 13 /> <corners android:radius= /> </shape> </item> <!-- Background --> <item> <shape> <solid android:color= /> <corners android:radius= /> </shape> </item> </layer-list> You can change the background of the list item xml to use the card created. xmlns:android= - android:layout_width= android:layout_height= android:paddingBottom= > … You can tweak the list view by adding margins, modifying space between the cards, modifying header and footer etc. We have our card look ready, and figure 7.0 shows the application with enhanced UI. Figure 7.0 Movie app with enhanced Card UI Figure 8.0: Movie app after integrating Navigation Drawer
  • 14. Healthy Code May 201414 Engineer @ Intuit, developing web and mobile applications, Pranayholds a Masters degree from IIIT Bangalore. He is passionate about building mobile applications and hacking on new web technologies, and he helps Blrdroid as Assistant organizer as well. Pranay has been developing Android apps from the last 3 years and has developed a variety of apps personally and @ Intuit. He has more than seven apps in Google Play Store. He conducts workshops in colleges where he likes to share his knowledge and helps students get start with android under Blrdroid Teach Program. You can find the code for Card UI in https://github. com/pranayairan/CodeLessDoMore/tree/master/ CodeLessDoMoreCardsUI. You can enhance the application further by integrating Navigation Drawer and the application will look as shown in figure 8.0. The code for integrating Navigation Drawer is available at https://github. com/pranayairan/CodeLessDoMore/tree/master/ CodeLessDoMoreNavigationDrawer. I have shared the complete code for the article in the Github repository, https://github.com/pranayairan/ CodeLessDoMore. Publisher: T. Sivasubramanian Editor: S. Prabhu Production: New Horizon Media Private Limited Proof Reader: Shweta Gandhi Publication Address: 11/6, First Floor, Fourth Street, Padmanabha Nagar, Adyar, Chennai - 600020 Printer: Sakthi Scanners (P) Ltd 7, Dams Road, Chindadripet, Chennai - 600002. Contact Phone Number: 044-42337379 Email: siva@healthycodemagazine.com Web Site: Price: Rs. 150 /- Healthy Code May 2014 Vol. 1 | Issue. 2 Disclaimer: The articles and contents of the Healthy Code magazine are sourced directly from the authors with their permission.HealthyCodedoesn’tassumeresponsibility for violation of any copyright issues by an author in their respective article. We have made sure to the best of our knowledge that the articles and code presented here are without any errors. However, we can’t be held liable for any damage or loss that may arise from using these. - Publisher Pranay
  • 15. Healthy CodeMay 2014 15 Pragmatic BookShelf’s Seven X in Seven Weeks series is quite popular, and this is another interesting book from their stable. In spite of being two years old, it still serves as a fantastic introduction to NoSQL databases even now. Jim Wilson and Eric Redmond (also, author of, ‘Programming Google Glass’), are the authors of this book It talks about NoSQL databases like MongoDB, CouchDB, Redis, Riak, HBase and Neo4J. The only RDBMS database that’s been discussed is Post- greSQL. The choice of the databases in the book has been clearly explained in the introductory section. Each chapter takes up one database, introduces it and tells you how to set it up. The ritualistic CRUD operations are discussed with simple code-based examples. The chapter then explores the core fea- tures of the database, and winds up discussing the strengths and weaknesses. It also highlights a number of other features, which can be explored outside the book. Apart from the regular exercises at the end of each day of discussion what’s interesting is the variety of examples covered to explain the concepts. Unlike a lot of technical books that run through a single problem in all the chapters, each database is ex- talks about creating and playing with cities, Couch- DB talks about music and so on. My favorite read is the chapter on MongoDB be- cause of the succinct introduction to sharding and replication concepts. - ent databases, it is a treat for the experienced to un- - Prabhu Sunderaraman SevenDatabases inSevenWeeks EricRedmond,JimR.Wilson Book Review
  • 16. Healthy Code May 201416 How did you decide to start a company that focuses on mobile technology? In 2007, Apple came out with iPhone, and it changed the mobile phone world dramatically. All research at that time pointed out to a growing mobility and cloud market. It was then that we started RapidValue Solutions and decided to focus on mobility and build a niche for ourselves. What was the predominant mobile technology at that time? It was primarily the Apple iOS as that time. Building a Mobility Business Interview H ealthy Code spoke to Rinish KN, Chief Technology Officer of RapidValue Solutions, an end-to-end enterprise mobility services provider based out of Pleasanton, California with offices in India (Kochi and Bangalore). Rinish has previously worked as an architectatOracleandWipro,buildinge-commerce websites, before he co-founded RapidValue Solutions with Rajesh Padinjaremadam and Sirish Kosaraju in 2008. Here are the excerpts from that chat. Blackberry was also very popular. In those days, Apple competed with Blackberry. In the Android space, the first HTC phone was released in 2008. What was the first opportunity that you got for your company? First, we had to prove to ourselves that we could build mobile applications. So we hired a Java developer. There were three managers and one programmer. We built a simple expense tracking application system for iPhone and Android to prove our capability. After that, we started getting interesting projects and customers. ? ? ?
  • 17. Healthy CodeMay 2014 17 Was the learning curve pretty high for your team initially? In India, we always have more Windows developers than Mac developers. When iOS entered the market, it was very new to all of us. However it’s not difficult to learn the platform. The developer guide of Apple is very helpful. They have very good videos, articles and documentation. Their XCode editor is awesome. We learnt most of the technical details from their developer portal. Even today we hire straight Java programmers, C++ and C# developers and train them in mobile development using the same way. What kind of applications did you start building first? We started building native applications initially for iPhone and Android. Native applications are the ones that you have to download from App Stores such as Apple’s iTunes or Google Play Store on your mobile before you can use them. With Native apps, users can make use of phone capabilities like Camera, GPS, offline browsing etc. We started building business to customer (b2c) applications. A good example of this kind would be like media/publishing application, music streaming applications and retail product catalogs. These native applications interface with the server to access data from content management systems and provide you the latest information on the phone just like your client-server applications. What kind of applications are you developing today? Over the last five years, we have expanded from mobile application development to providing end-to-end enterprise mobility services. Our services include mobile strategy, UX/UI design, mobile app development, enterprise system integration, mobile testing and ongoing support and maintenance. We are now developing a lot of applications for large enterprises and many Fortune1000 companies. Some of the applications include: HR Management Service by which employees can apply for leave, view pay slips etc. Mobile Commerce by which consumers can view and purchase products online. Inventory Management App for scanning at warehouses for receiving goods and managing inventory. Physicians Communication and Scheduling App for doctors to interact with their staff. Rinish K N ? ? ?
  • 18. Healthy Code May 201418 Online Class Room App for University faculty to interact with students, and many more types of applications across industry segments. In many cases, we are extending the ERP systems for access from mobile devices. In addition to mobility services, we have recently launched a global product ‘eQuipMeTM ’, a mobile field service suite which connects field service technicians and customers in real-time from any mobile device. Tell us a little bit about mobile websites. How different are they different from native applications? The evolution of mobile websites is very similar to the evolution of web applications. Long ago, we moved from Mainframes to Client Server Computing. With the advent of Internet and we started building web applications. Similarly in the mobile space, you can view the native application as a client server application interacting with a server at the backend. Mobile websites are similar to web applications. You simply use the browser in the mobile phone and connect to your application on the web server. Even though any website can be viewed from the mobile browser, you need to build a mobile website to leverage the features of the mobile phone and for proper rendering. However, now a days many are building websites with responsive design. Responsive websites are a notch better than mobile websites. There are so ?
  • 19. Healthy CodeMay 2014 19 through the year? Yes. Mobile development is a fast-paced business. We typically deliver a full application in 3 months on average. But in most cases, we continue the client relationship for 2 to 3 years, either in the same project or other projects. So, sustaining development team is not an issue for us. Is it possible to build a large-sized company with prime focus on mobile development? Absolutely. The enterprise mobile application space is rapidly growing. The company budgets for building mobile applications are increasing every year. RapidValue currently has over 200 employees. Given that we have expanded rapidly in the past five years (employees, offices and customers), we are expecting 100% Y-o-Y growth. We strongly believe we can do it! What are your thoughts on wearable devices and Google Glass etc.? It certainly looks like the future. Previously, we never thought our phones would connect to the Internet. Now we do it every day. Cars are getting connected to the Internet in the US. Google Glass is another good example. Wearable devices and connected devices is where RapidValue will focus in the coming years. Now that mobile technology has so many job opportunities, where does a developer stand in the mobile space? Actually mobile development is quite similar to Java development. People who have knowledge in Java or C# can get into mobile development. For a Java developer, learning Android is similar to learning Spring or Hibernate Framework. Anyone having knowledge in object oriented programming can start on mobile application development. Passion for learning is the key. many types of phones in different sizes and shapes available today. So your mobile web application should adjust to the multiple phone sizes and platforms. A responsive website will do that for you. If the requirement is to reach out to a large number of users as in mobile commerce application, mobile websiteisthebestoption,andifrichuserexperience and phone capabilities need to be enabled for the mobile app, native app development is the right approach. Another option is the Hybrid Mobile Web App which has some capabilities of mobile website and some of native app. What are Hybrid applications? Hybrid applications are a mix of native and other types. The UI is built with HTML 5 and JavaScript. The same JavaScript is used for accessing native features of the phone like Camera, Gyroscope, etc. You use technologies like PhoneGap, Titanium Appcelarator or RhoMobile to achieve this. These frameworks take care of the native code that is needed to run your application across different platforms like iPhone and Android. There are so many Mobile JavaScript frameworks like jQuery mobile, Sencha Touch, Kendo, etc. How does a developer navigate this JavaScript land? It is better for a developer to have multiple skills. They should pick up HTML 5, JavaScript, iOS or Android to begin with. There are many JavaScript frameworks, but once you pick one up, you should be able to switch to others. Just like if you know Java, you can easily learn to program in Servlets, JSP, Hibernate and Struts. It’s similar to that. Sencha Touch is very rich in UI. jQuery Mobile is very light-weight. All these frameworks have their own advantages and once you know any one of these frameworks, the switch is not very hard. There is a perception that mobile application projects are short term (3-4 months). How do you sustain development ? ? ? ? ? ?
  • 20. Healthy Code May 201420 Article INDEX!=
  • 21. Healthy CodeMay 2014 21 = FASTER ACCESS Ankit Kumar Katiyar & N.S.Sekar O ne of the frequently encountered solutions that application developers are offered, while dealing with performance issues with the oracle database is: “create an index on that column”. This may enhance the performance in some cases if you know your index well enough. However this can actually degrade or not have any significant impact on the SQL performance in the application at all. Therefore it’s important to be aware of the behavior of index if you want to leverage its true potential. We have identified a bunch of issues while working with index in Oracle and discussed them in this article. Here’s a list of concerns raised by developers and our response to them. Concern #1: I have created an appropriate index on particular column. But why is the query engine not picking up the index? This may happen due to bad or incomplete statistics. In the absence of statistics, the optimizer (Cost based optimization) may choose a full table scan (FTS) as compared to indexed access. Recommendations: Prior to testing queries, just make sure you re-analyze the table and index with dbms_stats. This provides the optimizer with good metadata. You can use the following queries to check the last analyzed status. You can use the following queries to execute the dms_ stats procedure to analyze objects. Concern #2: I have created an appropriate index on a particular column and I have also verified the earlier step discussed in Concern#1. I still see that oracle is not using that index. This may happen if the number of rows in that table is less or your query is returning almost all the data in a table. Recommendations: If table is small that it can be read in a single I/O call, then a full table scan of table might be cheaper than an index range scan. Single I/O call can be defined by
  • 22. Healthy Code May 201422 DB_FILE_MULTIBLOCK_READ_COUNT parameter and value defined by blocks. If your query is returning the majority of the data in a table, then a full table scan is probably going to be the most efficient way to access the table and optimizer may choose to decide that it would be more efficient not to use the index. Concern #3: I have created proper B-Tree Index on the particular column and have also analyzed the table and index. I still don’t find oracle using that index. Oracle B-TREE Indexes can surely help in improving the query performance provided there is optimal selectivity on that column. The ratio of the number of distinct values in the indexed column/columns to the number of records in the table represents the selectivity of an index. Ideal selectivity is 1 in case of primary key and unique key. While optimizing, oracle takes a decision of choosing an index based on I/O. As discussed earlier, if the query is returning the majority of the data in a table, then a full table scan is probably going to be the most efficient way to access the table. Recommendations: We should create indexes on tables that are often queried for less than 15% of the table’s rows. This value may be higher in situations where all data can be retrieved from an index, or where the indexed columns can be used for joining to other tables. Please check if you have right index on that column. In other words, in oracle while standard B-tree indexes are most effective for columns containing a high number of different values (good selectivity), bitmapped indexes are most appropriate for columns with a limited number (poor selectivity) of possible values. In general, B-tree indices are good for OLTP and Bitmapped indices are good for OLAP systems. Factor in your usage, prior to creating the index. Concern #4: I have a query
  • 23. Healthy CodeMay 2014 23 The query engine is still not using the index. If you are using the SQL “like” clause then it can be tricky because the wildcard “%” operator can invalidate the index. Recommendations: STRING% will do INDEX RANGE SCAN data because optimizer knows where the string gets started. % STRING will do the INDEX FULL table because LIKE expression that starts with a wildcard. %STRING% will perform the FULL table scan because optimizer doesn’t know from which letter the String get started. Concern #5: I have a query, I also have a proper index on id column. Why is the query engine still not using the index? If you have got a WHERE clause which contains something like “id is null” then query engine will always perform the full-table scan because NULL values cannot be indexed. If you have no choice, but to have this condition in your query, consider replacing it with a NVL function. Recommendations: If you have a null in your where clause you may have to keep the following in mind: When you have “IS NOT NULL” type WHERE clause will use an index When you have “IS NULL” type WHERE doesn’t use an index Concern #6: I have a query, I have proper index on name column then why is the query engine not utilizing an index?
  • 24. Healthy Code May 201424 Even though the name column has an index, the upper functions will invalidate the index and WHERE clause predicates might invoke FTS (unnecessary I/O). Recommendations: In such cases, use Function-Based index on that column. Function-Based indexes give the ability to index computed columns and use theses indexes in a query as shown here. Concern #7: I have created a Function-based index on a table column, yet when I check my execution plan, the optimizer ignores the Function-based index? Typically, function-based indexes or any index are ignored when analyze the index has not been performed. Recommendations: After creating a function-based index, don’t forget to re-gather table statistics and get extended statistics on the function. Concern #8: I have a query, I have a proper index on these columns but no use of the index. This may happen if you are performing mathematical operations on the indexed column then oracle will invalidate the index and will go for the full table scan. Concern #9: I have a following query In this case name column is indexed but oracle is not using an index. Why? When an indexed column appears on both sides of an operator, the index for that column is disabled. Recommendations: You can rewrite the above-mentioned query as Concern #10: I have following query Inspite of having a proper index on these columns why doesn’t oracle use it? If we use the NOT EXISTS then nested index scans will be used in the sub query for each row in the DEPARTMENT table. The only records that will be returned from DEPARTMENT are those that return no rows from the sub query, and no full table scans are performed by the sub query. Recommendations: The following query statement is more efficient. department.department_id=employee. department_id) Concern #11: In my query, I have an index on a DATE column but oracle is not using index if I fetch results using JDBC driver? This might happen due to data type conversion between Date and TimeStamp. Developers, typically use the setTimestamp method in order to set time. When this is done, the index on the DATE column will not be used. This is because, oracle internally converts/casts datatypes (of date to timestamp) . Recommendations: You can address this problem with the following:
  • 25. Healthy CodeMay 2014 25 Concern #12: In spite of having index on “first_name” and “last_ name” columns the query “ takes much longer than expected. The use of ‘OR’ statements confuses the optimizer (Cost Based Optimizer). It will rarely choose to use an index on column referenced using an OR statement. Recommendations: You can work around this issue by using UNION ALL as shown here. Concern #13: I have created composite index on the column but how does it work with my query? A composite index contains more than one key column. Composite indexes can provide additional advantages over single column indexes. Consider creating a composite index on columns that are frequently used together in WHERE clause conditions combined with AND operators, especially if their combined selectivity is better than the selectivity of either column individually. Even If you do not include the first column of a concatenated index in the WHERE clause of your statement then also Index Skip Scanning will be used. Summary This article was just a brief overview at database indexing with some light on b-tree index, bitmap indexes, function-based indexes, and composite indexes. Index efficiency is hard and finding appropriate index even harder. We hope that these tips when used appropriately may help you debug performance issues, even after you have created the index on the relevant columns. In general, when things are really slow due to a SQL statement, in your application, use the EXPLAIN PLAN to look at the execution plan of the statement. Following this, make the changes in your SQL based on cost estimation. Remember that “FULL TABLE SCANS ARE NOT ALWAYS BAD” and “SQL INDEX != FASTER ACCESS” in all scenarios. Happy indexing!!! Ankit Kumar is currently serving Successfactors (SAP Cloud) as a Principal Engineer. His work is with the Employee Central (EC) product wherein his main focus is to make EC world’s most high- performing, scalable, and blazing fast cloud platform. Prior to this, he worked with Oracle as a technology lead and Hewlett Packard (HP) as a software analyst. He holds a patent and disclosure in database and network technologies, respectively. NS Sekar Sekar is Vice President of Engineering at Success Factors. He has previously worked as Director at Yahoo and Informatica. He is a seasoned tech- nology and product development executive with experience in building and scaling distributed en- gineering and product teams from multiple ear- ly-stage startups to the next level. His expertise includes Data Integration, Data Quality, Web Ana- lytics, Internet Platforms, and SaaS Ankit Kumar
  • 26. Healthy Code May 201426 Regional Scrum Gathering India July 11, 12 - Hyderabad With the theme of “Humane Scrum”, the Region- al Scrum Gathering® India 2014 focuses on explor- ing techniques, tools, behaviors, and experiences that help bring about the mind-set so essential to - tions small and large. Venue: Hotel Trident, HITEC City, Near Cyber Towers, Madhapur, Hyderabad, AP 500 081. http://scrumgatheringindia.in/ tiConf India will be a single day event featuring some of the best Titanium de- velopers and evangelists from around the globe. We will be talking everything about Titanium, Mobile Development, Cloud and JavaScript. Venue: 25 Windsor Square, Golf Course Road Bangaluru 560 052 Karnataka, India Website: http://ticonf.org/ Rootconf 2014 May 16-17, 2014, Bangalore Rootconf is a conference that will help you plan and develop a strategy map for infrastructure and devops. It will show you the building blocks for reaching a strategy for Continuous Integra- tion, Deployment and Delivery. Target audience: Organizations who need a CI developer teams and performance of their web stacks. Venue: MLR Convention Centre, J.P. Nagar Brigade Millennium Complex, J.P. Nagar 7th Phase Bangalore, Karnataka India. Website: Technology Conferences JULY 19, 2014
  • 27. Healthy CodeMay 2014 27 the art of continuous improvement Each backed by more than a decade of experience, our agile consultants and coaches work with managers and teams to address people, process and products for a more comprehensive approach. Lean + Agile Assessment Agile Management Consulting Agile Team Coaching Lean Product Innovation Get the real-world insight, practical advice and experience needed to lead your team, speed time to market, and boost morale. We offer classes for all levels, including: Agile Engineering Agile Testing Workshop Scrum Product Owner Training ScrumMaster Training Organizational Intro to Agile Great teams build great products. Achieve a state of continuous team improvement with Sensei, a simple retrospective tool for agile teams. Try it for free, no obligations: • www.lithespeed.com • 703.745.9125 • @lithespeed Our combined customer discovery and agile product development won’t just get you to an MVP: It will provide your team with the hands-on training to set up and to run effective experiments long after the engagement ends. * * * * * * * * * * * * SenseiTool.com Phase 1: Getting Started + Product Discovery Phase 2: Accelerating Discovery + Introducing Agile Development Phase 3: Transition and Closeout
  • 28. Healthy Code May 201428 Domain Specific Languages in Python Article
  • 29. Healthy CodeMay 2014 29 An interface should be designed in such a way that the code, which a programmer writes, is almost same as what he or she is thinking in their head. Such an interface is termed as natural. With a natural interface, there is less translation to do when converting from the mental model to the actual code itself. This is beneficial not only when writing code, but it is also easier to understand the intent when reading the code later on. One way to create an interface that is as natural as possible is via Domain Specific Languages (DSL). Domain Specific Languages Generally speaking, we use a general purpose programming language to get our job done. However, because they are a general purpose, we may sometimes have to go through unnatural hoops to get things done. Let us take a simple example of pattern matching. Suppose we want to determine if a given string represents an IP address. The process of doing so might involve taking the string, splitting it up on the period, and then checking if there are exactly 4 parts, and whether each part is a number between 0 to 255. A Python implementation might look like this: (ip_address): components = ip_address_string.split( ) if len(components) != 4: False : int_components = [int(component) for component in components] except : False for component in int_components: if component < or component > : False True To someone looking at the code for the first time, it is not obvious what pattern this code is matching. Also, if we want to change the pattern that is being matched, then it isn’t straightforward to make the change. Using regular expressions, we can change the code to something like this: def is_ip(ip_address_string): match = re.match( ,ip_address_string) if not match: return False for component in match.groups(): if int(component) > : return False return True In regular expression notation, the string “^(d{1,3}). (d{1,3}).(d{1,3}).(d{1,3})$” amounts to matching 4 groups of digits, each group having 1-3 digits, separated by periods. Anyone can look at the regular expression and understand the pattern that is being matched. If we need to make a change to the pattern, then it is easy to plug in the new pattern in the code. Regular expressions are an example of a domain specific language. It is a language that allows us to express the pattern, rather than an implementation on how to match the pattern. We are thinking in our head, “I need to match four integers separated by a period,” andtheregularexpressionallowsustoputthatdirectly into the code. Without regular expressions, we need to do a lot more work in translating our mental model into the code when writing it, or understanding the intent when reading the code, leading to unintuitive or difficult to understand code. There are many other DSLs that we use daily without even realising it. For example, SQL is a domain specific language for retrieving data from a relational data source. By using SQL we can communicate very clearly about what data we want to retrieve rather than specifying how the data should be retrieved. Now that, I have opened the doors of DSL, let’s walk through the features of DSLs. External v/s Internal DSL There are two types of DSLs: External and Internal. In an external DSL, a special syntax is used as a language. This syntax is specified as a string or in an external file. The regular expression interface that we saw above is an example of an external DSL. Internal DSLs don’t use an external syntax. Instead, they make use of the syntactical features of the programming language cleverly to make the interface more natural. Let’s discuss this External and Internal DSLs with an example. To begin with, let us decide the public API that we are going to use to make the calculations. Siddharta Govindaraj
  • 30. Healthy Code May 201430 There are two ways we can design the interface for the calculator. Internal DSL: Provide classes that we use to create the expression that we want to evaluate. External DSL: Use an expression syntax, which we must parse and evaluate. Calculator: Internal DSL way The code snippet for the Calculator using the Internal DSL approach looks like this. Add( , Mul(2, 3 , 6)).evaluate() , Add(3, 4)), ).evaluate() We build up the expression using normal python classes like Add, Div and Mul, which are evaluated to give the result. Implementing the Internal DSL syntax as shown above is an interesting premise in Python. Let us start with the Add class. Add should be able to take any number of parameters in the constructor, and return the sum when the evaluate method is called. import operator from functools import reduce class Add( ): def __init__(self self.terms = args def evaluate(self): return reduce(operator.add, self.terms) This simple implementation handles adding a series of constants: >>> Add( , 3).evaluate() 4 >>> Add(2, 4).evaluate() 6 But, the Add class should also be able to take other expressions as a parameter. Add(1, Add(2, 3)) should The words ‘static’ and ‘synchronized’ are a menace to Test Driven Development. Continuing to use a miserable developer tool is like being complacent in an abusive relationship -- why not get out for a better life? Pragmatic Programmer Quotes
  • 31. Healthy CodeMay 2014 31 also return 6. Our current implementation will give an error because in the evaluate method we assume all the terms are numbers. There are two ways to handle this. One way is to check for expressions and call evaluate on the sub- expression before adding. Such an implementation will look like this: (self): total = for term in self.terms: if isinstance(term, Add): total += term.evaluate() : total += term total The other option is to create a Number class with an evaluate method. A number will always evaluate to this example. ( ): (self, value): self.value = value (self): self.value With this class in place, we can modify the Add class to evaluate each expression before adding the values. ( ): (self): reduce(operator.add, [term evaluate() for term in self.terms]) Now we can add both numbers and sub-expressions. When evaluate is called on a term, it will return the number or evaluate a sub-expression, depending on which object it is. Unfortunately, this change means that we have to wrap numbers in the Number class and we have to now invoke the Add class like this >>> Add(Number( ), Number(2)).evaluate() >>> Add(Number( ), Add(Number(2), Number(3))). evaluate() 6 This syntax looks ugly, but we’ll get back to that problem later. For now, we have support for sub- expressions. Let’s go ahead and implement Sub, Mul and Div. ( ): (self self.terms = args (self): reduce(operator.sub, [term. evaluate() for term in self.terms]) ( ): (self self.terms = args (self): reduce(operator.mul, [term. evaluate() for term in self.terms]) ( ): (self self.terms = args (self): reduce(operator.truediv, [term. evaluate() for term in self.terms]) With these classes in place, we can now start mixing operators. >>> Add(Number( ), Mul(Number(2), Number(3)), ), Number(6))) Okay, now that the basic functionality is working, let us clean it up a bit. First, there is that annoying need to wrap up numbers in the Number class, which makes the interface quite ugly and verbose. Second, there is a fair bit of duplication between the various classes. it accepts numbers and internally wraps them in the Number class. import ( ): (self self.terms = [self.wrap_term(term) for term in args] (self, term): Number(term) if isinstance(term, term To clean up the duplication, we create a base Operation class and put all the common functionality in there. After the change, the code looks like this:
  • 32. Healthy Code May 201432 Operation( ): (self self.terms = [self.wrap_term(term) for term in args] (self, term): Number(term) if isinstance(term, term (self): reduce(self.operation, [term. evaluate() for term in self.terms]) (Operation): operation = operator.add (Operation): operation = operator.sub (Operation): operation = operator.mul (Operation): operation = operator.truediv We can now use the module in a more natural way! >>> Add( , Mul(2, 3 , 6)).evaluate() , Add(3, 4)), ).evaluate() >>> Add( , 3)).evaluate() Calculator: External DSL way calculator.evaluate(“ + 2 3 + / 6 ) calculator.evaluate(“ 3 + 4 ) / ) In the External DSL approach, we pass the input as a parse and evaluate. We will reserve the external DSL implementation for later article. External and Internal DSLs. In short, if the main users for your package are going to be other developers (for example, if you are creating a module that will be used like a library with other modules), then it is worthwhile to see if the language contains a natural syntax that you could adapt into an Internal DSL. Otherwise, go for an external DSL interface. The complete code of the article can be downloaded from 2014 External DSL Internal DSL Can use the most natural syntax Syntax limited by syntax of programming language Easy to understand the intent Easy, but less than an external DSL Can be maintained by non-programmers Cannot be maintained by non-programmers Requires that you implement parsing logic No parsing required Siddharta Govindaraj is the founder of Silver Stripe Software, a product company based in Chennai. He is active in the Chennai tech, agile and entrepreneur communities in his free time. Siddharta
  • 34. Healthy Code May 201434 The Joy of Functional Programming Article
  • 35. Healthy CodeMay 2014 35 style is the one that most of us are familiar with, and the functional style is the one that has been around for as long, but as a well-kept secret. Imperative v/s Functional Style Most of us have programmed in imperative style, maybe without realizing it. It’s not our fault that we’ve been taught to code that way, and most of the languages within our reach promote that style. Imperative style is primitive; we express our ideas in detail, telling not just what, but how to do things. At After all, computers follow instructions, and it’s our duty to give them. Functional style is declarative; we express our ideas at a higher level of abstraction and let the underlying - ity. Let’s get a feel for them using a few examples. Taking Full Control - visible by any number other than 1 and itself. So, we can set out on that task, iterating through all numbers a divisor, bingo, the number is not prime. Let’s code that logic in Java, just the way we described: { ( number, divisor){ } ( number){ for( i=2 if } number> } } We started at the value of 2 and iterated through each number until we reach the target value. If the target was divisible by any index, we break out of the loop declaring that the number is not prime. If we com- pleted the loop, we make one last check, to see if the The Power of Expression If we ask a fellow programmer what they under- stand by programming, we may hear words like cod- ing, compiling, execution, and so on. But, in essence, it’s an act of communication, a form of expression. It’s not just expressing ideas for execution by the comput- ers. It’s more than that, a lot more, in fact. It’s what we create so fellow developers, and ourselves, can main- tain moving forward. Much like writing in a natural language like English, there are several ways to express ideas. Some writings are easy to grasp while others are hard to follow. Pro- grams are like that, and if we’re keen, it’s not hard to A good code should read like a story, not like a puzzle. pick either active or passive voice. The former gives Programming has similar styles. What is popular or the most familiar is not necessar- There are at least two styles of programming in use to- day, one more widely used than the other. Imperative Venkat Subramaniam More than which language we pro- in it. Almost every mainstream pro- - of syntax. In languages, as in love, we have to see beyond the looks very quickly. In this article, we will discuss semantics of what we express. We will also look at the key reasons to use this style of programming and how we
  • 36. Healthy Code May 201436 of primes. That’s familiar code, but it’s primitive and low level. A quick glance at the code, we see that the loop stands among the numbers in range – is lost. Focusing on the Essence Let’s try that exercise again, this time using a more de- clarative style of functional programming, using Java 8 (see References.). import { ( number, divisor){ } ( number){ number > && range(2,number) .noneMatch(index- } } In this version, we raised the level of abstraction and concisely expressed: in the range of values from 2 to the given number (not inclusive) ensure none match Functional code reads like the problem statement. The focus here is on the essence – what we’re inter- ested in rather than the mechanics of how to get that. Imperative style feels like giving instructions to a toddler. Functional style feels like communicating with a responsible adult. Let’s leave the primes examples behind for just a bit and explore other aspects with a few more examples. Favoring Immutability Functional style promotes immutability. Most of us are used to mutating variables. Sometimes it’s hard to imagine how we could solve a problem without muta- tion. Let’s look at an example. In the next code we use imperative style to total all even values in a collection. int int result = for(int e:values){ if 2 == ) } } Given a list of values, once again in this example, we loop through the values cherry picking the even values and accumulating them. The result is being mutated repeatedly as we loop through the values. This has two limitations. The for loop provides only sequential looping and, furthermore, the mutation makes it harder to make the computation concurrent for a large list. Let’s rewrite this in functional style. int values.stream() . 2 == ) .reduce( ,Math: } Let’s read that aloud to see what’s going on: Given a reduce (sum) the values using the addExact method, using 0 as the initial value, and return the result. This code also begins to read like the problem statement. Again, we focus on what instead of how. Further- more, we avoided mutability, that leads to fewer moving parts, and that, in turn, helps to minimize er- rors. Later we will see how that can help with concur- rency as well. Favoring Functional Purity a value of x = 5, what’s the result of the computation below? x++ +6 + x++; your guess. Instead, ask yourself how you feel when had to decipher it. The chances are we would get con- fused and get it wrong. We don’t have to endure that, - ware to develop and to deliver value.
  • 37. Healthy CodeMay 2014 37 2 * x + 7; A pure function or expression does not modify or af- outside. Pure functions are easier to understand as they have fewer moving parts. They’re also easier to test – for a given input, the output is always the same. We would need fewer tests for pure code than code is referential transparency. The compiler can replace, where possible, the code with the result of the compu- tation. Furthermore, the compiler can freely reorder expressions or functions that are pure. That ability to dynamically optimize code is very useful to exploit concurrency on multicore processors. We saw that functional style promotes declarative code and favors immutability. In addition, functional style brings higher order functions. A higher order function can accept functions as parameters, may create functions, and may return functions. In other words, we can do with functions what we’re used to do with objects. This leads to some powerful capabili- ties, one of which is lazy evaluation. Since we can pass functions to functions, instead of evaluating the parameter function before the call, we can postpone its evaluation for later (or even skip it). faster, but avoiding things that don’t have to be done. faster, but by avoiding those that shouldn’t be done Let’s look into an example of laziness. In the double- FirstEven method we take a list of values even values, double each of them, but only pick the (int number){ System.out.println(“isEven called for “+num- 2 == } int ues){ values.stream() . ( ::isEven) .map 2) . () .orElse( } - doubleFirstE- ven method before we ponder further. (1, , ,4, ,6, 7,8, ,10 We called the doubleFirstEven method with a list of ten values. Let’s take a look at the output from this code. In the previous example, the method picked only the values for which the invoked method (isEven) re- turned true and the map method transformed the val- ues by doubling them. Finally the method
  • 38. Healthy Code May 201438 Even though we had ten values in the input list the isEven method was evaluated only twice. This is due to lazy evaluation of the functions presented to the and map methods. Rather than evaluating the argument functions right away the Stream (which is part of Java 8, other languages have similar data structures) postpones their evaluation. Furthermore, the Stream fuses the methods together, optimizing the execution to only the most essential steps. While this involves quite a bit of complexity under the hood, such optimization is possible due to function purity. Easy Concurrency Let’s revisit the isPrime example that we looked at in the beginning of the article. If the candidate number for prime check is small, then the time taken is not If the number is large, we would want to employ mul- tiple threads, especially on a multicore processor. If we started with the imperative style code, turning that into multithreaded code is not easy. We have to split the results across threads, and then merge back and error prone. Making the function style code concurrent is almost do that for us and we only have to give it a nod. Let’s see how. a function named isPrimeSequential. ( number){ number > && range(2,number) .noneMatch(index- } We iterate on a range of values, looking for the pat- tern of divisibility. For large numbers, we can make the computa- the Stream library in Java 8 does that already and all we have to do is simply ask, like in the next example. ( number){ number > && range(2,number) .parallel() .noneMatch(index- } TDD is a skill; it involves a decent amount of unlearning, relearning, and reevaluation. Let's not expect to get good at it instantly. You know it’s time to take a break when you’re fixated to review and fix code printed on the back of someone’s T-shirt. Pragmatic Programmer Quotes
  • 39. Healthy CodeMay 2014 39 We used the parallel() method on the Stream to turn the lazy collection into a lazy parallel collection. Un- der the hood the library uses a special kind of iterator called a spliterator to parallelize the execution. Let’s measure the time for the two versions. number = System.out.println(TimeIt.code(()-> new MeasurePrime(). System.out.println(TimeIt.code(()-> newMeasurePrime().isPrimeConcurrent Here’s the output from this code. As we can see there is a substantial speed improve- ment between the sequential and the concurrent ver- on our part. The JDK library took care of most of the work for us and all we had to do was provide it a few pure functions. Recap of programming in this article. Overall we are able to Declarative code keeps us focused. The what can be varied independent of the how. The code begins to read like the problem statement. Has reduced chance of errors due to fewer moving parts. Easier to test due to purity. Once we get our heads wrapped around it, it is a pure joy to program in functional style. You can access the code for the article from github.com/healthycodemagazine/May2014 References Java 8 Download: html. Venkat Subramaniam, Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expres- sions. Pragmatic Bookshelf, 2014. com/titles/vsjava8. Dr. Venkat Subramaniam is an award-winning author, founder of Agile Developer Inc., and an instructional professor at the University of Houston. He has trained and mentored thousands of software developers in the US, Canada, Europe, and Asia, and is a regularly invited speaker at several international conferences. Venkat helps his software projects. Venkat is a (co)author of multiple books, including the 2007 Jolt Productivity award-winning book Practices of an Agile Developer. His latest book is Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions. You can reach him by email at venkats@agiledeveloper.com or on Venkat
  • 40. Healthy Code May 201440 as your calling in life? Interesting question! Design has always been my passion and I feel like a born designer. During - nal workshop on usability, which was a paradigm shift for me. That’s when I realized designing is not only making things beautiful, but also making things usable irrespective of age, ability and situa- tion. That one workshop changed the way I think and work, and that’s when I decided to become a UX Designer. What was the best Android UX project you have worked on? Why? For any designer, all their projects are the best as every design has a challenge and a learning experi- ence. Shyamala Prayaga is a seasoned UX (User Experience) designer at Amazon. She specializes in mobile and web usability standards and accessibility. She designs and delivers cross platform mobile-user experi- ence across iPhone, Android, Blackberry, Palm Pre and Win- dows Mobile, and is passionate about speaking at conferences and workshops. Healthy Code spoke to Shyamala about the future of Android design, and here are the excerpts: The Future of Android Design Interview
  • 41. Healthy CodeMay 2014 41 Jokes apart, one of my best Android UX projects was an automotive shopping tool. When a user decides to buy a vehicle, there's a lot of market research, friends reviews and competitive analy- sis. After all the research done, sometimes there's a long waiting period to purchase the shortlisted model, because it may not be available with the dealer, or the desired color is not available and so shortlisted model/color with some other dealers with less or no waiting time and purchase them? We were trying to solve this problem and the so- Number) Scanning. Designing the whole UX for this application was so challenging and fun. What do you see as the biggest challenge in designing for Android Mobile? Almost every year Android comes up with a big release of their operating system, leaving apart the frequent patches, which brings in lot of UX and UI changes too. Since the design principles are still not consistently moving in one direction, it becomes something that’s sustainable for a longer period. This leaves designers to think in one direction and revamps, which I think is a big challenge. Is there such a thing as a mature design? Before talking about mature design, we need to ask ‘What is a design?’ In my opinion, design is a solution to a problem that you have. There can be many ways to solve the same problem through various designs. Some can be very complicated, some can be straightforward and simple, and some can be intuitive. I would say any design is mature, if it is able to achieve the goal it was intended for with minimum What does Android design have in store for the future? I think future Android design will include Aug- mented Reality, Gesture Based Interaction and Voice Based Interactions. What do you mean by Augmented Reality? Shyamala Prayaga This is a very interesting concept and an emerg- ing technology where we can map the virtual re- ality with the actual reality and interact with the applications. With Augmented Reality catching interactions, so why would Android lack behind? would be Augmented Reality based. Imagine I am using an online shopping application and can try products real time using the mobile’s camera and augmenting self live, as in a mirror. Or imagine playing cricket on a smartphone and augmenting yourself as one of your favorite play- ers. How much fun would it be! You also mentioned Enhanced Gesture Based Interactions. What is that? Android smartphones have become a one-shop stop for all the needs of the users right from online banking, shopping, playing games, and reading books. Ah, reading books, interesting! Imagine reading e-books by just using hand ges- tures and camera sensors, rather than swiping, tapping, pinching etc., to turn pages, zoom pages,
  • 42. Healthy Code May 201442 and more. Rather than using a touch or swipe to scroll pages in my application, just by using ges- tures, I can control the entire application. Wouldn’t that be fun? This is the future of Android design, which I fore- see for all the reading needs. How does Voice Based Interactions work? Imagine how easy it would have been if you could speak and control interactions of your smartphone, like a robot: By speech you could decide which applica- tion you want to open, download, browse, inter- act with. By speech you could decide whom to call, what to search for etc. By speech you could draft a huge mail, mes- sages, status messages of social apps like FB, WhatsApp. By speech you share images, videos, send as a future concept that Android would try. With Facebook acquiring WhatsApp, So- cial Media and Instant Messaging have gained lot of momentum and competition. How do you predict the future of messag- ing in Android? - quent upgrades it is making to its Hangout. I pre- dict a universal messaging system as the future of Android Mobile, where rather than having sepa- rate applications for video calling, voice calling, instant messaging and emailing, they would pro- vide an all-in-one solution where the UI will be slip between functionalities. Or who knows, maybe Android mobile would ship it as a default in-built functionality of the fu- ture devices. Every Android release has a unique play- ful name. Can you guess what the next one would be? Looking at the past trends with Android coming up with interesting names like KitKat, Jelly Bean, Ice Cream Sandwich, Eclair, the interesting future name could be chocolates like “Perk”, “Crunch”, “Snickers” or some deserts name like “Cheese Cakes” or “Rice Pudding.” Alphabetically, Lolli- pop or Lemon Pie sounds perfect, but I am sure it won’t be Apple Pie!
  • 44. Healthy Code May 201444 Article Have you been to a Code Retreat lately? Bharadwaj is a product manager at Appnomic Systems in Bangalore. hosted by Multunus in Bangalore and conducted by Venkat Subramaniam. Here’s a sneak-peek of the event from his eyes.
  • 45. Healthy CodeMay 2014 45 What is a Code Retreat? Code retreats are day-long coding fests. Program- mers take a crack at solving Conway’s Game of Life Puzzle in multiple short sessions. Each session is for 45 minutes. Developers work in pairs (miniature ex- treme programming sessions). Every session starts with a clean slate, that is, no carryover code at all. Test Driven Development (TDD) is encouraged. After ev- ery 45-minute session, a 15-minute stand-up meeting follows where everyone gets to share his or her expe- rience and things that they have learnt. At the end of the stand-up, the group may decide to impose some constraints for the next session like not using classes, no global state, no-returns-from-any-methods, etc. The choice of programming language, framework and design are all left to the pair. This meet-up at Mul- tunus had close to 25 programmers who kept on hack- ing away the whole day. Conway’s Game of Life alive or dead. Every cell interacts with its eight neigh- bors (just like the good old Tic-Tac-Toe game grid). Any live cell with fewer than two live neigh- bours dies, as if caused by under-population. Any live cell with two or three live neighbours lives on to the next generation. Any live cell with more than three live neigh- bours dies, as if by overcrowding. Any dead cell with exactly three live neigh- bours becomes a live cell, as if by reproduction. You can learn more about the game at en.wikipedia.org/wiki/Conway's_Game_of_Life. solve the puzzle along with writing tests (remember, we are using TDD) especially, if one is a newbie to ei- ther the puzzle or the language chosen. However, the fun is not in solving the puzzle itself, but it lies in the One can read more about the format and structure of Bharadwaj
  • 46. Healthy Code May 201446 JS ever. That straightaway exposed our weakness! Since we did not have time to learn a new framework we decided to hand-code the tests. I remem- ber writing some code that seemed to solve something. Along the way I re-discovered the right way to write inner functions in JavaScript. That was the highlight for me! Session III – Back to Scala The next session had me pairing up with a Java guy who wanted a sneak- peek into Scala. This time we used my laptop to code. In order to give him text-editor. I wanted to stay clear of ScalaTest and Scala’s build system - so as to give my partner a good look at some mass of code and not distract him While coding, I had this nagging realisation that I had not understood the problem well enough. I wanted some thinking-time away from coding and just focus on the puzzle. We were nearing lunch time also. So I decided to Session IV – Playing with Python Code Retreat at the community website - My Experience I, along with my partner (pair programmer), programmed in 4 languages, namely - Scala, JavaScript, Python and Ruby! Here is a brief on each of my sessions. Session I – Dive into Scala Programming Both my partner and I had prior experience with the language. Thankfully, my partner was fa- miliar with the problem too. We quickly discussed and zeroed in on a subset of the problem we - ing in Game of Life) and agreed on a simple design. We started The test part straightaway ex- posed my poor knowledge of the ScalaTest. Later while writ- ing code, we got stuck in trying to write object equality in Scala - something I could do with my eyes closed in Java. That was the second time my limitations were exposed. We programmed on my partner’s computer, and he used Gradle, which was a Session II – Playing with JavaScript JavaScript (JS) was common lingo with my next pair-pro- gramming partner in the sec- ond session. Neither of us had used any testing frameworks in
  • 47. Healthy CodeMay 2014 47 in Python. This guy had given a good thought into the problem and the approach we came up with was very refreshing! He coded away in Python, which I found easy to follow, and we wrote a lot of code. We were quite close to solving one of the situations in the game when the time ran out. Writing so much code to solve the problem meant that the test code was mini- mal during this session. However, I was beginning to appreciate the complexity and immense freedom of design that this simple-looking puzzle posed at us. Session V – Rolling with Ruby There were lot of Ruby developers in the group, and I was very curious to get a feel for this language. So I chose a Ruby-man for the last session. This person was much younger than me but surprised me by his thor- ough approach to TDD. He insisted on evolving the test code almost simultaneously with the main code, and I must admit, it did frustrate me initially. I wanted to write a blob of test code, write a blob of solution code, and keep alternating between the two. However, my partner, who was the one coding in Ruby, would have none of it. He requested that we keep shifting gears between the test-code and solution-code for ev- ery few lines of code. I knew he had a good point in what he was suggesting, and asked if he was really able to code like that in his work. His answer was af- - ated the young programmer’s discipline. Epilogue It’s not every day that I force myself to think on good programming problems. This was an excellent oppor- tunity for that. That itself made me immensely happy. I was split on approaching the problem from a bot- tom-up or top-down approach – which had me think- ing about an aspect of design that I had not thought for some time. I don’t remember the last time I pair programmed before this event. It’s a fabulous thing, and I want to grab every opportunity of doing so in future as well. The code retreat certainly pushed me away from my comfort zone, and that’s a great way to learn. Having not solved the problem still nags me. One of these days, I will sit down to write code that solves Conway’s Game of Life to at least some extent.
  • 48. Healthy Code May 201448 Already, a few approaches are brewing in my head. I recommend Code Retreat to all developers. Try to get in the next time it is happening somewhere nearby in your city. Last but not the least, Venkat put forth some wonder- ful thoughts on the endeavour of software develop- ment. I also saw a great start-up in Multunus. The day was a delight. Big thanks to all my partners in Code Retreat, and all those who made the event possible. If it comes around, I am going again. Bharadwaj works as a technical product manager at Appnomic, and was previously with HP. He programs mostly in Scala and JavaScript, and is also quite comfortable with Java and Octave. He has done his MBA from IIMB. Bharadwaj W e all want to create a simple design, but the act of creating such a design is not that simple. W e looked at this problem and said we can solve it using a pool of threads. Now we have a pool of problems. O ur field has fundamentally transformed in the last two decades, from developers fighting DLL hell to fighting assembly and jar hell. Pragmatic Programmer Quotes
  • 50. Healthy Code May 201450 With time developers soon realized that JavaScript, the most used language of the web is missing a proper build system and JavaScript task runner. Do you want to run your JavaScript tests? Grunt has it covered; production? Well, Grunt takes care of that too. This article will talk about playing with Grunt in web applications. and technology conference speaker gave an exclusive interview to Healthy Code when he about the current state of Groovy and Grails and the issues companies face in moving away from Java to embrace it. He discussed the latest web favorite HTML 5 and how it has changed the way web applications are developed today. He also spoke about several toolkits and libraries that are popular among developers. Functional programming promotes pure functions or functions with no hygiene while programming has a purity with examples. Coming up in the June issue Functional Hygiene: Reasons to Avoid side effects Get your Grunt on - Rocky Jaiswal Interview with Ember-Data is a module of Ember.js that allows us to bind our client side logic seamlessly with backend services. It has been coming for quite a while and needless to say, even in its nascent stages, it managed to make our lives much easier than what it used to be. Now we have reached a stage where Ember- Data 1.0 seems almost around the corner. This article aims to familiarize the reader with Ember-Data’s functionality and philosophy. On the Way to Ember - Data 1.0 – Dr. Venkat Subramaniam – Abhimanyu Chakravarty Owned and Published by T. Sivasubramanian. Published from 11/6, First floor, Fourth street, Padmanabha Nagar, Adyar,Chennai - 600020 and printed by M. Elumalai, at Sakthi Scanners (P) Ltd, 7, Dams Road, Chindadripet, Chennai - 600002. Editor: S.Prabhu.