I created and published my first Android app: an initiative tracker for pen-and-paper roleplaying games. If you have an Android tablet, you can download it off Google Play and try it out. As opposed to my earlier attempts, I now used Xamarin with XAML and PostSharp (the product we make). In this article, I walk through my experiences.

Soothsilver Initiative Tracker

The app looks like this:

In pen-and-paper roleplaying games, such as Dungeons & Dragons, in combat, players take turns in the order of initiative: a number based on what each player rolls on a die. Because each player takes several turns in a combat, and the order of players is different each combat, playgroups make use of an initiative tracker to keep track of whose turn it is, who goes next and so on.

As you might expect, there are many initiative trackers on Google Play already. I know because I tried them all — but not one that matched all of my requirements exactly, so, of course, I rolled out my own :).

And it worked well — I made it within half a day (though the subsequent process of publishing it on Google Play took about as many hours again) — and our playgroup is still using it four months later.

I should mention that is entirely my own personal hobby project — I host in on my own GitHub (give me a star) and PostSharp as a company certainly does not provide support (but feel free to ask me). We don't even officially support Android at the moment, though as evidenced by this app, it generally works, including debugging.

Using Xamarin with XAML

I made some attempts at Android development before, using Java/Kotlin and native Android API, but I often got stuck and never created anything worth publishing. That's why this time I tried if maybe using C#/.NET would work better.

It did, curiously, but it still wasn't close to desktop development. You know how when you're developing a desktop application and you type in some code and press F5 and it immediately just runs? And how when you're developing a mobile application and you need to install several prerequisites and check manifests and set configuration options? That's still there, even when you're using Xamarin.

There's also the fact that everything is slower: the designer, the build, the transfer to your device or to the emulator, even the distribution process and upload to Google Play. I think if I had more experience, it would go faster, but I still found the entire process more complicated. Part of the reason why I don't create mobile games.

The user interface design, at least, was more familiar. I used Xamarin Forms with XAML design files and the paradigm is very similar to UWP and WPF so I created my screens quickly. Visual Studio now even supports live updates: I modified my XAML, saved the file, and the form on my device changed!

Of course, XAML also means INotifyPropertyChanged, the XAML solution to data binding.

INotifyPropertyChanged

I've used INotifyPropertyChanged in several projects so far and I still don't quite like it.

Personally, as far as binding values to user interface elements goes, my number one favorite approach is the low-level draw loop (as in XNA/MonoGame): you ask your model sixty times a second what are you supposed to draw and you draw that. That isn't an option in complex UI frameworks.

My next favorite approach is the one taken by JavaFX: you use special smart properties (wrappers) in your model and bind them among themselves. I find that clearer, less boilerplatey, but it's getting complex, especially with the larger elements like list views.

Regardless, Xamarin has XAML, and XAML means MVVM and INotifyPropertyChanged. Fortunately, this time, I have PostSharp.

PostSharp auto-implements everything about INotifyPropertyChanged. With it, I was able to reduce the interacting part of my model to this:

[NotifyPropertyChanged]
[Recordable]
public class Creature : INotifyPropertyChanged
{
  public string Name { get; [ThenSave] set; }
  public bool Friendly { get; set; }
  public int Initiative { get; set; }

  [SafeForDependencyAnalysis]
  public bool Active
  {
    get { return MainPage.Instance.Encounter.ActiveCreature == this; }
  }

  [SafeForDependencyAnalysis]
  public Xamarin.Forms.Color BackgroundColor
  {
    get
    {
      if (Friendly) { return Color.PaleGreen; } else { return Color.LightSalmon; }
    }
  }
  ...
}

PostSharp's solution to INotifyPropertyChanges is magic so I'll walk you through what's happening here.

The [NotifyPropertyChanged] attribute is a PostSharp attribute and it means "whenever any property of this class changes, raise a PropertyChanged event for that property". For the properties Name, Friendly and Initiative, it means the event is raised after some code uses their setter.

But what about the properties Active and BackgroundColor which are getter-only?

The property MainPage.Instance.Encounter.ActiveCreature is referenced via a static property (MainPage.Instance) so there's no way to react to its change from within the class Creature. What I do in this app is that I use OnPropertyChanged to manually raise the PropertyChanged event for the property Active for all creatures whenever the active creature changes. PostSharp can't help here because of the unfortunate way in which I set this up. What I should have done instead is add to the Creature class a reference to its parent Encounter, which removes the need to refer to a static property.

For BackgroundColor, the situation is different. The property's value depends only on another property of the same creature: whether it's friendly or not. PostSharp can determine this (it reads the IL code of BackgroundColor's getter and sees that it references the property Friendly) and makes it so that whenever the value of Friendly changes, a PropertyChanged event is raised also for BackgroundColor — and I didn't need to write any code.

The [SafeForDependencyAnalysis] attribute in my code sample is a signal to PostSharp that even though the code within uses static properties, it's okay and PostSharp shouldn't emit a warning. PostSharp normally emits the warning to tell the user "hey, I can't automatically raise events in response to changes of static properties; are you sure you're handling that yourself?". It's necessary even for BackgroundColor because it refers to Color.PaleGreen and Color.LightSalmon, and those aren't constants, they're merely static fields. (They are readonly, so maybe the warning isn't really necessary and we could look into suppressing it.)

Other uses of PostSharp

You may have noticed a couple of extra attributes in my code sample.

Those weren't strictly necessary but since I was using PostSharp already, I figured, why not go all the way.

[ThenSave] is a method boundary aspect I created. It means, "after this method completes, save all creatures on disk so they're not lost when the user closes the app". I could have done this instead:

private string _name;
public string Name { get => _name; set { _name = value; ThenSave.SaveEverything(); } }

Which would do the same thing, but I feel like the solution with the [ThenSave] aspect is prettier and if I needed it for more than one property, it would also help save lines of code.

The last attribute I didn't talk about is [Recordable]. This one is a built-in PostSharp attribute which means "I remember everything that happens to me; you can use undo/redo."

Normally, when you implement undo/redo, for each possible action the user can take, you create a triplet: what happens when you take the action, what happens when you undo it, and what happens when you redo it.

PostSharp's undo/redo makes use of the fact that most of the time, everything that these actions do is just changing the values of some properties. So, whenever you change the value of some properties of a [Recordable] object, the object remembers it and it's added to the undo stack which I exposed with the Undo and Redo button on screen.

I also marked the list of all creatures (the class Encounter) as [Recordable] as well. That way, if I first change the name of one creature in the encounter and then another, both changes are made to the same undo stack and can be undone in turn by the same button.

I suppose the app didn't really need an undo/redo functionality. Most initiative trackers on Google Play don't have one. But with PostSharp, it cost me very little to add it and it actually proved useful, especially since typing is more time-consuming on tablets so undoing a mistaken name change rather than retyping the original name helps speed up gameplay.

Publishing on Google Play

I didn't technically need to publish the game: I mostly wanted it for myself and the build that Visual Studio placed on my tablet was good enough. But publishing seemed simple enough and maybe in the future I'll want to create a true game and this could be a trial run.

It wasn't actually all that simple. The Google Play Console, the online app that you use to upload and manage your Google Play games, has about twenty pages that you can fill in and about half of them are mandatory.

Uploading the binary itself failed several times for me when I checked the wrong checkboxes when creating the distribution build in Visual Studio. Visual Studio has a feature that allows you to upload your build to the Play Console from Visual Studio, but it broke at some point in the past and doesn't seem to work anymore. Still, for every problem I faced, there was a forum thread somewhere on the internet that pointed me in the right direction.

The cost of creating a Google developer account was just $25 and it's a one-time fee that I don't need to pay for future apps.

Whenever I made a change to the game data, either uploading a new build or even fixing a typo in the store listing description, it required a new verification from Google, which seems to be manual at least the first time around: it took about a week to get my first version approved (but subsequent approvals were faster). I didn't actually talk or chat with a human at any point.

Overall, it was a good experience, though I recommend that you do this on a powerful computer (because creating the distribution build is slow) and with good internet (because the distribution package for Google Play is large and you need to upload it).

Conclusion

I'm happy with how my app turned out.

I used the free Essentials edition of PostSharp (more than enough for a little app like this). As an employee, I had access to the full Ultimate edition but I didn't need it. (You may also be eligible for a free Ultimate license.)

If I didn't use PostSharp, I certainly wouldn't have implemented Undo/Redo and my Encounter and Creature classes would increase in size and complexity a bit but with a bit of refactoring, it would still be quite manageable, I think. That said, XAML is a technology where PostSharp shines and I certainly prefer the current code than what it would have been without PostSharp.

As one of the core contributors to a compiler for a new language, I often find myself needing to explain new concepts and ideas to other developers. Over time, I've gradually found an approach that tends to work. First, where does the concept fit on the language feature or paradigm map? Second, what is the problem that it is
aimed at, and how are other perhaps more familiar solutions weak? And then -- with that critical foundation laid -- what does the new concept actually do to help?

Recently, I was asked to speak about Aspect Oriented Programming at .Net Community Day in Sweden. I've known about AOP for years and discussed it with developers before, but this was a nice opportunity for me to
spend a while thinking about how best to go about explaining it. So I set about coming up with the AOP answers for my three questions.

The paradigm jigsaw

There are a bunch of titles that we tend to put before the word "programming". "Object Oriented Programming", "Functional Programming", "Declarative Programming" and "Generic Programming" are just some examples. They're all paradigms, but the amount they try to answer differs. The first three I listed -- OOP, FP and DP -- will
happily jostle for pride of place in a language, seeking to be its "core paradigm", and posing a challenge to language designers who see value in all of them. Of course, some languages do decide to just follow a single paradigm: regexes are happily declarative, and Java has admitted little into the language that isn't squarely inside the OO box. However, most of the popular and expressive general purpose languages out there today embrace multiple of these "core paradigms", recognizing that solving every programming task with a single paradigm is like doing every garden task with a lawnmower.

At the same time, there are paradigms that simply seek to deal with a very particular set of issues. Generic programming is one of them: it deals with the situations where we want to use the same piece of code with different types, in a strongly typed way. This idea actually cross-cuts the "core paradigms"; generics are simply
a case of parametric polymorphism, which one finds in functional languages.

The purpose of Aspect-Oriented Programming

This is the kind of place that AOP sits. It's not pitching itself as a successor to -- or even a competitor of -- any of our familiar core paradigms. Instead, it takes a problem and proposes an approach for solving it. So what's the problem?

In any complex code base, there are cross-cutting concerns -- things that we need to do in many places that are incidental to the core logic. For example, logging and exception handling and reporting are generally things that a piece of code does in addition to the task that it really exists to perform. Of course, we factor as much of
the logging and reporting code out as we can, but generally we find ourselves doomed to repeat similar-looking bits of cross-cutting logic in many places. Even if it's just a call to the logger, or a catch block, it ends up duplicated.

Duplicated code is generally a bad sign. For one, it inhibits future refactoring; if we decide to switch logging library, this is now a change in many places. Since we have mentioned the logging library in many places, we have many pieces of our code that are closely coupled to it -- something that goes against our general preference for code that is loosely coupled. We also run into challenges when we want to install new cross-cutting concerns into our software -- there's so many places to change!

Aspect Oriented Programming is aimed at these kinds of challenges. It introduces the concept of join points -- places in our code that we could add some functionality -- and advice -- the functionality that we want to incorporate. It provides a mechanism to write the cross-cutting functionality in one place and have it "inserted" into the join points.

Managing complexity

A common reaction is, "wow, magical", but if we cast our eyes back over programming history, it's really not so surprising. Once upon a time there was just assemblers. Repeating regular sequences of instructions was tiring, so macro systems were created. These "magically" got substituted for a sequence of instructions, with some parametrization thrown in to make them more powerful. A little further on, named and callable subroutines allowed for real re-use of code. We raised the abstraction bar: "you don't have to worry about what this bit of code does, just call it like this". Then came OO. Here things got really magical: invoking one of these method things leaves you with no idea what bit of code is going to be called! It could come from that familiar bit of code you wrote yesterday, or it could come from a subclass that's going to be written in 10 years time.

Over the years, we've evolved ways to manage complexity in software, many of them hanging off increasingly non-linear or loosely coupled flow of control. We've coped with the increasing complexity in our paradigms and programming style, because they more than pay themselves back by decreasing complexity in the software we produce using them. AOP's concept of join points and advice is giving us a little more conceptual overhead in exchange for a more maintainable and less coupled implementation of our cross-cutting concerns.

Looking to the future, I think it's important to remember that where we are with any paradigm today is almost certainly some way from the ideal. We've learned a lot about object oriented programming over the decades that it has existed, and continue to do so. Multiple inheritance has generally been marked down as a bad idea, and the
emergence of traits in Smalltalk (also known as roles in Perl 6) has made some -- myself included -- question whether we'd be better off dropping inheritance altogether in favor of flattening composition.

AOP has only had 15 years of lessons learned so far, and I've no doubt we've got a long road to walk from here. However, that being the case shouldn't stop us from embracing AOP today. After all, the ongoing journey of the object oriented paradigm isn't something that stops us from using it. The critical question is, "does this help me deliver higher quality, more maintainable software" -- and I think there are a bunch of use cases where today's implementations of AOP help us to do so.

About The Author
Jonathan WorthingtonJonathan Worthington is an architect and programming mentor at Edument. He works to help development teams improve their software architecture and work more efficiently, following best practices. He is also one of the core developers of the Rakudo Perl 6 compiler, where his work focuses on the implementation of object oriented language features and the type system. In his free time, he enjoys hiking in the mountains, good beer and curry.

In my response to Anders Hejlsberg spreading FUD about aspect-oriented programming, I mentioned the common confusion that Aspect-Oriented Programming (AOP) and Dependency Injection (DI) are competing concepts. In this post, I will further clarify the differences and similarities between AOP and DI.

The timing seems perfect, because Dino Esposito just published the article: Aspect-Oriented Programming, Interception and Unity 2.0 in the December 2010 issue of MSDN Magazine. This is a great article and I highly recommend anyone involved in .NET development to read it. Like most dependency-injection frameworks, and several general frameworks (WCF, ASP.NET MVC), Unity offers an AOP-like feature: interceptors.

What is Dependency Injection?

Dependency Injection is a design pattern that strives to reduce explicit dependencies between components.

One of the benefits of reducing dependencies (moving from a tightly coupled architecture to a loosely coupled architecture) is the reduction in the level of awareness components have of each other, thereby achieving a better separation of concerns by implementing the “program to an interface, not to an implementation” design principle.

A common misinterpretation of this design principle among C# and Java developers is that clients should consume interfaces (the thing you declare with the interface keyword) instead of classes. I prefer the following wording: “program to a contract, not to an implementation”. The contract of a class is composed of its public members, augmented by their documentation (plus their formal preconditions, post-conditions and invariants, if applicable). To be even more precise: “program to a documentation, not to an implementation”. So if your aim is just a better separation of concerns, you don’t really need interfaces, you just need the public, internal, protected and private keywords. It’s important to note that in object-oriented design, interfaces are not the silver bullet. Not all framework designers follow the same philosophy: the Java class library relies more on interfaces than that of .NET, probably because .NET designers had negative experience with the all-interface approach of COM.

Programming to an interface (instead of a class) is useful when your component has to talk to many implementations of the interface. There are innumerable cases where this is useful (after all, we all want our architecture to be extensible), but let’s face it: in as many cases, when our component needs to talk to another, we know perfectly well which implementation we have in mind, and there will never be a second implementation running side-by-side. So why use an interface here?

There are two cases when you want to program to an interface even if you know you’ll always have a single implementation:

  1. You depend on a component that has not been delivered yet and need to start programming – and, more importantly, testing your code – right now. You need to simulate (mock) this component until it is delivered, only for the purpose of testing.
  2. You depend on a component that has a persistent state (such as a database), real-world effect (such as a credit card processing system) or simply depend on a slow or unreliable resource (web service). You need to substitute these components with an implementation of your own, only for the purpose of testing.

In these situations (which all happen to be related to testing), it’s good that components are not wired together in source code – even if we know how they will be wired together in the final setup. So how do we wire these components together? This is where Dependency Injection comes into play.

With the DI design pattern, you instruct a “container” how the objects should be wired together, and you ask the container to wire the objects. Indeed, most of the time, you don’t create new objects using the class constructor, but using a factory method of the container. The container would figure out which implementation you need to be wired to, and would return it to you.

Aspect-Oriented Programming

Dependency injection addresses the problem of wiring loosely-coupled components together. Aspect-oriented programming (AOP) solves a very different issue: taking a reality where some features (such as transaction handling or auditing) affect virtually all business requirements, and expressing this complex reality in a compact way, with minimal duplication of code (DRY principle). When we think of auditing, we want to look in a single source file. When we see a piece of code related to customer management, we don’t want to see auditing code. As you know, this is impossible to achieve with plain object-oriented programming, and that’s why aspect-oriented programming was invented.

Aspect-oriented programming allows you to specify an implementation pattern (using source code, not natural language) into a so-called aspect, and to apply the aspect to base code, typically to business or UI code.

 

Similarities and Differences between DI and AOP

There are some similarities in the objectives of DI and AOP:

  • Both achieve a loosely coupled architecture.
  • Both achieve a better separation of concerns.
  • Both offload some concerns from the base code.

However, DI and AOP differ significantly in situations where they are found to be useful:

  • DI is good when you have a dependency on a component, you just don’t know to which implementation.
  • AOP is good when you need to apply a common behavior to a large number of elements of code. The target code is not necessarily dependent on this behavior to be applied.

Dynamic Proxies

How did dependency injection ever become associated with aspect-oriented programming? It’s simply that the DI pattern makes it easy to add behaviors to components. Here’s how: when you ask a dependency from the container, you expect to receive an implementation of an interface. You can probably guess which implementation you will receive, but since you play the game, you just program to the interface. And you’re right. If you ask the container to add a behavior (for instance tracing) to the component, you will not receive the component itself; instead, you will receive a dynamic proxy. The dynamic proxy stands between your code and the component, and applies the behaviors you added to the component.

Because DI frameworks have the ability to put behaviors between the client and the implementation of a component, DI has been identified as one of the technologies able to deliver AOP.

There are two technologies that can deliver dynamic proxies: dynamic code generation (using System.Reflection.Emit, typically), and remoting proxies (see RealProxy).

Please read Dino Esposito’s article in MSDN Magazine for details about dynamic proxies.    

Proxy-Based AOP: The Good

What I love about the proxy-based approach is how AOP blends into the DI concept. DI lets you configure how the container should build the components by injecting dependencies, setting properties and calling initialization methods – you can also inject aspects at the interface of components. You can configure aspects just as other dependencies in an XML file or using C# code, just as if the issue of building and assembling components were unified.

The ability to add aspects just by changing a configuration file may prove very useful in production. Suppose there’s some issue somewhere and you want to trace all accesses to a specific component. You can do that without recompiling the application. This may be a decisive advantage in formal environments, where it can take months to go from a bug report to the deployment of a fix.

Proxy-Based AOP: The Bad

Proxy-based AOP, as implemented by DI frameworks, has serious limitations:

  • It only works on the surface of components, exposed as an interface. It does not work for all methods that are internal to the component, whether public or private, static or instance. Remember that a component is an application part, and generally includes several classes.
  • It only works when the client code got a reference of the component from the container. Aspects will not be applied if the component invokes itself, or if the component is invoked without the intermediary of the container. This can be seriously misleading!
  • Since aspects are applied at runtime, there is no possibility for build-time verification. Build-time AOP frameworks such as PostSharp will emit compilation errors if the aspect is used incorrectly, and will even provide the aspect developer with different ways to verify, at build time, that the aspect has been used in a meaningful way (for instance, don’t add a caching aspect to a method that returns a stream, or to a method that already has a security aspect).
  • It is difficult to figure out (a) which aspects are applied to the piece of code you’re working on and (b) to which pieces of code the aspect you’re working on has been applied. Full frameworks such as PostSharp or AspectJ can display this information inside the IDE, substantially improving the understandability of source code.
  • Run-time AOP has higher runtime overhead than build-time frameworks. This may be of minor importance if you only apply aspects to coarsely-grained components, but just generating dynamic proxies has a significant cost if you have hundreds of classes.
  • Dynamic proxies are always a side feature of dependency injection framework and do not implement the full vision, even when technically feasible. They are mostly limited to method interception, which hardly compares to what AspectJ and PostSharp have to offer.

Proxy-Based AOP: The Ugly

There’s always a risk when a practice becomes mainstream: it starts being used just for the sake of itself, because it makes you feel safe. This is when a practice becomes a dogma.

It clearly happened to test-driven development, which suddenly imposed upon the community to write tests at meaningless levels of granularity. And thus so with dependency injection, which tends to be used to isolate classes from each other. Remember that dependency injection had been initially proposed to isolate components, i.e. parts of applications of rather coarse granularity. I am concerned that we are ‘forced’ (by social pressure) to write more complex applications just to meet testing ‘requirements’ that do not result in higher quality. Remember that unit testing is an instrument, not an objective. The ultimate objective is quality of your application during its whole lifetime.

Don’t get me wrong, I am not suggesting that you should not write unit tests. I am concerned that religiously following a practice may actually degrade the quality of your code.

The same issue exists with proxy-based AOP. If DI frameworks made you excited for the power of AOP, you may be tempted to restructure your code just to use more of this proxy-based stuff. Don’t. Adding aspects to the surface of components using proxies is simple and elegant. If you are making your code DI-friendly just because you need aspects, you are probably doing something wrong. The principal mantra of AOP is that you should not change your base code. If you are, you should probably look at a real AOP framework such as PostSharp or AspectJ.

Conclusion

Aspect-Oriented Programming and Dependency Injection are very different concepts, but there are limited cases where they fit well together. In these situations, using the AOP facility of a DI framework makes perfect sense. For other cases you have two options: abuse from dynamic proxies (a non-solution), or use of a dedicated AOP framework.

This is not just me, not just PostSharp, and not just .NET. The same dilemma hangs over Java programmers, who have to choose between the proxy-based Spring AOP and the build-time AspectJ (read the summary of  Ramnivas Laddad ‘s talk on this topic).

AOP and DI are not competing technologies. You can use both in the same project. What’s important is to understand what each technology was designed for, and to focus on the quality of your code.

Happy PostSharping!

-gael