Sunday, April 7, 2013

Should I Add More Developers?

By Jeremy Conkin:  

Brook’s Law and Developer Head Count
Scope, time, cost.  These three elements compose the standard project management triangle.  In consulting, cost usually translates to head count.  When cost isn’t fixed, project managers will add more developers to provide a richer featureset or shorten shipping timelines.

Ideally, every developer added to a project yields the same amount of value for every day spent as a member of the team.  Staffing with this assumption is straightforward.  Let’s say the product owner wants a specified number of story points before shipping, and the product burndown chart predicts the team will fall short.  If new developers contribute a fixed number of points per sprint, project managers merely have to add solve this formula:


# of devs to add >= ((points needed)-(points projected))/((developer contribution) * (# of sprints remaining))

Brook’s Law contradicts this formula by stating that “adding manpower to a late software project makes it later.”  Here are some factors to consider when adding new developers to a project.

Ramp-up time

Generally a developer needs time to learn the code base and the best practices of a team.  Over a developer’s first two sprints, the team should expect smaller throughput from the new team member.

Mentoring

For a new team member to succeed, time must be reserved for integrating this person.  Some of these responsibilites include
  • Pair programming
  • Thorough code reviews
  • Explanations of project practices
These tasks impact the velocity of the team.

Diminishing Returns

As team size grows, efficiency per team member decreases.  Communication overhead and code integration tasks grow with the team.  For these reasons, scrum best practices recommend keeping the team size under 10.  Expect a percentage drop in team efficiency for each team member added.

Holistic Look at Adding a Developer

This graph makes the following estimates
  • The team was previously delivering 30 points per sprint.
  • A new dev will contribute 8 points per sprint.
  • 2 sprints of ramp-up are required.
  • Mentoring will take between 3 and 6 points during ramp-up.
  • The team will drop 10% in efficiency with a new member.

As you can see, adding a new developer to this project wouldn’t result in positive throughput until sprint 3, but a cumulative gain in points wouldn’t happen until a hypothetical sprint 4!  If the product owner plans to ship after three more sprints, the team would not benefit from having a new developer.

Does adding more developers to a project lead to an earlier ship date?  The answer depends on how much time is remaining on the project.  When augmenting staff on an exsting team, be sure to consider Brook’s Law.

Monday, March 11, 2013

Manually Adding Documentation in XCode

By Jamal Rogers:  






Documentation is extremely helpful when it is embedded in XCode. Not only is it readily available offline, it allows you to see popup contextual notes on different functions. It also gives you more information in the Quick Help inspector. One good feature of XCode is that allows you to add third-party documentation easily, just by adding a feed URL in the documentation preferences menu. When creating third party documentation, the creator can generate an atom feed that provides all the information XCode needs to download and install the documentation. And being a feed, it can be easily updated with new versions of the documentation.

At Solstice we make frequent use of RestKit, which is a great framework for interacting with web services via HTTP. The project has recently undergone major changes, an the current version of RestKit is significantly different from previous versions. Consequently, much of the documentation has also changed. For our projects that still use the older versions of RestKit, we would like to keep the old documentation in XCode. Ideally, there would be separate atom feeds for each version of the documentation. However, there is only one feed for the RestKit API, and that contains the current version. Fortunately, the RestKit site has links to previous versions of the API documentation. To get the docs for version we need, I downloaded the archived file org.restkit.RestKit-0.10.3.xar, then extracted the .docset file with on the Terminal command line using the command: xar -xf org.restkit.RestKit-0.10.3.xar. After copying this .docset file into the directory ~/Library/Developer/Shared/Documentation/DocSets, and restarting XCode, the RestKit v 0.10.3 documentation showed up in Xcode. I then went into the Downloads tab of the Xcode preferences menu, under Documentation, and made sure that "Check for and install updates automatically" was unchecked, otherwise the new version of the documenation would overwrite the old version the next time XCode checked for updates.

Monday, February 11, 2013

Blocks and Memory Management (Stack vs Heap)

By Pablo Alcalde:  

With ARC (Automatic Reference Counting), working with blocks has become an easier task, but there are still some issues we can run into if we don't understand how they work.  While blocks can be tricky to set up and manage in code, they are one of the most powerful tools, especially when programming asynchronous tasks.  Here are the concepts we need to understand before we can go more in depth:

Memory
Stack: This is the fastest way to read and write variables for the compiler. There is one private stack per thread. Threads share information through the heap. When we enter into a new scope (declared with "{ }" in Objective-C), the compiler makes space for it in the stack, when this scope ends (returning from a function or getting in to the close bracket), the compiler releases all the space allocated in the stack for that scope by returning the stack pointer back to the previous position into the parent’s scope. As a result, there is no way to retain objects allocated in the stack:  the object(s) will be released when the scope ends no matter what you do.

Heap: It is unique per application and it shared between all threads. It is a simple structure where you put objects that will never be released unless you (or ARC) do it manually. It is slower than the stack but there are many advantages: it can request more space if it needs it (if a stack runs out of space your app will crash with a stackoverflow exception), and you can delete any object without affecting another (in the stack this is not possible, since you push and pop things in a specific order).

Blocks
So how do blocks fit in the picture?  Well, blocks are the only objects in Objective-C allocated by default in the stack.  Why?  Because the compiler always prefers to allocate things in the stack (it’s faster), but it only can do that if it knows the exact size to allocate. Only plain values (like pointers) can be allocated in the stack. Blocks are fixed in size. You can not modify a given block once you’ve created it. Blocks are constant during the whole execution. They are pieces of code that needs to be executed fast, so they are perfect candidates for the stack.

Can we move a block into the heap so we can pass it to another scope, knowing that it will never be released unless we do it manually? Yes, using copy. Everytime you send a copy message to a block, it is moved into the heap (if it wasn’t already).  However, you then would be the one responsible for releasing it (if you use ARC, it will do it for you, as it does with any other property).

You can do  [myBlockVariable copy] if its a local var, or you can set it directly in the declaration if its a property like this:
@property (copy, nonatomic) void (^myBlockVariable) ();

Remember: If you use retain rather than copy with a block, it might work if the block is already in the heap.  But, if your block is in the stack (and they are by default), you can not retain it.
The block will be gone once it’s out of scope no matter how many retains do you have. In order to have your block retained pass its scope you should always use copy. Using copy more than once for the same object doesn’t create multiple copies of it - it only increases the retain count of that object in the heap.

Rule 1: If you are creating a block that is going to be executed in another class (most cases) you don’t need to copy it. It’s the receivers responsibility, not your's. The receiver should also release it after it’s done with it.

Rule 2: If you are creating/receiving a block to be executed in your class through different scopes. Use copy and set it to NIL when you are done with it.

Retain Circles: The use of self in Blocks
There is another memory issue when referencing properties inside a block. The only way a block can ensure that the objects it is using will be always available is by retaining them. If a block is alive in memory, the objects that block uses within its code should also be available, at least until the block is released.

If self (my class) has a property that is a block, self is strongly pointing to the block.
If the code within the block references to self in any way (self directly or self.property or [self someMethod]), the block is then strongly pointing to self: 




So self can never be released when the parent retains go away because it has something strongly pointing to it (the red arrow) and our block can never be released because it has self strongly pointing to it also.  If the block lives in the stack because no one sent a copy to it, we wouldn’t have a problem since the block will be automatically released when its out of its scope, and the retain of self by the block will be gone.  The problem here is that you can’t know if the block is in the stack or not.  If the block lives in the heap, we could avoid this scenario releasing our block (setting it to NIL) when we are done.  The problem here is that you usually want to have your block alive while the class is alive. You usually don’t create a block to be executed only one time, right?

So what’s the solution to eliminate the red retain then?

Use always a weak pointer to self rather than self within blocks:__weak MyClass * weakSelf = self; //weakSelf could never retain any object now

Of course you are talking a risk here since you are not retaining objects that will be used in the future. You should then make sure that self (and its properties) are still alive every time you call your block from any other class. Otherwise, you will get a bad access memory.

If you break any of these rules exposed here your code might (or might not) still work if you are under ARC. However Apple suggests to use always this rules in order to be 100% secure.

Hope this helps you understand blocks better!


Monday, February 4, 2013

Teamwork is Priceless

By Benjamin Craig:  

The first team I’ve worked on here at Solstice has just finished a release sprint. As the project wraps up, it is essential to look back and assess what went well and what could have gone better throughout the life of the project. This post will be focused around just one aspect of working on a project, which is in my opinion the most valuable aspect; teamwork.   

Teams bring a variety of experiences and perspectives that synergize in a beautiful way. Each person brings a unique viewpoint and if everyone trusts that their contributions are appreciated, ideas flow with abundance.  In a supportive environment everyone releases his or her thoughts to the team, and the product ideas start to mix. The group distills the technical and artistic design into essentials by building, understanding, and reaching a consensus. Nobody minds who thought of this or who disagreed with that. The group produces work that none of the individuals could have come close to achieving individually.

Another great benefit of teamwork is the shared sense of responsibility. Humans are social (yes, even developers!), and the sense of camaraderie they develop with a team helps to persevere through challenges and reach success. There isn’t the extreme pressure that sole developers may feel; alone and responsible for delivering quality on time. Rather, there are other experts all around the office eager to help solve the problem. It may be as simple as making it a priority to eat lunch with somebody. 

However, I may be biased towards our teams here at Solstice, that are just not large enough to shield anyone from responsibility. With that being said; everyone has a defined role, and everybody gets things done. Our teams are co-located, which is important because face-to-face interaction is by far the most efficient way to communicate. When teams don’t rely on communication by telephones, video chat software, or email to get their point across, the whole development effort tends to move much more quickly.

Friday, February 1, 2013

Animating on a SurfaceView using Sensors

By Samuel Frank Smith:  

I'm going to be demonstrating how to animate a few colorful balls in an Android view, based on the gravity returned by the device's sensors. The points we'll focus on are using a SurfaceView, SensorEventListener, and animating using a thread. While some code snippets are here, it's highly recommended that you download the provided project.




While I won't cover every section of the code, it is brief and should be straight-forward. I will however be sure to discuss the points mentioned above. 

To begin, there are three main class files. The Ball class is an object that holds information on the Ball's position, velocity, and image. The application has a single Activity, AnimateSensorActivity, which will hold our custom SurfaceView, track Sensor changes, and pass information to the animation thread. The final class is the meat of the application; it contains the animating thread which updates balls' positions, draws them to the canvas, and informs the surface of changes.

In our Activity we implement SensorEventListener and create a SensorManager to access the devices sensors. The Listener will allow you to detect changes when they occur; this callback then updates the gravity variables that belong to the animating thread. The Manager is needed to request access to these sensors which is done in onCreate. A final point about these sensors is to ensure access from the manifest.

public class AnimateSensorActivity extends Activity implements
SensorEventListener { … }

Registering sensors:
protected void onCreate(Bundle savedInstanceState) {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}

Passing gravity to our animating thread:
public void onSensorChanged(SensorEvent event) {
animationThread.setGravityXandY(event.values[0], event.values[1]);
}

Manifest feature use:
<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true" />

SurfaceView is a View that allows drawing to it. Like a normal view it sits in the layout hierarchy, can have children, and so forth. The callback implementation is so that we can stop and start the animating thread when the surface is present. We also take the SurfaceHolder and give it to the thread. The holder will allow the animating thread to lock changes on the canvas from being updated prematurely to the SurfaceView.

When the animating loop starts we use our holder to lock the SurfaceView's canvas and obtain a canvas to which we can draw.
c = surfaceHolder.lockCanvas(null);

After finishing the draw to the canvas we can alert the SurfaceView we are done and unlock the canvas.

surfaceHolder.unlockCanvasAndPost(c);

In context, it looks like this:
while (threadRunning) {
 Canvas c = null;
 c = new Canvas();
 try {
  c = surfaceHolder.lockCanvas(null);
  synchronized (surfaceHolder) {
   updateLocations();
   doDraw(c);
  }
 } finally {
  if (c != null) { 
   surfaceHolder.unlockCanvasAndPost(c);
  }
 }
}

The animation is handled by this thread which runs a loop. Each iteration of this loop detects the time elapsed since last call and uses this to calculate the Balls' positions. I won't explain the way the balls are updated, they use basic high school physics, and instead let's focus on the canvas. It's important to note that the canvas will retain previous drawings, so our first call in onDraw is to wipe it by making it entirely black. The still logo is then drawn and provided the Bitmap to draw, the (x,y) location to draw at, and a Paint which can apply additional effects.

private void doDraw(Canvas canvas) {
  // Clear canvas
  canvas.drawColor(Color.BLACK);

  // Draw the background (Warning! assumes screen > img)
  canvas.drawBitmap(backdropImage,
   (screenX - backdropImage.getWidth()) / 2,
   (screenY - backdropImage.getHeight()) / 2, null);

  drawFallingObjects(canvas);
 }


With the provided project you will be able to tweak the objects on screen, create new controls, and play around with the physics. This should be the basics you need to get started. For those interested, here's the APK.

Friday, January 4, 2013

Reachability Notifications with RestKit v0.10.x

By Michael Cohn

Proactively reacting to an application's changes in network connectivity can make or break a user's experience.  Using Reachability notifications can help accomplish this goal by monitoring the network state of your device.  Here is how to register a class as an observer of RestKit's reachability notifications and how the listening class can react to changes in the application's network status.  As always, reading through the documentation of RestKit and NSNotificationsCenter will provide an in-depth look at each's functionality and capabilities.  Please note that the following methods and code snippets will work for RestKit v0.10.x and not v0.20.   

To implement reachability notifications for RestKit in iOS, we need to interact with the RestKit API and NSNotificationsCenter.  RestKit is an iOS framework that provides, among other features, a "high level HTTP request / response system."  We can use Apple's NSNotificationsCenter to perform certain actions/methods when a given event occurs.  NSNotifications provides a lot of utility across classes in an application as one class can be notified of events in another class.

To start, you need to create an observer of the RKReachabilityDidChangeNotification, which is a notification posted when reachability changes.  The code snippet below assumes that your class has it's own instance of a RestKit service using an RKObjectManager.  It will add the calling class as an observer of a RKReachabilityDidChangeNotification and will call the networkReachabilityDidChange: selector.
[[NSNotificationCenter defaultCenter] 
       addObserver:self 
          selector:@selector(networkReachabilityDidChange:) 
              name:RKReachabilityDidChangeNotification 
            object:self.restKitService.objectManager.client.reachabilityObserver];
Many projects utilize a shared instance of a RestKit's RKObjectManager which is typically used when all network calls have the same base URL.  Depending on where you add the notification observer, how you want to set up your observer, and your RestKit implementation, you may need to change some of the parameters above.

Now, we need to create the networkReachabilityDidChange: method we referenced above.  In this case, the calling class was a ViewController, allowing that ViewController to tell the view what to display depending on the current reachability status.  The ViewController could also communicate with any of the model classes to call certain methods depending on connectivity changes.  The method below will cast the notification as an RKReachabilityObserver and then determine its network status, using definitions from the RKReachabilityObserver class.
- (void)networkReachabilityDidChange:(NSNotification *)notification {
    RKReachabilityObserver* reachabilityObserver = (RKReachabilityObserver *) [notification object];
    RKReachabilityNetworkStatus myNetworkStatus = [reachabilityObserver networkStatus];
    if (RKReachabilityIndeterminate == myNetworkStatus || RKReachabilityNotReachable == myNetworkStatus) {
         //The network is unreachable or the network reachability status is unknown.
    } else if (RKReachabilityReachableViaWiFi == myNetworkStatus) {
         //You are connected via WiFi
    } else if (RKReachabilityReachableViaWWAN == myNetworkStatus) {
         //You are connection via a Wireless Wide Area Network (like 3G or Edge)
    } else if (RKReachabilityNotReachable == myNetworkStatus) {
         //The network is unreachable
    }
}


As is the case with any NSNotificationCenter observer pre-iOS6, you should remove your class as an observer when your view unloads.  In your viewDidUnload method, you should call:
[[NSNotificationCenter defaultCenter] removeObserver:self];

You can additionally choose to remove/add notifications in other view response methods, such as viewDidAppear and viewDidDisappear.  You can explicitly remove the observer for this notification while keeping other notifications for the class active by using the line below:
[[NSNotificationCenter defaultCenter] 
         removeObserver:self 
                   name:RKReachabilityDidChangeNotification 
                 object:self.restKitService.objectManager.client.reachabilityObserver];
This way, you can control if your class will receive any RKReachabilityNotifications when it is off-screen or restrict your observer to listening for notifications when on screen.

What benefits have you found by implementing reachability notifications with RestKit?

Wednesday, December 12, 2012

Handling AJAX Calls on Web Views

By AJ Leeds & Karthik Devulapally:  

Successful mobile development depends on your ability to be adaptive—
especially when developing hybrid apps. A prime example of this is the strange
issue we encountered when building our hybrid apps on iOS and Android
platforms. The web pages we were trying to load use AJAX. As a result, several
of the web view delegate methods were not being called. To efficiently handle
these events on the apps the solution was to inject JavaScript.

We injected the JavaScript, combined with a JavaScript bridge/interface, and the
native methods (iOS and Android) could be accessed. For iOS applications, we
used TGJSBridge, and for Android applications, we used JavaScript interface.
Here are the solutions for both iOS and Android applications:

iOS Solution

TGJSBridge library acts as a bridge between JavaScript and the Objective C,
where you can send messages from JavaScript to native method, and vice versa.
The JavaScript below helps to detect when the AJAX call starts and complete.
It sends a notification to TGJSBridge. TGJSBridge then calls its own delegate
method, where we can handle AJAX events. Our own JavaScript in the app
bundle is ajax_handler.js.

Here is our implementation:
ajax_handler.js
 $(document).ajaxStart( function() {  
 jsBridge.postNotification('ajax_handler',{message:'start'});  
            });  
 $(document).ajaxComplete( function() {          
  jsBridge.postNotification('ajax_handler',{message:'complete'});  
             });  
When the webview starts loading the webpage inject ajax_handler.js:
 jsHandler = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"ajax_handler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil];  
   [webView stringByEvaluatingJavaScriptFromString:jsHandler];  
Create TGJSBridge jsbridge and assign it to the web view delegate:
 TGJSBridge *jsbridge=[TGJSBridge jsBridgeWithDelegate:self];  
 webView.delegate=jsbridge;  
Next, implement the TGJSBridge’s delegate method and handle your AJAX
event:
 - (void)jsBridge:(TGJSBridge *)bridge didReceivedNotificationName:(NSString *)name userInfo:(NSDictionary *)userInfo fromWebView:(UIWebView *)webview  
 {  
        if ([name isEqual:@"ajax_handler"]) {  
     if ([[userInfo objectForKey:@"message"] isEqual:@"start"]) {  
       //handle your logic  
                NSLog(@”AJAX start”);  
     }  
     else if ([[userInfo objectForKey:@"message"] isEqual:@"complete"]) {  
       //handle your logic  
                NSLog(@”AJAX Complete”);  
     }  
   }  
 }   
Android Solution:

Implementing the JavaScript for Android is fairly simple. Here is what’s needed to
invoke an Android method from a web view. Using the JQuery methods ajaxStart
and ajaxComplete, we can call a native method to let us know when the AJAX is
starting and when it’s finished.

First we need a web view:
 WebView view = new WebView();  
We need to enable Javascript for that webview:
 WebSettings settings = view.getSettings();  
 settings.setJavaScriptEnabled(true);  
Next, we need to tell the web view to point to our JavaScript interface:
 view.addJavascriptInterface(new javascriptInterface(), "javascriptInterface");  
Override the UrlClient's onPageFinished and add the Javascript.
 view.setWebViewClient(new WebViewClient(){  
  @Override  
    public void onPageFinished(WebView view, String url) {  
  view.loadUrl("javascript:$(document).ajaxStart(function (event, request, settings) { javascriptInterface.ajaxBegin(); });");   
      view.loadUrl("javascript:$(document).ajaxComplete(function (event, request, settings) { javascriptInterface.ajaxFinish(); });");  
    }  
 });  
The Javascript interface:
 public class javascriptInterface(){  
    public void ajaxBegin(){  
      Toast.makeText(getApplicationContext(), "AJAX Start",  Toast.LENGTH_SHORT).show();  
    }  
    public void ajaxFinish(){  
      Toast.makeText(getApplicationContext(), "AJAX Finish", Toast.LENGTH_SHORT).show();  
    }  
 }  
That's it. Now, the toast message will display when the first AJAX call is made and another one when the last AJAX call is complete.