JSON and the (A/B)rgonauts

argonauts
As far back as Robotlegs days, I’ve been wanting to drive my bindings from JSON. It would be cool to change the behavior of my app without requiring a recompile, just by editing a text file. And in these days of mobile apps, the utility of doing this could be greater than ever before.

Since this is now a feature in the works (on branch json-binding), let’s talk about a key way you might put this to use.

The basic paradigm

The new feature allows you to take a properly formatted blob of JSON and feed it to a binder. For example, some JSON like this…

[
    {
        "Bind":"strange.examples.strangerocks.game.IGameModel",
        "To":"strange.examples.strangerocks.game.GameModel",
        "Options":["ToSingleton", "CrossContext"]
    },
    {
        "Bind":"strange.examples.strangerocks.game.IGameConfig",
        "To":"strange.examples.strangerocks.game.GameConfig",
        "Options":["ToSingleton"]
    }
]

…can be loaded from a text file or server and fed into Strange like this.

//after I've loaded the JSON file...
injectionBinder.ConsumeBindings(injectionBindingJson);

Once consumed, your binder will implement these bindings as if they had been written out by the following code:

injectionBinder.Bind<IGameModel>().To<GameModel>()
    .ToSingleton().CrossContext();
injectionBinder.Bind<IGameConfig>().To<GameConfig>()
    .ToSingleton();

With this new feature, you can write most instructions you’d write in the Context, such as injections, View/Mediator bindings and Signal/Command bindings, but in JSON instead of in C#.

Side-track: a quick intro to A/B Testing

(If you’re already clear on what A/B testing is, you might want to jump to the next section.)

To my thinking, one of the best uses of runtime JSON bindings is A/B testing. A/B Testing is an analysis technique for tuning application or game features. You have an idea that some feature in your game could be better than it is, so you experiment. You segment your user base: some users will see the feature one way (the ‘A’ segment), others will see it a different way (the ‘B’ segment).

A simple example:

There’s a button you really want your player to click, maybe the entrance to your in-app store. Your UI designer says the button is in the wrong spot. OK. Test it.

Create a segment of users who see the button in the new spot (‘A’ segment) and a control group (‘B’ segment) who see it in the old way. Who goes into the store more? The ‘A’ group or the ‘B’ group? You can use an analytics tool like Unity Analytics to find out, and decide whether or not the UI designer was correct.

This technique removes a lot of the guesswork from understanding how your players behave.

The fault in our binaries

In the traditional approach to A/B testing, the app contacts a server which sends back some numbers/strings to express the terms of the test (in our example above, where to place the button). If the test is particularly radical, the server might return a completely different binary. That might be acceptable in a web app, but a different binary is impractical and usually against the terms of service on mobile and consoles. This means that for really powerful A/B tests, you need to release a new binary for each test…possibly even multiple binaries.

At this year’s GDC, one speaker told our audience that they don’t do A/B testing on iOS. Why? The release cycle through Apple’s App Store is too slow. Sure, a server can feed in a few numbers and strings, but their tests are too complex for that. They need to alter how the game runs, and they just can’t release new binaries fast enough to work effectively with iOS. So they test on Android. Needless to say, this pretty much surrenders any hope of understanding how their iOS market differs from their Android market; and it’s well understood that these two platforms differ in many important ways.

So what if you could run a battery of tests without releasing a new binary?

This is where I think JSON bindings become really useful. With a little foresight, I can include numerous permutations within a single binary, all ready to be bound together based on instructions from a server.

Example:

Hypothesis: The user will be more likely to make an in-app purchase if they receive a call to action when they fail at a level.

Test: Do users upgrade if presented with a screen directly after failing a level?

Segment ‘A’: (Test Group)

[
    {
        "Bind": "mygame.signals.LevelLostSignal",
        "To": "[mygame.commands.LevelCompleteCommand, 
                mygame.commands.PresentUpgradeOptionCommand]"
    }
]

Segment ‘B’ (control GROUP):

[
    {
        "Bind": "mygame.signals.LevelLostSignal",
        "To": "[mygame.commands.LevelCompleteCommand]"
    }
]

Example:

Hypothesis: The AI on level 7 is too hard.

Test: Which AI allows an acceptable number of players to beat level 7?

Segment ‘A’: (Test Group)

[
    {
        "Bind": "mygame.ai.IEnemyAI",
        "To": "mygame.ai.EasierLevel7EnemyAI"
    }
]

Segment ‘B’ (control GROUP):

[
    {
        "Bind": "mygame.ai.IEnemyAI",
        "To": "mygame.ai.Level7EnemyAI"
    }
]

Segment ‘C’ (A/B tests can be A/B/C/D/E…So this is another test group):

[
    {
        "Bind": "mygame.ai.IEnemyAI",
        "To": "mygame.ai.SuperEasyLevel7EnemyAI"
    }
]

As you can see from these two trivial examples, runtime JSON bindings open up the whole of your binding infrastructure for testing and tuning without the need to release a new binary. This isn’t a magic bullet, of course. You aren’t going to turn Pac-Man into Assassin’s Creed on the strength of a few binding changes. But the ability to broaden the scope of what you can consider testable, and even compose fundamentally new tests without a new release cycle, should put a little extra power into your hands.

When does JSON set sail?

The code is available today on the branch mentioned at the top. I’d love to have it tested and any bugs exposed before we make it officially a part of the next release of StrangeIoC.

Advertisements

Do you Strange?

Today’s post is just a quickie.

Alongside our rapidly developing next version of Strange, we’ve been working on an updated website. The new site contains two new community-oriented pages:

Strange Projects

This page will feature released projects that have utilized StrangeIoC. We’re encouraging you to submit anything you’ve built…a game or app, on web, mobile, standalone, etc, that shows how you are putting Strange through its paces.

Other resources

This page is part of our ‘Help’ section, and provides, alongside all our other documentation, links to code samples, tutorials, videos, and anything else that can help a developer learn and grow with StrangeIoC. If you’ve written a blog post, created a presentation, or done anything else that could help your fellow coders learn to do Strange things, we’d love to include it in our list.

Thanks friends. Keep it Strange!

A farewell to names

This past Saturday I woke up with a surprise. For some reason the answer to a problem that had lingered subconsciously for years inexplicably bubbled up fully formed into my head.

The name blame game

The problem was naming: specifically, named binding injections in Strange. Named bindings is a solution to an important problem, solved by our friends at Robotlegs. They knew that an application might need more than one implementation of an abstract class or interface, so when injecting they had to have a way to determine which concrete version to instantiate. To solve this, they used naming to differentiate one implementation from another. In Strange, it looks like this:

injectionBinder.Bind<IEnemyAI>().To<CrazyIvanAI>().ToName("Ivan");

This solved the problem, but in my view solved it rather inelegantly, because the client class that uses a named injection now needs to look like this:

[Inject("Ivan")]
public IEnemyAI aiModel { get; set; }

This is precisely the opposite of how dependency inversion is meant to work. The client is telling its  provider what it needs, instead of the other way around. That said, I had no better idea how to fix this, so it’s what we ended up using in Strange. That all changed with my flash of insight on Saturday.

Could naming, like the rest of binding, be inverted?

Not naming any names

So my mission was to supply injections to identical interfaces and abstract types without editing the consuming class. Which means what used to look like this:

public class EnemyMediatorOne
{
    [Inject("Ivan")]
    public IEnemyAI aiModel { get; set; }
}
public class EnemyMediatorTwo
{
    [Inject("George")]
    public IEnemyAI aiModel { get; set; }
}

Now needs to look like this:

public class EnemyMediatorOne
{
    [Inject]
    public IEnemyAI aiModel { get; set; }
}
public class EnemyMediatorTwo
{
    [Inject]
    public IEnemyAI aiModel { get; set; }
}

That latter example yields scarily similar injections, but there is one thing that obviously sets them apart: the classes in which they are defined. So we can use the client class as the identifier to separate one injection from another!

This leads us to a new InjectionBinding method: SupplyTo.

SupplyTo is an optional instruction in your injection binding that explicitly identifies a client class you want to have consume this injection.

Here’s an example:
(Note: there’s a bug — in WordPress I presume — that causes this example to render a bit oddly in some browsers. I got tired of trying to solve their issue. My apologies. I think the idea comes across. If you really need to see it correctly, it renders fine in Firefox.)

injectionBinder.Bind<IEnemyAI>()
    .To<BasicEnemy>()
injectionBinder.Bind<IEnemyAI>() 
    .To<BossEnemy>()
    .ToName("Boss") 
    .SupplyTo<RedBossMediator>() 
    .SupplyTo<BlueBossMediator>() 
    .SupplyTo<GreenBossMediator>();
injectionBinder.Bind<IEnemyAI>() 
    .To<BigBossEnemy>()
    .ToName("BigBoss")
    .SupplyTo<BigBossMediator>();

In the above example, we have three implementations of IEnemyAI:

  • BasicEnemy
  • BossEnemy
  • BigBossEnemy

By default, anyone who requests IEnemyAI receives an instance of BasicEnemy. But certain marked classes, such as RedBossMediator, receive a different class instance. And one class, BigBossMediator, receives its own special AI. The key point is that each mediator simply marks the interface for injection…no naming in the class is required.

public class StandardEnemyMediator
{
    [Inject]
    public IEnemyAI aiModel { get; set; }
}
public class RedBossMediator
{
    [Inject]
    public IEnemyAI aiModel { get; set; }
}
public class BigBossMediator
{
    [Inject]
    public IEnemyAI aiModel { get; set; }
}

The result is a much better form of inversion, and more flexible code (which is what we’re always after, right?

A couple things to call out from our example. First, note that we still name the binding itself, whenever there’s more than one key. This is important both for backwards compatibility and in order to retrieve the binding, should you ever need to. And see how we apply multiple SupplyTo’s in a chain. This makes it convenient to list any number of consumers for this injection.

Finally, I’ll mention that this change should be fully backwards compatible. So you don’t need to use it if you don’t want to. And you should be able to safely mix-and-match the new approach with the old one.

Naming the limitation

There is one important caveat to this model. Since we’re using the client class as the key, there’s no way to use this technique to inject two of the same interface/abstraction into the same client class. That’s a corner case, albeit an important one, in which you’ll still have to rely on the old-fashioned naming method.

The name of the branch

This work is now on the branch invert-names. If all checks out, we hope to release it as part of the next major release of the framework. Happy binding!

IoC solutions for Unity

This post is just a list of Inversion-of-Control/Dependency Injection solutions for Unity3D for anyone looking to compare. I can’t at this time validate how good any of them are (well, with the obvious exception).

This is a living list. If you know of any I’ve missed, please let me know.

StangeIoC

Strange is the open-source IoC framework I built and which is the main focus of this blog. It borrows heavily from previous OS projects Robotlegs and SwiftSuspenders.

http://strangeioc.github.io/strangeioc/

Robotlegs for C#

The Actionscript version of Robotlegs was foundational for StrangeIoC. In 2015, our friend prankard ported the framework to C#. Unsurprisingly, the framework will look very familiar to our user base.

https://github.com/robotlegs-sharp/robotlegs-sharp-framework/

Stiletto

A .NET port of Dagger, the lightweight Android dependency injector from Square.

https://github.com/paulcbetts/stiletto

Zenject

Zenject, like StrangeIoC, is an OS project with a focus on helping Unity developers write large, flexible code bases.

https://github.com/modesttree/Zenject

Sebastiano Mandalà

Sebastiano developed some early ideas on Injection containers for Unity. His work was inspirational for many projects that followed, Including StrangeIoC and Zenject.

http://blog.sebaslab.com/ioc-container-for-unity3d-part-1/

http://blog.sebaslab.com/ioc-container-for-unity3d-part-2/

Simple Injection by Kasper Mindra

http://blogs.unity3d.com/2014/05/07/dependency-injection-and-abstractions/

Simple IoC Container for Unity3d

http://www.codeproject.com/Articles/774606/Simple-IoC-Container-for-Unity-d

uFrame

uFrame is a paid MVVM framework available from the asset store.

http://invertgamestudios.com/home

Uniject

Uniject is an Open Source DI project with a heavy emphasis on creating/promoting testable code. Note that as of this writing this project has been dormant for 2 years.

https://github.com/banderous/Uniject

Inconspicious Framework

Inspired by Strange, the developer tells me. The main difference/selling point is integration with UniRx for type-safe commands/signals.

https://github.com/yuhe00/Inconspicuous.Framework

The Good, The Bad and The Strange

This is a presentation I gave awhile back, which I finally got around to recording. It explains the core principle of dependency inversion upon which Strange is based. It’s largely intended as an intro that explains why writing Singletons is such bad practice (and writing Factories only marginally better), and why injection is a better way to go.

Part 1 (theory)

Part 2 (practice)

I’m going to Unity!

Unity logo

Powered by Unity

As friends of Strange will know, things have been very quiet on the development front over the last eight months or so. The reason is that I’ve been engaged in building a new startup company which frankly had nothing whatsoever to do with Unity. All that is changing today.

The sad news is that my startup didn’t take off as quickly as we had planned or hoped. The good news is that this puts me back in the Unity game, and therefore back into StrangeIoC. Even better, I’m not just going to work on Unity, I’ll be working at Unity.

So what does this mean for Strange? Well, Unity are hiring me, they’re not buying Strange, so on the one hand don’t expect them to be integrating it into the product anytime soon, or charging for its use, or anything of that sort. From Unity’s perspective i don’t think anything about Strange will really change. On the other hand, you can expect that future StrangeIoC development (and there will be further development) will be able to take better account of upcoming features, and of course I hope to both increase the profile of Strange in Unity development circles and help improve the overall community ethic around relevant issues such as decoupling, testing, and other best practices.

I hope everyone in the Strange family is as excited about this turn of events as I am. While I’m naturally disappointed that my little startup didn’t meet with instant success, I’m nevertheless stoked to be back with Strange and Unity. I hope you’ll forgive my absence and celebrate an exciting future.

So what will I be doing? Well, my first responsibility will be to the analytics team, helping you to make better sense of how users are playing your games. From our early discussions (and this Unite 2014 presentation), it’s clear Unity wants to eliminate the pain points that keep you from instrumenting your app or understanding the resulting data. My experience in front-end development and decoupling come very much into play in achieving these goals. More generally, you can be assured that the philosophies underpinning IoC will have another in-house advocate.

Before I wrap, let me take a moment to once again thank the superheroic efforts of Will Corwin, who has looked after Strange, answered questions on the Google Group, handled pull requests and bug reports, and generally kept this enterprise alive in my absence. It’s down to him and you that there is an enterprise to return to.

So, the ball is in your court. Where should Strange go next? Ideas for new features? More examples/documentation? I’d certainly love to build a roster page at our site listing games and companies using Strange, which I think would help advance the cause. Please chime in. We’re off to a Strange new start!