Coping with Device Rotation in Xamarin.Android

You think that you have your Android application in a state where you can demo it to your supervisor when you accidentally rotate your device and the app crashes. We have all been there before and the good news is that the fix is usually pretty simple even if it can sometimes take awhile to find.

This has always been an issue for Android developers, but I have found that, due to the unique interaction between your C# classes and the corresponding Java objects, it seems to be a little more sensitive with Xamarin.Android apps. In this post, we will discuss what happens when you rotate your device and cover the different techniques that you might choose to use to manage your application state through device rotations as well as the ramifications of each of them.

Configuration Changes

So, what happens when you rotate your device?  Your device’s orientation is considered to be a part of the configuration of your application and, by default, Android will restart your Activity whenever it detects a change to the configuration.  At first glance, this seems like a pretty heavy-handed approach to handling device rotations, but there is a reason behind it. To understand that reason, we need to go back and review a few basics about Android app development.

Android, and by extension Xamarin.Android, has a way for you to create resources that only apply for a particular configuration value. Resources can be added to a folder that is tied to a configuration value, and those resources will only be used if that configuration value exists in the current setup. This is seen most often with drawables when you see the various drawable-mdpi or other drawable-*dpi folders so that you can provide images that are scaled appropriately for the resolution of the device. The Android system will choose the proper drawable folder and fall back to the base drawable folder at runtime whenever a given image is requested. This system of coupling resources to a given configuration goes beyond drawables to include all of the resource types, so layouts, strings, values, colors, etc. These can all be restricted using the same configuration qualifiers.

Device orientation is one of those configuration values that can be used to conditionally load different resources through the use of the “*-port” or “*-land” qualifiers.  Though, this means there could potentially be different resources used when viewing the app in landscape mode than in portrait mode, and that needs to be accounted for when the device rotates.  The Android team decided that restarting the Activity would be the best way to handle this so the resources could be reloaded with the new configuration values when the Activity restarts.

That might all sound fine, except that it can cause problems if you have not correctly accounted for this behavior in your code.  There are several approaches that you can take to deal with this, although the simplest approaches can also be the most restrictive to your app.

Prevent Orientation Changes

The first approach is also going to be the easiest to handle, but it is the most limiting, because it involves telling Android that your Activity only supports a single orientation. You can do this by setting the ScreenOrientation property of the ActivityAttribute on your Activity class to the orientation that you want to force your Activity to use.

[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class MyActivity : Activity
{
}

This approach has some obvious drawbacks, but if it works for your UX needs then it will be a simple way to ensure that an orientation change will not affect your application.

However, it is important to keep in mind that orientation changes are not the only configuration changes that might occur and cause your Activity to restart. For instance, a user can change their font/text size, which will also trigger your Activity to restart. So suppressing an orientation change is not a complete fix for any issues that your app would experience with restarting the Activity.

Manually Handling Configuration Changes

The second approach is a much more manual approach. It is possible to tell your app that you want to manually handle configuration changes in your code instead of restarting the Activity. To implement this approach you need to override the OnConfigurationChanged method in your Activity and manually process the new configuration object to do whatever needs to be done and then subscribe to specific configuration changes. Again, just like preventing an orientation change, this is as simple as tweaking your ActivityAttribute to specify which configuration changes will trigger calls to your method.

[Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
public class MyActivity : Activity
{
    public override void OnConfigurationChanged(Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);

        // perform actions to update your UI
    }
}

You might have noticed that I included the ScreenSize configuration change in my attribute. The reason is since API 13 (Honeycomb) the screen size also changes with the orientation, so you need to subscribe to both changes in order to keep your Activity from restarting.

This source code example will indeed prevent the configuration change from restarting your Activity, but it will not change which resources were used. If you were originally in portrait mode, then you would still be using your portrait resources even though you are now in landscape mode. If you want to also update your resources, then you will need to manually inflate the new resources and replace the old resources with them. However, since the Activity is not being restarted, that means the lifecycle events (OnCreate, OnResume etc.) are not executing, so any code that obtains references to views in your layout, or initializes values in your layout, will need to be performed again for your newly inflated views.

This can quickly become a lot of work if your UI is anything other than trivial and it is going to be prone to breaking if you forget a step or something changes in the future. As a result of that, I cannot recommend this approach unless your app does not utilizing orientation based resource overrides that would require inflation.

Retaining your Fragment Instance

If you are making use of fragments in your app, then they are also destroyed and recreated along with your Activity when a configuration change occurs. If your Activity class itself is just a thin wrapper around different fragments that actually contain most of your application state, then maybe it will be enough for you to persist your fragments and let the Activity still recreate itself. Like the previous examples, this is very simple to do since you just have to make one method call on your fragment to let Android know that the instance needs to be saved.

// from activity
var fragment = new MyFragment();
fragment.RetainInstance = true;

// OR in fragment
public override void OnCreate(Bundle bundle)
{
    RetainInstance = true;
}

Android will save the instance of your fragment and when it rebuilds your Activity it will reuse that fragment instance instead of creating a new one. This sounds pretty good, but if your fragment makes use of any resources that are orientation specific then you run into the exact same problem that you have with manually managing the orientation change. You will still need to inflate your new resources and initialize them manually, so other than saving your member variables for you this approach does not gain you a lot.

However, one place where this technique can be very useful is if you have some objects that may not serialize/deserialize well. As long as those objects do not retain references to the Context/Activity, such as other views or drawables, you can add those objects to a dummy fragment and retain that fragment. The fragment itself should just be a thin fragment that does not do anything else, and since there is no resource inflation happening in it you do not have to worry about reinflating anything.

Save and Restore your Application State

The Android designers knew that destroying and recreating the Activity was going to cause problems so they provided a mechanism for developers to save their state and then restore it after recreation.

Both the Activity and Fragment classes have a SaveInstanceState method that receives a Bundle where you can store serializable data. This method is called just prior to those objects being destroyed so the class states are still valid. You can use this bundle to store member variables from your class, or data that was retrieved and you do not want to have to retrieve it again, or anything else that is serializable.

protected override void OnSaveInstanceState(Bundle outState)
{
	base.OnSaveInstanceState(outState);

	outState.PutBoolean("someBoolean", someBoolean);
        outState.PutInt("someInt", someInt);

        // assume someObject is of type List<SomeModel>
        // I like to use Newtonsoft.Json to serialize to strings and back
        outState.PutString("someModels", JsonConvert.SerializeObject(someModels));
}

Activity classes have a RestoreInstanceState method that receives the Bundle containing the saved state and it has a chance to repopulate the class’s members with their data, although the same bundle is also passed to OnCreate so you could put your restore logic there as well depending on your need. RestoreInstanceState is called after OnStart, so if you need to initialize views before the Activity is started then you will want to use OnCreate. Keep in mind that the bundle in OnCreate can be null if the Activity is being launched so you will need to perform a null check.

protected override void OnCreate(Bundle savedInstanceState)
{
        base.OnCreate(savedInstanceState);

        // you must do a null check before referencing it here
        if (savedInstanceState != null)
        {
            someBoolean = savedInstanceState.GetBoolean("someBoolean", false);
            someInt = savedInstanceState.GetInt("someInt", 0);

            someModels = (IList<SomeModel>)JsonConvert.DeserializeObject<IList<SomeModel>>(savedInstanceState.GetString("someModels", null));
        }
}

protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
        base.OnRestoreInstanceState(savedInstanceState);

        // this method is only called when restoring state, so no need to do a null check
        someBoolean = savedInstanceState.GetBoolean("someBoolean", false);
        someInt = savedInstanceState.GetInt("someInt", 0);

        someModels = (IList<SomeModel>)JsonConvert.DeserializeObject<IList<SomeModel>>(savedInstanceState.GetString("someModels", null));
}

Fragments are a little different in that there are multiple methods that receive the Bundle with the saved state so you can restore your state in any of them. Generally speaking I would recommend using the OnActivityCreated method to restore your state since this happens prior to the UI views in your Fragment getting restored. If you needed to restore your state after the UI views being updated then you can use the OnViewStateRestored method.

public override void OnActivityCreated(Bundle savedInstanceState)
{
	base.OnActivityCreated(savedInstanceState);

	// load the data from the saved cache if it exists
	if (savedInstanceState != null)
	{
		someModels = (IList<SomeModel>)JsonConvert.DeserializeObject<IList<SomeModel>>(savedInstanceState.GetString("someModels", null));
	}
}

Android does not want you to have to do all of the work so it will automatically save the state of all views in your UI with IDs for you. Pieces of information like your scroll location are also saved and restored with the views in between OnActivityCreated and OnViewStateRestored, so if you want your scroll location to be correct then you will need to populate new adapters with your saved data and attach them to your lists in OnActivityCreated so that the scroll size is correct before Android sets the location.

One other piece that you will need to keep in mind is that Android will also attempt to restore your fragments and the back stack in the fragment manager. However, if your Activity keeps a reference to any of the fragments within it, you will need to save that fragment identifier so that Android can restore it with the correct instance. Fortunately they provide an easy way to do that.

protected override void OnSaveInstanceState(Bundle outState)
{
	base.OnSaveInstanceState(outState);

        // I am using the SupportFragmentManager here since I am using AppCompat with the support libraries.  This should also work with FragmentManager if you are not using AppCompat
        SupportFragmentManager.PutFragment(outState, "currentFragment", currentFragment);
}

protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
        currentFragment = SupportFragmentManager.GetFragment(savedInstanceState, "currentFragment") as MyFragment;
}

It might seem like a lot of work to save and restore your state, but all you really need to do is save off your Activity and Fragment’s instance variables and restore them at the appropriate moments. Most of the issues that I run into deal with forgetting to save/restore variables that I have added.

How does this affect async/await?

One other thing that you will need to keep in mind is that you will need to manage your async/await Tasks. You should try to implement your Tasks so that they can be cancelled if needed. If you have a pending Task when your Activity restarts, when the Task completes it will try to resume the original location which no longer exists. Ideally you should cancel any pending Tasks when the Activity or Fragment is stopped, or come up with an approach where the Task is running in some class instance that is not destroyed with the Activity.

Conclusion

As a developer, it can be annoying work to properly maintain your application’s state. If your application has a relatively simple UI that does not involve resource overrides, then you are probably going to be safe ignoring orientation changes. However, if your requirements change in the future, then that decision could give you a headache. This is one of those cases where it is probably easier to implement it properly from the beginning rather than ignoring it and refactoring it later once it has become an issue.

I hope that this article has helped you come to a better understanding of Android configuration changes and how you can take steps to make sure that your app is going to work properly when it is rotated.

Mobile App Services

Starting on a mobile app can be a daunting proposition.

Your stakeholders at Rex’s Gym really need this app to help drive customer retention, promote the business, and make payments a breeze.

Getting the development environment set up, learning a new language, understanding a wholly different API for screen layouts per-platform, having to go to the Apple Store and buy a Mac (which is the absolutely last thing you thought you would ever do).

Stress, headaches, pain, mayhem, churn! You haven’t even started yet! Then suddenly a manager says that you need:

  • Source control
  • bug tracking + task tracking
  • A reliable build system
    • Have all Alpha and Beta builds be installable to any mobile device within the organization
  • in-app usage tracking and phone-home crash logging
  • push notifications
  • OAuth2 based login to existing back-end systems
  • in-app payment + in-app recurring subscriptions
  • … and to top it off your boss wants an integrated SMS based text message e-mail gathering t-shirt promotion

You go out and look at the Apple, Google, and Microsoft references for all that stuff. Have a slight heart attack after scanning through hundreds of pages of doco. Go home. Have a beer. Lose some sleep. Go for a run. Then you stumble into this blog post that will give you pointers to make all that stuff easier and more reliable than if you had to do it all on your own.

Please note: Where possible I have tried to make service choices that have libraries and connectors that work across iOS (Obj-C / Swift), Android (Java), UWP / Windows 10 / Windows 10 Mobile (C# / XAML), and cross-platform mobile app solutions like Xamarin or Ionic / Cordova. As with all things, your mileage may vary.

 

Source Control Options – Just use Git, but hosted where?

Source control for projects now has many cloud based options. Most of them also integrate to task tracking and documentation services in diverse ways.

Depending on your preferences and cost profile, there are many awesome options for source code hosting. I have found that the options tend to settle down to 2:

A dark horse here would be to checkout Visual Studio Team System to host your Git repo.

Be sure to check out our other SuperDevelopment article regarding source control best practices for a great overview.

 

Bug / Task Tracking

For bug / task tracking there are many options. These options may be dependent on choices you make for source control hosting.

If you want industrial strength task management + work items integrated with your source control, then consider Atlassian + Bitbucket + Jira.

If you want something more lightweight, then go outside of the box and take a look at Pivotal TrackerTrello, or Github issues.

I think that the key here is to create an always available, fully transparent, one-stop-shop for all bug and task tracking. Things like e-mail, Slack, and other communication schemes tend to fall apart really quickly when the number of people working on a mobile project is greater than (or even sometimes equal to) 1.

 

Mobile App Build Server Options

You took the morning and you settled on source control and a good task tracking system. The first task you put in your tracking system is: Setup a build server.

As a corollary to setting up your build server, you would also really like options for continuous integration and continuous builds as you commit changes. You are just one person, and you have 15 stakeholders. The more you can automate, and the more builds you can get out there, the quicker you will solidify the decisions of those 15 stakeholders.

For mobile app build systems + full app CI you have a series of good options:

  • Bitrise – A fully cloud hosted build system that lets you snap together your build process. Has integrations to Github and Bitbucket. It even lets you build those pesky iOS projects because they handle a virtual in-the-cloud Mac to handle the Xcode command line stuff. With Bitrise you can be up and running in under a day.
  • Jenkins – An on premise solution. Only tackle this if you have a spare Mac laying around. Could take 4-5 days to rev up Jenkins and make it reliable. Plus ongoing maintenance. Overhead is worth it if need a fully on site solution.
    • The recent shipment of Blue Ocean by the Jenkins team really starts to make the Jenkins build system look like a great option.
  • Visual Studio Team System — If you have Microsoft Azure credits, then take a serious look at VSTS for mobile app building.

 

 

Special Note: Fastlane Toolset

You start revving up your builds, and start to notice some badness: The Apple Developer Portal has all these crazy requirements for certificates, provisioning profiles, app IDs, Ad-Hoc provision, App Store provision … Arrrgh!

Fastlane match is here to solve all that crazy cert, provisioning profile, app ID stuff by tooling up against these guidelines.

Fastlane also solves many other problems:

  • Pilot – Command line publishing of your iOS builds to iTunes Connect / TestFlight
  • Snapshot – Creates localized screenshots of your app which you can use for per-country app submission to the Apple App Store.
  • and so much more.

To document all the greatness that is Fastlane would take hundreds of pages. Suffice it to say, relax, lean back, and learn to love Fastlane.

 

Alpha / Beta Build Distribution – HockeyApp

While revving up your build system, you took a look at your next line item: Easy distribution of Alpha and Beta builds to any mobile device, usage tracking, and phone-home crash logs. In this realm, I really recommend:

  • HockeyApp – It really does it all.
    • Easy integration path as an app binary output destination with all of the above build systems.
    • On-device app which creates a mini-app store for distribution of your Alpha and Beta builds to your internal customers.
    • Easily integrated usage tracking and crash log reporting API for iOS, Android, Windows, and Xamarin based applications.
      • You can even use all the usage tracking and crash log reporting for your shipping application, not just for Alpha and Beta builds.

Other app tracking services are out there, but the ‘one stop shop’ of HockeyApp, in addition to Microsoft backing the product, makes HockeyApp a very slick solution especially if you are in a hurry.

 

It has been a couple of days, and you have all your build infrastructure revved up. Your initial Xcode project is up in Git source control, the app is building automatically on every commit / push via Bitrise, all that provisioning profile / certificate stuff is on auto-pilot with Fastlane – match, and you even have your first ad-hoc build installing to your personal iPhone via the HockeyApp app. All is right with the world.

Now you tackle a couple of screens from your requirements, and meet your first sprint deliverable. Your stakeholders are amazed that you were able to deliver the app to their specific devices after only 2 weeks.

The new sprint comes up, and you look at some of those bigger items on that task list. The next task you know you need to tackle is push notifications.

 

Push Notifications – Urban Airship

IMHO the first place to go is Urban Airship.

There are other services out there, but nothing scales out and up with your business messaging needs quite like Urban Airship does.

In my experience, I was able to hand over a restricted role based login from Urban Airship to my primary stakeholders and watch as they created and sent push notifications out to the app with ease.

Urban Airship’s per-platform integration options are second-to-none as far as ease of app integration.

Everything may depend on your cost requirements especially as it relates to projected number of users and needed level of messaging.

It took a couple of days, but you now have Urban Airship integrated, a development messaging environment is now delivering push notifications to your app, and you are ready to tackle the next item.

Alternatives to Urban Airship for push notification handling include:

 

In-app OAuth2 Login

The customers login to the current web site using a series of web based OAuth2 login schemes against a custom back-end server. Your app has to integrate into those same login schemes. Even worse: They also want you to be able to handle login via Facebook, Google+, and Twitter.

Just to pile on, your stakeholders demand that you find a way to not ‘just embed a web view’ to do the primary OAuth2 based user login. It’s OK, they might understand you have to show a web view for Facebook, Google+, Twitter, and other social network pairing but they don’t want to see a web view for the primary app login. As much as possible your stakeholders want pure native views for all logins.

There are frameworks out there to help you do this, but they can seem scattered and hard to integrate per mobile platform per social network. Windows 10 / UWP especially seems very complicated as far as doing a native OAuth2 based login, getting back the user roles by cracking open a secure JWT, all without a web view.

There is a third-party service that may be able to help. In this case the service is Auth0 (pronounced Auth Zero). Auth0 provides a wrapper / helper depending on server login type as well as a full suite of per-mobile platform front end login API connectors.

The mobile app integration for Auth0 divides into 2 general schemes:

  • Lock — Auth0 presents all needed views, web views, and other login UI for you.
  • Client API — Allows you to code a fully native UI yourself and just passthrough username / password and other login configuration parameters via a pure API.

Worthy mention: Amazon Cognito.

 

Intermission

You are about 3-4 weeks in so far. You have major app screens up. Your boss loves the notifications, she even gets them on her Apple Watch. Your product managers are floored at the awesome login integration. You have already forgotten about all that build / signing / provisioning / app distribution stuff because all you do is commit, and the build pops out of HockeyApp automagically and installs to your internal test and stakeholder devices.

Well there was that whole crazy Ad-Hoc build headache with adding UDIDs of the designer’s main devices but Fastlane made that easy via register_devices

 

In-app Payment + In-app Subscription

Your stakeholders are getting itchy. They want $. They want to make sure that you are looking at in-app payment and in-app subscription schemes. Next sprint comes around, and you start to look around at options (I mean, you need to get $ too, right?).

Your business doesn’t have a payment system in place that you can easily integrate with. You start to sweat a little. Until you find Braintree Payments.

You look at the Braintree client list and realize that you have bought stuff through them and never even realized it.

You sign up for their sandbox. Do some preliminary app integration. The stakeholders are kinda ‘Meh.’ when it comes to a few issues. Then you go for the throat and show an in-app  Apple Pay integration with your sandbox. That demo just showed you buying a recurring membership to Rex’s Gym with your thumbprint. How is that not made of pure awesome!

You also looked around and found out that Urban Airship has a similar system.

 

T-shirt e-mail gathering promotion?

You pop your head up at 6PM on a Friday after an all day coding frenzy, go get a Diet Mountain Dew. Close your eyes. Stretch. Open your eyes. Wha… your product manager is dangling a t-shirt in front of your face.

It is a cool t-shirt. You are working for Rex’s Gym and the design is awesome.

Your product manager says she wants you to fully engineer a t-shirt promotion from within the app. The end user is going to text their e-mail address via SMS to a phone number, it is your job to receive the text, process the e-mail address out of the text, and send out an invite e-mail from Printfection that allows the user to get their t-shirt.

She hands you the number that receives the SMS messages, and the Printfection credentials, and tells you go get it done.

So you look around and realize that Printfection has an API. But the last thing you want to do is code up a whole bunch of the stuff in the app, or even on a hosted server, to hit that API and manage the whole workflow of this promotion.

It is 6PM. It is Friday. Code haze has entered your brain from the all day binge. A sunny weekend awaits you! Help!

So you look around some more and find Zapier.

Zapier lets you setup a ‘zap’ that fully automates the whole flow:

  • SMS is received
  • Scan SMS for e-mail address
  • Log e-mail address in a Google Sheet
  • Send Printfection invite to e-mail address.

… all of that with no code to create, maintain, or host.

Special thanks to Ben Peter of Zapier for his presentation at minnebar 11 for this one!

 

Worthy Mentions

Azure – iOS Developer Center – Can handle push notifications, single sign-on, and many other data handling scenarios.

Firebase – Owned by Google. Handles many back-end services, including push notifications, usage tracking / diagnostics, and much more.

 

C# vs. Swift – Iron Man vs. Captain America

In Captain America: Civil War we get to see the ultimate battle between Iron Man and Captain America.

It is a battle of simple gutty defense vs. smart weapons and flashy offense, humility vs. brashness, down in the dirt vs. up in the clouds.

To totally geek it up, the same kind of battle exists in the languages that software engineers use today and I believe this is especially true in the battle of C# vs. Swift.

Don’t worry, this really isn’t a versus type write up. If anything I seek to point out each language’s unique strengths, then show how software engineers can get into the right superhero mindset to really use those strengths, and be aware of the weaknesses, to create great solutions.

 

C# = Iron Man – Strong Flashy Offense

C# is truly the Iron Man in this comparison. It is amazing how much showy weaponry C# can bring to bear to solve problems.

  • Have a problem with your UI freezing up? Bring in Task<T> / async – await, and seamlessly refactor years old code to be fully asynchronous, even within native UIs where thread synchronization is key.
  • Have a super large dataset that you need to tame? Bring in IEnumerable<T> / yield return or Lazy<T> from the deferred execution realm.
  • Have a need to produce arrays and collections that are the result of super smart functional filtering? Bring in LINQ.
  • Need to do smart filtering of XML? Bring XDocument and its magic LINQ over XML powers.
  • Need to do JSON processing? Head on over to NuGet, reference Newtonsoft.JSON ,and get stable, powerful JSON serialize / deserialize behavior and be done in no time.
  • Need to hit a REST service with super specific HTTP header formatting and authentication? System.Net.Http has you covered.
  • Need a cross-platform way to retrieve data from remote sites + Model / View / View Model architecture? Check out ReactiveUI.
  • Need async but inline immediate responses to collection changes? Check out Rx.NET.
  • C# is strongly typed, but you can also use reflection and loosen that strong typing as needed.
  • C# can even be used to generate itself.

You can even do most the above across all platforms. Windows, Windows Mobile, Android, iOS, Linux servers, … C# has you covered, in any way, any time, any where.

There is every gadget and gizmo that you can bring in and bolt on to existing C# code to get your job done. Even the very oldest C# code from 2002 is still supported and easily transformed using Visual Studio, or Resharper tooling into something shiny and modern.

C# has all these weapons, but the lifetime of these weapons are sometimes mere seconds before they are replaced with the next version via NuGet. The masters of C#, just like Tony Stark, have no issue with throwing out just created stuff in favor of the next great thing.

C#’s weaknesses are the dreaded NullReferenceException and the indeterminate mutability of most data structures. C# is great at attacking problems, and hitting at the 90% of the solution in a lightning quick way. However, C# doesn’t play defense very well. If you go too fast too far with C# you can out run your air cover, leaving you vulnerable when attacked from the flanks by null members, timeout errors, weird data changes, unhandled exceptions, or not connected to network scenarios.

C# is a highly flexible, multi-weapon language that you can use to attack any problem.

Swift = Captain America – Strong Defense

Swift is the ultimate boots-on-the-ground and in-the-mud defensive language. In Swift you don’t solve problems by attacking them head on with whole armories of shiny weaponry, you hunker down, put your shield up, and start slogging up that hill one step at a time.

Every line of Swift code written requires the author to think of the worst case:

The inventors of Swift must have looked at the metrics of existing Objective-C iOS applications and realized that the number 1 and 2 problems were:

  • Coders not realizing that the data they are changing on one screen leads to changes in data on other screens.
  • App crashes due to trying to access the value behind a null pointer.

Defense was needed. The power of Captain America’s vibranium shield was needed, only this time wielded by coders to stop these major in-app issues.

Coding in Swift is highly defensive in nature. To see this in action take a look at Swift Optionalsif .. let syntax, and the class initialization rules. As you use them, Swift optionals will permeate your entire thinking as you rev up your data structures. Every variable you use and/or create needs to be immediately thought of in terms of optional vs. non-optional.

Within Swift the use of specific reference and value types allows you to defend against unwanted mutation to your data structures.

Each line of defensive code is one more brick piled on top of other bricks of defensive code. When done you end up with applications that resemble the Great Wall of China and are truly written for the worst case. This layered defensive code coordination leads to super solid software structure that can take a real beating when attacked by the invaders (or users) of the software.

When done solving the problem in Swift you have a beautiful shiny shield that can repulse almost any mutability or null data attack. Because you play so much defense in Swift, coding up solutions to things seems to take longer. In reality, you have taken all that defense that C# out ran and have incorporated it into the structure of the solution.

The constant nullability slog, coupled with the constant mutability slog, while coding in Swift leads the developer to wanting more weapons to go at problems. Constant defensive coding slog can lead to developer fatigue quite quickly. However, when the problem solution is achieved, the engineer can see that their defensive coding effort has been like using Captain America’s shield as their primary weapon.

With the future potential of Swift existing across platforms, it could mean more solidly crafted software across the board, from server side to mobile applications. The underlying thought process behind Swift is already starting to leak into other languages, especially in the area of nullability.

I know that Swift isn’t without its share of flashy bolt-on weapon systems. Comparing C# to Swift when it comes to third-party library support is like comparing Iron Man’s crazy spin laser and hand repulsors to any weapon Captain America has ever wielded (at least in the movies).

 

But who wins in the ultimate battle?

If you ask me, I think Captain America and Iron Man are both good guys who should be augmenting each other’s strengths and covering their corresponding weaknesses.  I bet the  *SPOILER* real big bad *SPOILER*  is hiding behind the scenes and making them battle it out.

As with all things in software engineering there is never a clear winner. There are drawbacks and advantages to the structure, approach, and capabilities of all languages and constructs. These drawbacks and advantages tend to fit or not fit for solutions to given problems.

Good ideas tend to bubble to the top (i.e. delayed execution, in-language async, nullability enforcement, mutability enforcement), whereas bad ideas tend to settle to the bottom (i.e. garbage collection in Objective-C).

Swift is so new, the in-language concepts so hardened, the community so outspoken and willing to move quickly, that the verdict is not yet out.

C# has been around so long, has so much weaponry, and is currently so incredibly flexible across even dynamic and functional concepts. There is no way C# doesn’t continue to flex with some of the core concepts surfacing from the Swift and Kotlin worlds.

Who knows, one day you just might see Iron Man wielding Captain America’s shield. Just like C# currently wields dynamic and functional constructs, C# could well start to take on deep nullability constructs as they exist in Swift.

At the end of the day, we all win as these 2 languages battle, take on, and wield the best parts of each other to surface great solutions to real software problems.

C# / .NET for Mobile Development: Worth a Second Look

Over the past few years I believe that Microsoft, and their Xamarin partners, have created a compelling, quick, stable, and rich ecosystem for native development across Android, iOS, and Windows 10. It is finally time for native app developers to double back and take a look at C# / .NET based code for their native app platform needs in iOS, Android, and Windows 10.

[Read more…]

Sencha Touch

Mobile applications are everywhere these days and the number of development frameworks geared towards mobile audiences is growing as well. This can make it difficult for us developers who have to spend valuable training time learning one or more of these frameworks in order to be able to do our jobs. Sencha Touch is one of these frameworks and it allows a developer to code in HTML, CSS, and Javascript, and then package up the application to run on different mobile devices. This article is intended to provide a general feel for what Sencha Touch is and what it does.
[Read more…]