Use tap events instead of click events in iPhone browser
Posted by Jon in Javascript, iPhone on June 18, 2010
When working on a web app for embedding in a iPhone application we came across jQTouch, a really nifty little jQuery plugin which makes it easy to create a web application UI that really resembles that of a native iPhone application.
We soon encountered a problem due to the fact that click events are rather slow to fire on the iPhone. There is a delay due to the fact that the iPhone waits for the user to complete a gesture before deciding that the intended gesture was in fact a click.
JQTouch uses divs to navigate between screens, so for example if you have the div
<div id="primary-view"></div>
you can simply navigate to it through a normal anchor link, and the transition will thanks to jQTouch be really “iPhone like”.
<a href="#primary-view">Primary view</a>
Our main problem is that we load our content dynamically through Ajax. So our links looked like this:
<a onclick="fetchContent();" href="#primary-view">Primary view</a>
This resulted in a race condition. The anchor link listens to the tap event which is fired much earlier than the click event, and therefore we mostly ended up in empty views. So we needed to replace all onclicks to ontap listeners. The problem then is that we could no longer test our webapp in a normal desktop based Safari browser.
So, we decided to happily go along and write inline onclick events on our links and other interaction elements. But while in the iPhone we see to it that the onClicks are removed and replaced with tap listeners.
That function looks like this:
function rebindClicks(){ var userAgent = navigator.userAgent.toLowerCase(); var isIphone = (userAgent.indexOf('iphone') != -1) ? true : false; if (isIphone) { // For each event with an inline onclick $('[onclick]').each(function() { var onclick = $(this).attr('onclick'); $(this).removeAttr('onclick'); // Remove the onclick attribute $(this).bind("click", preventClickEvent); // See to it that clicks never happen $(this).bind('tap', onclick); // Point taps to the onclick }); } } function preventClickEvent(event) { event.preventDefault(); }
We now call this little function everytime the DOM is changed. If something turns up with an inline onclick. It is will be rerouted by jQuery to a tap listener instead.
Again, we felt we needed to do this because many of our developers do not have a Mac (and hence do not have the iPhone simulator). And testing on the iPhone can be really time consuming. So for testing during development we wanted to use onClick, and when testing on iPhone we wanted to use taps instead.
But the biggest bonus was without a doubt that things are overall much faster in the web application. Taps fire much faster than clicks in the iPhone.
Here’s how it looks running the same app both in desktop safari and embedded into the iPhone simulator.
Rule 4: Use Only One Dot Per Line
This is the fourth part of a series of articles starting here.
The fourth rule of the exercise is to only use one dot per line. Why is that important? Well apart from the apparent readability increase, many dots one one line can signify that an activity is happening in the wrong place. Or maybe your object is dealing with two other objects at the same time.
In both these cases you are not fully implementing the object oriented paradigm. Objects are supposed to know something about their immediate “friends” but not about their friend’s friends.
This is an example of a quite broken implementation.
public class TimeLineObject extends UIComponent { .... public function redraw():void { TimeLineDrawer.theInstance.drawTimeLine(TimeLineDrawer.theInstance.timeLineCanvas); } }
To follow the rule of this exercise you might be tempted to remove the number of dots per line by doing something like this:
public class TimeLineObject extends UIComponent { .... public function redraw():void { var timeLineDrawerSingleton:TimeLineDrawer = TimeLineDrawer.theInstance; var canvas:Canvas = timeLineDrawerSingleton.timeLineCanvas; timeLineDrawerSingleton.drawTimeLine(canvas); } }
But this is hardly the point. It is very apparent in the above example that the activity as a whole is not in the correct place. In the TimeLineObject we are suddenly telling some remote singleton static object to carry out things for us. Our object knows to much and the architecture has in fact failed at some earlier point.
The example from the Thoughtworks book is excellent. It shows the correct way to think about the exercise, namely to put activities in its right place. I will quote it below. First the “erroneous” example:
class Board { ... class Piece { ... String representation; } class Location { ... Piece current; } String boardRepresentation() { StringBuffer buf = new StringBuffer(); for(Location l : squares()) { // Oh lord lots of dots here... :) buf.append(l.current.representation.substring(0, 1)); } return buf.toString(); } }
Applying the rules of having one dot per line here actually means REAL refactoring. I.e putting stuff where it belongs. And that is usually in other classes. Here’s the refactored example:
class Board { ... class Piece { ... private String representation; String character() { return representation.substring(0, 1); } void addTo(StringBuffer buf) { buf.append(character()); } } class Location { ... private Piece current; void addTo(StringBuffer buf) { current.addTo(buf); } } String boardRepresentation() { StringBuffer buf = new StringBuffer(); for(Location l : squares()) l.addTo(buf); return buf.toString(); } }
So, the lesson from this exercise is that you should put activities where they belong. Avoid using static utility classes and other “middleman” objects. And make sure that the object you are working in does not now to much about other object’s activities. Couple this with the previous rules and you have gone far in a sturdy, nice looking design.
Previous « Rule 3: Wrap All Primitives and Strings
Next » Rule 5: Don’t Abbreviate
Rule 3: Wrap All Primitives and Strings
This is the third part of a series of articles starting here.
Wrapping primitives (ints, floats etc) and strings is an easy way to increase maintainability and readability of your code. Also, as Abinesh TD Consider for example the following pseudo-javacode:
public class Contact { private String emailAddress; public void setEmail(String emailAddress) throws InvalidEmailException { if (! validateEmail(emailAddress)) { throw new InvalidEmailException("Uhm, that's not a valid mail address..."); } this.emailAddress = emailAddress; } public String getEmail() { return emailAddress; } private Boolean validateEmail(String emailAddress) { // TODO: validation regexp etc } }
A very simple class, containing a single field intended to hold an email address. It looks good enough, but imagine that you have other places where you would need to validate and store email addresses. You would have a tendency for code duplication right there.
Worst case would be that you would have a validation function in every email container class. It would be better to wrap the string intended to hold the email address in its own class, even if it only holds one field, the potential for code reuse increases exponentially.
A better implementation could look like this:
public class Contact { private EmailAddress emailAddress; public void setEmail(EmailAddress emailAddress) { this.emailAddress = emailAddress; } public void setEmail(String emailAddress) { try { this.emailAddress = new EmailAddress(emailAddress); } catch (InvalidEmailException e) { // Oh lord something went wrong here... :) } public String getEmail() { return emailAddress; } }
The benefits should be immediately clear. Suddenly the class EmailAddress requires the email address string to be valid to be instantiated at all. This would make it much easier to quickly zero in on bugs and also increases the potential reuse of your code.
Pretty much any variable you want to store, whether it is a primitive or a string – WILL need some sort of validation. This is a major reason for wrapping them. But other than that, consistently wrapping gives your object oriented code a higher degree of encapsulation.
Previous « Rule 2: Don’t Use the Else Keyword
Next » Rule 4: Only Use One Dot Per Line
Rule 2: Don’t Use the Else Keyword
This is the second part of a series of articles starting here.
The second rule of the “Nine Ways to Better Software Today” is to stop using
elseThis builds on top of rule 1, to decrease the level on indentation by again focusing on minimizing complex conditionals. Within the object oriented paradigm, polymorphism is a powerful model to handle this. Regardless of programming model, this exercise forces you as developer to find alternatives to using the else keyword and thus considerably beautifying your code.
Consider the following Python code
def set_member_status(member, status): """ Spot the else keyword """ if is_active(member): do_something(member, status) else: do_something_else(member, status)
There are several ways to simplify this method. For simple cases use early returns, as below. Early returns only work in methods which are short and lacking in complexity (keeping down the level of indentation helps with this). Once a method is long and contains many levels of abstraction, early returns can of course not be used. But by then you’ve failed at this exercise anyway.
def set_member_status(member, status): """ Example of using early returns """ if is_active(member): do_something(member, status) return # here is the early return :) do_something_else(member, status)
In many languages it is possible to use the ternary operator. That would look something like this (in javascript):
/** Wrong */ function drowned() { if (timeInWater < SURVIVABLE_TIME) { return false; } else { return true; } } /** Right */ function drowned() { return timeInWater < 10 ? false : true; }
Guard clauses is another way of increasing readability. The following example is taken from here
double getPayAmount() { double result; if (_isDead) result = deadAmount(); else { if (_isSeparated) result = separatedAmount(); else { if (_isRetired) result = retiredAmount(); else result = normalPayAmount(); }; } return result; }; double getPayAmount() { if (_isDead) return deadAmount(); if (_isSeparated) return separatedAmount(); if (_isRetired) return retiredAmount(); return normalPayAmount(); };
Previous « Rule 1: Only Use One Level of Indentation
Next » Rule 3: Wrap All Primitives and Strings
Nine Steps to Better Software Design Today: Thoughtworks Exercise
There are few companies out there more exiting to me than Thoughtworks. They sport a fantastic set of values, and have some of todays most brilliant programmers and software thinkers on board. But what strikes me as most wonderful about them is the way they communicate with programmers around the world. They really have an interest in good software, whether it is their own, or somebody else’s.
On reading their book, the Thoughtworks Anthology there was one chapter (Object Calisthenics by Jeff Bay) which struck me as extremely fun to read, it contained an exercise called “Nine Steps to Better Software Design Today”. An exercise completely focused on object oriented design quality with all that that entails, like encapsulation and appropriate use of polymorphism.
It is really a very simple exercise in many aspects, it simply provides nine rules, and asks me as a developer to do my absolute best to abide by those rules. What Thoughtworks does is so ingenious. Instead of just preaching the holy grail of object oriented programming, they ask me to be a part of the sermon. On reading the whole exercise I was instantly revving my engine to actually do the exercise. So I started up a small GWT project and forced myself to actually try and comply with the nine rules.
I’ve never had so much fun programming! And the process truly changed the way I will write code from now, whether it is in a purely object oriented language or not.
Said and done. I will start with the first rule:
Rule 1 : Use only one level of indentation per method
No matter which language you are working with, this is something that is very important. Check out the class, that thoughtworks uses as an example, below. It contains one function with several levels of indentation.
class Board { String board() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) buf.append(data[i][j]); buf.append("\n"); } return buf.toString(); } }
Now consider that after some refactoring the code could look like this:
class Board { String board() { StringBuffer buf = new StringBuffer(); collectRows(buf); return buf.toString(); } void collectRows(StringBuffer buf) { for (int i = 0; i < 10; i++) collectRow(buf, i); } void collectRow(StringBuffer buf, int row) { for (int i = 0; i < 10; i++) buf.append(data[row][i]); buf.append("\n"); } }
What basically has happened here is that methods have been extracted for each level of indentation. The whole class is so much more readable, unit testable, understandable… you name it. Or as the authors of the chapter puts it:
Try to ensure that each method does exactly one thing. One control structure, or one block of statements per method. [Heavy indentation] in a method [is] a signal that you’re working at multiple level of abstraction, and that means you’re doing more than one thing.
…
Working with methods that do exactly one thing, and classes doing exactly one thing, your code begins to change, [...] increasing exponentially the level of reuse.
Next time I will talk about rule 2: Don’t use the else keyword
Public Wave Invites?
Posted by PEZ in Innovation, Values on November 12, 2009
I just experimented with an interesting thing on Google Wave. I made my “Invite others” wave public. Now anyone on Wave can invite people using my invites. Pretty cool. Just a minute after I made the wave public the first person entered and used two invites. It feels quite awesome. Can people handle it all the way? Will someone come in and just use up all the invites? We will soon know. =)
Has anyone else done this? Are there lots of public invite waves out there?
Flickr Searches in 3D
Posted by PEZ in Flex/AS, Innovation on November 3, 2009
I’m experimenting with tying that 3D Album I mentioned earlier to Flickr Searches. Looks like this for now
ThreeDeeGallery.swf
Work in progress, both the app and this blog post.
Innovation – the heartbeat of products
Posted by Ram Sundararajan in Social, Values on July 31, 2009
Lately, I have been thinking and reading articles about innovation and innovative companies and I finally got the time to jot it all down over the weekend. And here are my thoughts…
Many companies want to be perceived as innovative. But are they really innovative?
Part of any process in a company should be to focus on products, the end goal that forms, guides and informs innovation. Wanton innovation is wasteful. There must be something in the product to pull it all together.
There are many companies that develop new technologies and go in search of problems for those technologies to solve. Take the internet bubble for instance; it was defined by this kind of thinking. It was a carnival of worthless innovation. Half baked business ideas and models pumped into money burning concerns in a misguided attempt to make quick bucks and beat the competition. Entrepreneurs launched websites for selling pet foods and some built gaint warehouses for delivering groceries by van. It turned out that no one wanted to buy groceries delivered to them by web van’s warehouses. Alas! The internet bubble burst taking with it all these half baked “innovative” ideas and businesses that had developed solutions to problems that never existed.
We need a very product oriented culture in companies. Lots of them have tons of great engineers and talented smart people. But ultimately there needs to be some gravitational force in the product to pull it all together. This gravity is what I feel innovation is all about.
I strongly believe that money is not the key for innovation. The key is the product focus and a product development cycle that has room for innovation. Microsoft for instance, spends billions of dollars in Research. Every year it invites journalists to look at its massive concrete and glass structure full of “innovations”. Yet, they end up copying things that Google or Apple does. Look at hotmail or yahoo mail apps. Its gmail mocked! Or Zune, the Microsoft variant of iPod, an obvious copy. The only product I know, correct me if I am wrong, that came out of these research facilities is the speech recognition component in Vista. Yeah it works well, but it is not a killer like gmail or iPod.
Talking about the key aspects of innovation, I think the company’s focus on the product is a must. If a company wants to be innovative and wants to differentiate itself from the rest, I think that it should question its products and its product development cycle.
As an example, let us look at Kano model of customer satisfaction.
It categorizes the features built into any new product as
• Must have feaures
• Linear features
• Exciter features
Must have features are the ones that must be in the product to be useful. Without the must haves there is no product. However, I feel that the must have features need not be fully implemented when the product is released. A “just about right” or “lagom” amount of completed must haves will do.
Research suggests, that although without the must have features the product will be useless, it is the linears and the exciters that gives more satisfied users.
Let us say, that I wanted to build a hand held music player. What are the must haves required for this tool to be useful?
Let us assume, a good head set, some hard drive to store music files, a play/pause/rewind/fast forward button
One can of course spend a lot of time for instance to make the head set really really good. But a good enough head set would fetch us “just about satisfied” users. There are other important things that can make the player really good. So lets stop there and move on!
The Linears, they are the ones that gives the user more satisfaction. A linear feature is the one for which “the more the merrier” holds true. It is called linear because customer satisfaction grows linearly with the quantity of these kinds of features. The more the linears in the music player the more satisfied the user gets.
Some examples of the linears I would like to add to the music player are
1. Good battery
2. A good display
3. A scroll wheel on the sides to browse music
4. Auto and manual lock/unlock button to lock when the user is on the move
5. Slick design
6. Light weight
7. Games, calendar, clock etc
Exciters are the ones that add great satisfaction to the customer. It often adds a price premium to the product. However, a lack of exciters will not decrease the customer satisfaction below neutral. But I believe that exciters are the ones that will make the product be perceived as innovative and these are the ones that make the product stand out from the rest of the pack.
Some exciters for the music player would be
1. As soon as I plugin the music player, it will bring up the users’ default music player (whatever it might be) and sync songs both ways.
2. Charge free device that uses solar and advanced light sensitive batteries
3. Maximum of 2 clicks to access any song on the hard drive.
4. No buttons in the player. We make the whole music player a touch screen.
In whatever feature in a product we do, we got to have 1 or 2 real exciters. Look at gmail for instance; they have built in at least one exciter in any type of functionality you find there…that is innovation! Google’s key to beat the competitive market where yahoo mail and hotmail once ruled!
For a product to be innovative, companies should integrate both linears and exciters in their feature list and make it transparent in their product development cycle. Categorizing features this way can contribute to an innovative company.
I believe that only innovative companies can stand in this harsh, competitive, volatile market. The more successful a company is in finding and implementing the exciters, the longer and happier the customer stays and hence stronger and faster the company grows. Many companies focus on adding a lot of linears to their application, this is not bad afterall. But they have to realize that time is wasted! Linear features increase the customer satisfaction to only a certain degree. They will not fetch greatly satisfied customers. Feature freaks got to think about it and control their temptation!
“Do you need satisfied or greatly satisfied customers?” One real good exciter is better than 10 different features. To me, it is like comparing a man to monkey!
So, let us all build more exciters…not just features!
Points or days? Should we care?!
Posted by Ram Sundararajan in Social, Values on July 27, 2009
Some months back, I wrote a mail to you guys about the easiness and the usefulness of using points system in a story instead of calculating its size in days or hours. I thought that I should blog this discussion now as I think that it might be useful for others too.
For calculating the effort involved in a story we now use days as the unit. By days we actually mean “ideal” days.
That is, we smartly ignore other work related things a developer does in a typical day and calculate only the amount of time s/he has to spend on the story.
We have calculated an ideal day to be 60 % of the developers’ typical day. In other words, it is 4.8 hrs or let us say 5 hours to approximate.
I think that this ideal day system for measuring the effort or size of a story brings in some unnecessary ambiguity into our calculations.
To understand what I mean, let us go back and ponder on what estimation means to us?
What are we trying to do in the estimating meetings?
The answer I think is, during the estimation meetings we are trying to define the size of each user story. In other words, we are trying to categorize each user story based on our previous experience and calculate the effort involved to put these stories into sizes or points like S, XS, M, L and XL or 1,2,3,5, and 8 respectively.
Great, so why do you use “ideal” days?
Well, I think that we use ideal days because we somehow wanted to relate time to effort so that we can know how many actual days a story is going to take or taken. Also, it becomes easy to express the status in number of days to the stakeholders rather than with an abstract entity called points. Yepp, true…but I think, this creates ambiguity to a very large extent when practised. For instance, an ideal day for person A need not be the same as the ideal day for Person B. So I think this system is highly subjective. It does not make sense to me to use a system that varies a lot between individuals.
If we wanted to measure how long a story is going to take, we should instead use the team velocity and perhaps create baselines using Burn down charts.
These two measures together can give a better approximate estimate in time for a story.
Let me add some weight to my argument with Mike Cohn’s thoughts on estimation
Choosing between story points and ideal days
With Agile methods, it is perfectly okay to use either points or ideal days as the measure of the size of a user story.
But I think that the points system is more advantageous and complete. Read on…to know why?
According to Mike (and I totally agree with him of course), below are the key advantages of using a points system
a) My ideal days are not your ideal days
b) Points estimate do not decay
c) Points are pure measures of size
d) Points estimation are usually clearer and thus faster
a) My ideal days are not your ideal days
Let us say, two runners one fast and one slow are standing at the start of a trial. Each can see the whole track of the trial and can easily agree that the track is one kilometre long. They either come to the agreement because of their previous experience or by comparing it with another track. Either way the process is easy and intuitive. Tracking the length of the trial is similar to the points system. That is, one simply measures the size.
Now, let us bring in some ambiguity by adding more parameters…
Suppose instead of discussing the length of the track, the runners wanted to calculate the time it takes to run the trial. Obviously, the time taken by the fast runner will always be lesser than the slower one. It is going to be difficult for these runners now to come to a consensus. Both of them with different numbers are correct from their point of view. They probably will never agree as to how long it will take to run the trial.
There is another thing that we need to pay attention too. An Ideal day between developers differ a lot because they are constantly involved with something else other than the story development. Things like support issues, big maintenance bug fixes, investigation, design for future projects all takes time.
So as said, the ideal days system is too subjective to be a standard.
b) Points estimate do not decay
An estimate in points has a longer life span than estimates in ideal days. It is simply because the point estimate only takes into account one parameter and that is the size.
Let me explain this with an example. Let’s say that we are to use ideal days to estimate a story that has to use a new technology like flex. We know that none of the developers have worked with it before and we have to do a lot of investigation and learning to produce the story feature. So, let us assume that the developer estimates it will take 13 ideal days to complete the story. Great!
Now, let us fast forward a few sprints and ask the same developer how long another similar flex story will take to do. Obviously, the estimate will be lesser, let’s say s/he says 3 ideal days. Bingo! we got a problem here. Similar stories take different amount of days to implement.
Many teams tend to ignore this as a problem because they think it is only logical that the amount of ideal days decreased, because the developer knows more about the technology now than before. They also argue that measuring team velocity over time would even out this difference. But it actually won’t in reality.
Because…we will see that using ideal days, the team velocity always remains the same even though developers do more work. See, the developer now after a few sprints produces the same feature in 3 ideal days, where the first time it took 13 ideal days. In other words, in 13 days the developer is now capable of producing 4 such stories (4 stories X 3 ideal days = 12 ideal days). But with ideal days the developer’s velocity is always 13 even though s/he can complete 4 such 13 days stories in 13 days. So ideal days do not reflect the actual team velocity in this case. (logically, after a few months the team velocity should have gone up)
With the points system, we do not take time into account…we just calculate the size. For instance, we say that the flex story is about 8 points or XL large and then after a few months, the team velocity is calculated, now we see that the velocity goes up because the team is now able to complete X number of more XL stories than they did previously.
c) Points are pure measures of size
As said earlier, points are pure measures of size and ideal days are not. Of course, ideal days can be used as a measure of size, but with deficiencies. As in the above example, points remain the same but ideal days tend to vary depending on the developers expertise.
Story points being pure measure of size has a couple of advantages. First of all, story points allow the team to estimate stories with analogies. It makes the estimation easy and more fun as we are only talking about “this story is like the other one” and hence should be for example an L or 5 points. When we estimate in ideal days, we can use the same analogy approach, but the problem is that we tend to bring in the calendar days and measure how long a story will take to execute instead of looking at how big a story is. As said, “how long” approach has hidden problems!
Secondly, a story being an abstract measure of size escapes the temptation to correlate it with reality or time. Less is more!
Ideal days has an inherent comparison built in
That is, we tend to always end up comparing actual vs ideal time.
Then this pondering eventually ends up with questions like, “how the heck we ‘only’ did 8 ideal days of work in a 14 day iteration?” You know more often than not, many teams put the blame on some bully.
d) Points estimation are usually clearer and thus faster
Yes, to me it sounds obvious that it should be really easy to estimate a story on just the size. We skip detailed level of discussion and it makes things easy.
So in estimation meetings, we got to decide only if a story is an XL or M?…Then arises suggestions like we got to do these and these things. Further the last time we worked on that piece of code we found that we had to re-factor it etc. We can also use our previous stories as analogies. Perhaps a similar story that was an XL involves lesser effort this time?! Maybe maybe not…that’s what we decide in estimation meetings.
My point here is that it is easy to talk on higher level and skip going into the details.
Of course, we got to break down the story into smaller tasks. But that has nothing to do with estimating a story size.
Finally, I think that estimation in ideal days has some advantages. But I unfortunately can see only one obvious thing.
Stakeholders want to know when a story will be finished. Is it by Aug 1 or Aug 15? Calculating ideal days might be easier
to get to the date the stakeholder wants to know. But it is like a shortcut and it creates a lot of side effects for the team members.
So I think we gotta stick to the best practises that agile gurus suggest. That is points for a story size and velocity based on points for the team! Just as Ez as it can be