ListensTo: The Sound of His Master’s Voice

Just a quickie post to introduce you to a nice enhancement, now part of the upcoming Strange release.

The sound of his master's voice.

Good Will Corwin, author of Strange Signals and my co-owner of StrangeIoC, has added a feature that allows you to remove some unnecessary legwork from your Mediators.

How many times have you typed some variation of this?

[Inject]
public MySignal mySignal {get; set;}

override public OnRegister()
{
    mySignal.AddListener(listenerMethod);
}
override public OnRemove()
{
    mySignal.RemoveListener(listenerMethod);
}
private void listenerMethod()
{
    //Took a lot of lines of code to get here
}

Now in the whole, vast scheme of things, this isn’t the worst thing in the known universe (I reserve that kind of derision for blended whisky). But it’s a lot of boilerplate, and pretty annoying when you’re trying to code as fast as you think.

Will’s latest work gets us to the same result a lot faster, and just as clearly:

[ListensTo(typeof(MySignal))]
public void listenerMethod()
{
    //Wow! That was fast!
}

[edit]I changed the method accessor above to ‘public’. Only public methods are  scanned for ListensTo. ‘private’ and ‘protected’ methods aren’t scanned (we always try to minimize the costs associated with reflection), so there’s no simple way at present to throw an error and alert you if you mark the method incorrectly. We’re looking at whether we can do this better.[/edit]

The ListensTo attribute allows us to implicitly handle injection, and the adding and removing of Signal listeners at the default moments, thereby making your code that bit more concise and manageable. As with anything to do with reflection, we encourage you to be cautious with this use in your main game loop (i.e., don’t create and destroy lots of Mediators at performance-critical moments…this has always been the case).

The new version of Strange is fast approaching. You can see the evolving feature list here: https://github.com/strangeioc/strangeioc/wiki/TODO-list-for-next-version.

It’s probably worth pointing out that these features are in flux…and we’re not ruling out more. If there’s something you need or just really want, please let us know!

Advertisements

New feature: Editor Views within Editor Contexts

At the SF Unity User Group a few nights ago, one gentleman asked me (as he had in fact once before) whether Strange could be used within the Unity Editor. He wants to do a better job building Editor extensions, and he’d like it if we could assist.

sherlock_strange

Sure, I said, if you want to build in the necessary changes. I wasn’t too keen to do the work myself…how many people actually have this need? But the more I thought about it, the more I decided it was an appropriate use case…and it didn’t actually seem that hard. We’d mostly just need a specialized Context and a specialized MediationBinder.

So I’ve been whirring away at this for a day or two, and the (definitely not-ready for production) alpha is now on branch feature/editor. It principally involves a new extension package called ‘editor’ that includes the following classes:

  • EditorContext (same as Context, but specialized for Editor)
  • EditorContextException (for reporting errors)
  • EditorMediationBinder (a specialized variation of MediationBinder)
  • EditorMediator (similar to, but with important differences from, Mediator)
  • EditorMVCSContext (a specialized variation of MVCSContext)
  • EditorView (like View, but we extend EditorWindow instead of MonoBehaviour)

Please review the code. For the most part, there’s not a lot that’s surprising. But we do have some differences to discuss, which I’ll get to after I (finally) get to our actual headline.

In order to test my work, I’ve started working on a StrangeIoC inspector. The beginning of this is also on the branch. Thing is, I don’t do a lot of Editor extension work, so I’m not entirely sure how to proceed. And any way, what features would be most useful? So I’m going to start working on this tool-thingy as part of the next release, but I’ll probably come to you via this blog to generate ideas and help me fix the things I break.

OK? Ball’s in your court my friends.

Moving on, here are some things you probably want to know about the differences between regular Strange and Editor-extending Strange.

There’s a lot more working around statics

EditorWindow features seem to be built on a lot of static methods. This isn’t helpful in a Strange world. On the other hand, Strange can help isolate a lot of this silliness. For example, my StrangePanel already has a ScriptReloadService to isolate the service aspect of knowing that scripts have been updated. This helps with abstraction and keeps my StrangePanelView focused on View-related behavior.

There’s no ContextView

Traditionally, we kick off a Strange app with a MonoBehaviour at the top of a view hierarchy. This doesn’t make sense in Editorland (the most magical place on Earth), where we instead use the [InitializeOnLoad] attribute. What’s nice about this, though, is that [InitializeOnLoad] means our package is just plain up-and-running when we enter Unity. And there’s no need to track or think about which View is “on top”.

There’s no Cross-Context behavior

At least for V1, this seems OK to me. It’s a bit hard to say at this point whether we want multiple contexts in a single Editor extension. I suppose we might. Anyway, let’s cross that context when we come to it.

To be clear, I’m talking about multiple Contexts in a single extension. I’ve made sure to handle the possibility of more than one extension, both of which happen to use Strange (this is called ‘optimism’). Each extension gets it’s own Context within which to operate.

EditorMediators are not Views

In regular Strange, your Mediators are MonoBehaviours, so in some respects they’re just like Views. I’m not even sure I could make this happen in Editor-flavored Strange, but I really didn’t try. EditorMediators now actually behave much more like Mediators in Robotlegs, in that they are in contact with the View, but unable to perform actual View logic themselves. This doesn’t seem like a problem to me. You’ll have to let me know if you disagree.

For the EditorMVCSContext, Signals are the primary event bus

I’ve been thinking about doing this in the rest of Strange, where the primary event bus is still EventDispatcher. For Editor, this seems an obvious thing to do, since Signals really are a better approach, and we may as well hit this brave new world with the best tools.

Review and Comment

As always, I ask you to look at this now, before it’s a fait accompli and in the live product. It’s better for everyone if this work is challenged and vetted a lot before we use it in anger.

And let me know what you want/need in a Strange Inspector. Should we be able to inspect our bindings from there? Write them? List all our Contexts/ContextViews? Give me some ideas!

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.

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!