StrangeIoC v1.0 RC1 is here!!!

Will Corwin just pulled us over the finish line! Or the starting line…whatever. The first release candidate for Strange v1.0 is now on tip.

https://github.com/strangeioc/strangeioc/tree/tip

Also check out Will’s post in the Google Group (you are a member right?): https://groups.google.com/forum/#!topic/strangeioc/IWRTPE4jc0w

Please start using it…find all the flaws…let us know what you like and what you don’t. We’d like to have it blessed and official in time for Unite Boston.

As always, a huge thanks to Will for pushing things forward, and a further thanks to all of you for your patience and interest. Let’s make Unite Strange!

Advertisements

v1.0 and BSHT latest

Once again, just keeping you up-to-date on our progress.

The Big, Strange How-To proceeds at a reasonable pace. We’ve received quite a lot of excellent feedback on everything released so far, and I can’t begin to tell you how grateful Will and I are for that. Please keep it coming!

I thought I’d share the table of contents, as it’s beginning to take a more concrete shape. I’ve also included the status of each chapter, so you can get a feel for how far along we are. Compare it to this article and any thoughts you’ve had, and let me know if you see anything missing.

Intro (open for review)

Walk through (wip)

Deep dives

Best Practices (first draft open for review)

Unit testing with Strange – wip

Platform-specific issues (TODO)

  • IL2CPP
  • iOS and Trampolines
  • Known unsupported platforms and why
  • Other?

As for the state of v1.0 itself, we’re honestly not moving forward as quickly as I’d like. Will and I have had some difficulty coordinating schedules. We need to review each other’s work, and firm up the release so you all can get some time with an RC before it goes live. Here’s our TODO list, along with the state of each item.

Best practices – Draft

These are my ideas so far around Best Practices for the v1.0 of the Big, Strange, How-To. Let me know what else we might want to say. What have I forgotten? What am I dead wrong about? Let’s work up a great list to help users get Stranger than ever.

My idea of a Strange Best Practice.

My idea of a Strange Best Practice.

General

“Render unto Unity that which is Unity’s”

What is the core purpose of Strange?

Dependency injection? That’s just one of many features. Decoupling? That’s simply a means to an end. No, the core purpose of Strange is to make your life easier. It’s a tool, like any tool. And like any tool it should be applied to the correct set of jobs. However much you like drills, you wouldn’t drive a nail with one. In the end, all the DI/IoC/Decoupling magic has to be judged against that standard. So after giving it a reasonable try, consider every recommendation, “rule”, and philosophical tenet here by evaluating exactly that. I already know the extreme value of what I’m advocating. It won’t hurt my feelings if you disagree (well, maybe a little).

Does the feature you’re working on fit well into Strange’s structure? If you’re trying to rethink physics into a Strange controller because that’s “proper” MVC, then I guarantee you’re doing it wrong. Unity already has a very nice physics system. Let it do its job. A third-party AI designed to be attached to a specific GameObject is more of a grey area. So ask yourself: is this likely to change? Is there a sensible way to decouple (perhaps apply the AI MonoBehaviour as a secondary Mediator)? If you can do these things, make it Strange. If you can’t, you have my permission to let it be.

Injection

Minimize injection at performance-critical moments

Strange is at its best for application-level architecture, and at its worst in your game loop. Supplying Mediators and injections to thousands of enemies at a performance critical moment would not be a very efficient use of resources. Be realistic about your performance requirements. If your game is entirely turn-based, maybe the performance issue is irrelevant to you. If you’re trying to create a massively multiplayer action game that runs on an older smartphone, make sure you think this through!

Wrap a third-party Singleton

Lots of very fine (and some not so fine) third-party libraries are written as Singletons. While we disagree with this choice architecturally, it’s a simple fact of the Unity world. If you need to use a third-party library written as a Singleton, simply wrap it in an interface that is useful to you. We provide instructions on exactly how to do this in the injection deep dive.

If you need named bindings, use supply-binding where possible.

As of v1.0, you can apply named bindings through inversion.

Signals/Commands

Models and services should never listen to Signals

When models and services listen to Signals, they make two critical errors. First, they become tightly coupled to the rules of the specific game/application, which limits portability. Second, they bypass Commands, which tends to result in models and services bloated with logic. Logic is for Commands. Models handle state. Services communicate outside the app.

Dispatching Signals (as opposed to listening) is a bit more of a gray area. It still limits portability, but there’s less of a tendency to bypass Command logic. Stylistically, some people prefer to make Commands completely stateless, so that they are never retained. I prefer the following pattern.

Use Promises in retained Commands

The most common reason for retaining a Command is that you are calling outside Unity, waiting for some response. The new Promises package makes this sort of callback much cleaner and lowers the number of dependencies. It also strengthens the argument for keeping Signals out of services and models altogether.

Consider the following Command:

public class FetchLevelNameCommand : Command
{
    [Inject]
    public IServerAPI service { get; set;}
    override public void Execute()
    {
        Retain();
        service.FetchLevelName().Then(OnName);
    }

    private void OnName(string name)
    {
        //Do something with the result
        Release();
    }
}

What I like about this pattern is (a) it’s very clean, readable code, (b) your service needs no injected Signals, (c) any adapter logic (up, down, or both) gets handled in the same place.

Using clear naming conventions, match Signal names to Commands

Ideally, Signals and Commands should be named such that they obviously connect. Obviously, the entire point of decoupling them is to allow you not to do this. That doesn’t mean you need to set out to make things any harder than they have to be. Start things in alignment, and don’t lose sleep when design changes dictate that they drift.

Pool Commands when possible

Every object created and destroyed must be handled by garbage collection. Marking Commands as Pooled() eliminates some of this collection. Provided you are careful to clean up after yourself, it’s usually best to mark Commands this way. See the section on Command pooling for details.

Follow the single-responsibility principle in your Commands

Treat each Command like a method that does one thing. If a single Signal results in ten different things happening, ganging all that up into one Command makes that code complicated, non-portable and inflexible. On the other hand, if you break all those responsibilities down, it becomes much easier to reuse the bits that may apply to other Signals. You’ll get less code duplication and more reuse, and other programmers (including you in three months’ time) will be able to understand with greater ease what the hell you were trying to accomplish.

Avoid injecting into Views

This is definitely a best practice, not a requirement. When a View goes through the mediation process we explicitly check whether it needs injection. So why tell you not to do a thing that we explicitly allow and provide a mechanism for? This goes to a philosophy that I call “I’m not your mother”.

There are plausible reasons for injecting directly into Views: you might have a bit of decoupled code you want accessible by the View; you might not buy our argument about the value of mediation; perhaps you want to couple a model directly to a View for convenience. I might disagree with these choices (or maybe not, depending on circumstance), but the choice on how to use our tool is ultimately yours.

Now, why is it “best” not to do this? Read the mediation section in the deep dive: keeping your Views as pure Unity probably serves you best most of the time.

“Gang up” a View into a useful component

We often observe that new users misconstrue the purpose of mediation, thinking that each GameObject, each button, each line of text must be its own View with a corresponding Mediator. This is manifestly incorrect. The point of mediation is to allow you a clean separation between the View and the app…nothing in that specifies a 1:1 control:View relationship. Create useful components, small or large, that meet your needs, and mediate those. With UI, I often find that this correlates to 1 screen = 1 View.

Keep Mediators thin

Mediators aren’t intended to do the work of the View. Nor are they intended to provide (much) logic. The sole role of the Mediator is to adapt between View and application. Keep it thin.

Consider using multiple Mediators

It is commonly assumed that each View needs only one Mediator. This is usually sufficient, but there are excellent cases for applying multiple Mediators. My favorite is for analytics. Rather than mixing up your analytics logic (was this button clicked? how many times? before or after the user did this other thing?) with either View or Mediator, consider adding an extra Mediator solely for the purpose of listening out for button clicks and the like. This can make the agonizing process of instrumenting your game clean and trivial.

Contexts

Use clear naming conventions plus implicit bindings to keep Contexts clean

In even a moderately complex application, your Context can start to look like a very long shopping list. We find that many bindings start to crystallize as development proceeds. Rather than enumerate the blindingly obvious, we recommend using Strange’s implicit binding feature to keep your Context spare. Implicit bindings are always overridden by explicit bindings, so you can make changes when special cases arise.

Part of the trick to keeping this easy, especially in large teams, is to maintain sensible naming conventions so you can intuit the most likely implementing class.

//Sensible naming convention
public class PlayerModel : IPlayerModel

//Less sensible naming convention
public class PlayerModel : IPlayer

//Full-on insanity naming convention
public class DefaultPlayerModel : IShip

Build platform variants at the Class level; put all platform-dependent statements in the Context

Have you ever waded through code like this?

public class FaceRegognizer {
 void Start () {


    #if UNITY_EDITOR
     Debug.Log("Doing a thing in Unity Editor");
    #elif UNITY_IPHONE
     Debug.Log("Doing a thing on Iphone");
    #elif UNITY_STANDALONE_OSX
    Debug.Log("Doing a thing on Stand Alone OSX");
    #else UNITY_STANDALONE_WIN
     Debug.Log("Doing a thing on Stand Alone Windows");
    #endif
 }        
}

And let’s be honest: it’s NEVER that clean. Instead of having this code mixed-in and littered throughout your code, we recommend sectioning off all platform-specific behavior into well-named classes. You’ll still have all that #if…#elif magic, but it’ll all be in one place, and each implementing class will tell a consistent, readable story for its use case.

//All common capabilities in an abstract class
abstract public class AbstractFaceRecognizer : IFaceRecognizer{}

//Each of these implements the functionality as required by the platform
public class DefaultFaceRecognizer : AbstractFaceRecognizer{}
public class IosFaceRecognizer : AbstractFaceRecognizer{}
public class WindowsFaceRecognizer : AbstractFaceRecognizer{}
public class OSXFaceRecognizer : AbstractFaceRecognizer{}

//Now bind with all the #iffyness
#if UNITY_EDITOR
injectionBinder.Bind<IFaceRecognizer>().To<DefaultFaceRecognizer>().ToSingleton();
#elif UNITY_IPHONE
injectionBinder.Bind<IFaceRecognizer>().To<IosFaceRecognizer>().ToSingleton();
#elif UNITY_STANDALONE_OSX
injectionBinder.Bind<IFaceRecognizer>().To<OSXFaceRecognizer>().ToSingleton();
#else UNITY_STANDALONE_WIN
injectionBinder.Bind<IFaceRecognizer>().To<WindowsFaceRecognizer>().ToSingleton();
#endif

Stick to a strict, Context-based hierarchy

As we explained in the Mediation deep-dive, the Context-based hierarchy — i.e., childing a GameObject to a chain that can “bubble up” to a ContextView — is only required in a multi-Context situation. That said, starting this way, even in a single-Context situation, gives you the flexibility to choose the multi-Context approach at a later time.

Build modularity using multiple scenes, each in its own Context

One of Strange’s superpowers is connecting multiple Contexts. We often talk about it as a special use-case, but the utility of this concept shouldn’t be underestimated, especially when working in teams. This basically brings decoupling to the macro level, since one person/team can work on one chunk of a game, completely abstracted from others. A scene can be a mini-game, level, store, UI screen, what-have-you, built to stand all on its own, yet able to be integrated into the larger whole when necessary. This can greatly speed up workflow and even make it possible to share whole sections of a project between multiple games. I mean, seriously, once you’ve created an in-game store for Age of Jellyfish, do you really want to build it again for Age of Anchovies?

Inching towards v1.0

This is just a quick update to let you know we haven’t been entirely idle. Progress on V1 .0 continues on two fronts:

  • Preparing the release candidate
  • Writing sections of the new Big Strange How-To

Will and I have been discussing the fastest route towards getting a release candidate to you so y’all can start playing with it. We apologize that this is taking longer than we anticipated. Some of this boils down to our work for Unity: there’s quite a lot of urgency around the release of 5.1, and even 5.2 behind that.

As to my work on the BSHT, I have partial (almost complete) chapters on injection, mediation, reflection, signals, and commands. I also have a great deal of the walk-through complete (I write a lot via dictation as I walk to and from work, as I’m doing now). In each case, there are some details that require investigation before I’m ready to put these chapters out for review.

Apologies for the delay. Rest assured we are as eager as anyone to get the new version shipped.

One Strange Week in Spain

will_aurimas_marc

Let’s start with what this article will not be about. Dependency injection will not be a native feature in Unity. Not, at least, for the foreseeable future.

But for one exciting week, it was.

A question I got more than once when I joined Unity was “will Strange become a part of Unity?” I answered, “No, Unity are hiring me. Not buying Strange.” Nevertheless, the idea of integrating certain features of Strange  directly into Unity has never been far from my mind.

Last week, Unity engineers from all over the world met up in Malaga, Spain for a big hackweek: one hundred and fifty engineers, all brainstorming and blue-skying projects they thought might be fun or useful for the company and/or community.  And a mighty assembly of ideas it was.

Among these brave souls, our friend Will Corwin proposed the integration of dependency injection directly into Unity as a native feature. Obviously, this was something I couldn’t pass up. Together with colleague Aurimas Cernius, we leapt in and made it so.

Our goals:

  • Create a simple, easy-to-use DI system
  • Explain the value of DI to hackweek participants

We were not attempting to make Strange a native feature. The MVC construct on which Strange is based is a useful application paradigm, but it’s certainly not the only one. None of us thought that the larger framework was appropriate as a native feature. What we did (and do) regard as appropriate, was the injection feature itself. To do this we needed the following pieces:

  • The injection system, obviously
  • The reflection system, for efficient caching
  • A context, for writing bindings

We started by copying the appropriate packages from Strange, stripping out anything that wasn’t useful to our case. Mostly this meant simplifying the Context.

One of the cool things about adding injection directly to Unity is the ability to ditch some of the shoehorned functionality Strange copes with on startup. UnityEngine.Injection, as our system came to be, had C++ hooks to kick off certain processes, making those early milliseconds cleaner and more reliable.

It all started with this player setting.

Use_DI

With this Boolean switched on, the DI system went to work, searching for a Context marked with the [BindingContext] attribute. This meant that a ContextView in our system was optional. Sure, you’d want one to mark out sub-contexts, but a viewless Context is probably a better choice for your first Context, which shouldn’t have to be tied to a view in any way, and shouldn’t be destroyed if your scene changes (we’ve even thought of implementing this idea in Strange itself).

Of course we have our familiar [Inject] and [PostConstruct] tags. The only other place where our injection system touches the developer is in MonoBehaviours. Aurimas wrote this native hook:

[InjectDependencies]
public class SomeClass : MonoBehaviour {
    [Inject]
    public ISomeService YouKnowTheDrill { get; set; }
}

Any MonoBehaviour so marked seeks out and finds the correct Context, based on the same set of rules Strange uses. The results of these simple changes were pretty cool.

  • A developer can start playing with DI with as little as a button click and about 5 lines of code (An Inject tag and a simple Context). Compare that with what it currently takes to get into Strange for the first time.
  • MonoBehaviours can request injection directly. They don’t need to extend View.
  • Strange (or other IoC systems) could be layered on top of this system.
  • A colleague pointed out that resolving bindings should really be a compile-time operation, not runtime. We agree. That could potentially be fixed by internalizing DI.

We had most of the functionality working by Wednesday morning, so we had accomplished our first goal. But for the second goal — explaining the value — we didn’t yet feel like we had an ideal presentation. Fortunately, inspiration struck late Wednesday: we quickly re-tooled a one player game to two player and wired it up with a real-time server.

Actually, we used not one real time server but two! We leveraged an experimental server written by another hackweek team, then showed how using DI bindings we could instantly swap between the experimental one and UNet.

The video below (no audio) shows our presentation “slides” along with some side-by-side video of the game running with the experimental server.

[BindingContext]
public class MyGameContext : Context
{
  protected override void mapBindings()
  {
    InjectionBinder.Bind<GameManager>().ToSingleton();
    InjectionBinder.Bind<IPlayer>().To<PlayerModel>().ToSingleton();
    InjectionBinder.Bind<IDispatcher>().To<Dispatcher>().ToSingleton();
    //InjectionBinder.Bind<IRealtimeServer>().To<NullServer>().ToSingleton();
    InjectionBinder.Bind<IRealtimeServer>().To<UnetServer>().ToSingleton();
    //InjectionBinder.Bind<IRealtimeServer>().To<CloudCodeServer>().ToSingleton();
  }

  protected override void postBindings ()
  {
    InjectionBinder.GetInstance<GameManager>();
  }
}

This was a fun project. It led us to consider more deeply than we ever had before what it would mean to integrate DI directly into Unity. As I said at the top, this isn’t something we see being implemented in real product anytime soon, but we made more folks within Unity aware of what we do and why. We met some great people, heard about some amazing ideas, and started some conversations that may someday bear fruit.