Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Tuesday, February 26, 2013

Choosing colors for your Roguelike

If you're making a roguelike you need to decide what colors to use. You could stick with the original 16 colors or you can use hundreds or thousands of colors. I don't know much about colors and color schemes but I have some advice on choosing colors for a roguelike. For my 2012 7DRL, I rule, you rule, we all rule old-school Hyrule, I followed three simple rules about color:

  1. The hue should match the real world color. That is; red things should be red and green things should be green.
  2. The saturation and brightness should match how important something is. If it's trying to kill you or it can save you then it should stand out as a bright color. If it's just background - floors, trees, walls - then it should be mostly gray or black so it doesn't get your attention. You can only notice so much at once and you should notice the important things first.
  3. Subtle variation in color is a good thing. Some variation makes large blocks of trees or water look better but too much variation and shading makes it hard to tell if the color is relevant or not. In iryrwarosh, each tree has three different colors. Water, lava, and sand also had some variation. The variation was subtle enough to break up the monotony and allow things like animated water and lava. Possibly too subtle, but that's just fine with me. Just don't overdo it; even if two trees are a slightly different shade of red or green, you should still know they're the same thing.

Overall I'm very happy with how iryrwarosh looked and I think it's due to following these three guidelines. It did take some time to tweak the colors, but it was really worth it. I plan on following the same guidelines this year.

As a bonus, here's the ActionScript that I use to make a color with a specific hue, saturation, and value.

Saturday, February 23, 2013

A* algoritm in ActionScript

Want to know the shortest path from one point to another? If you're making a roguelike then you probably do. You could use Dijkstra's algorithm, but there's an alternative that finds the result much faster. It's the A*, or A Star, algorithm. It's a lot like Dijkstra's algorithm except instead of checking the neighbors of all the currently visited cells, it just checks the neighbor of the visited cell that's the closest to the target. Of course if you already know which one is closest then you don't need to pathfind. Instead you just estimate which one is closest. Even if your estimates are a bit off, you'll still find the shortest path in much less time.

Here's an ActionScript implementation.

This algorithm needs some explanation since it was made by mathematicians - who generally suck at naming variables. That's why there's a g, h, and f cost. The H cost is the heuristic or estimated cost from a point to the end point. The G cost is the actual cost from the start point to a point. There's no need to estimate that because you only calculate this on points that you've visited. The F cost is the total of the two. By only checking the neighbors of the point with the lowest F cost, you end up - in the best case - only checking the points that are in the shortest path. You can change the getGCost and getHCost methods to cause different behavior. Maybe some points cost more to travel through? Maybe moving diagonal cost more than moving in the cardinal directions? Try it and see what happens.

The checkEnding boolean is because in my game people sometimes can pathfind to walls and obstacles that block movement.

It's mostly used for pathfinding but can also be used for carving rivers, roads, or caves during worldgen. You could also use it to tell where someone is probably going to go - useful for placing traps I suppose. Have you seen any interesting uses for this algorithm?

Tuesday, February 19, 2013

Dijkstra's algorithm in ActionScript

Dijkstra's algorithm is a useful algorithm for roguelike developers to know. It basically calculates the distance from a starting point to all other points. Once you know the distances, you can walk backwards from any point to the start. It's great for worldgen, floodfilling, ai, and pathfinding to the nearest something. Dijkstra's algorithm is also the basis for autoexplore in brogue. If you want to know "where's the nearest" of something, use Dijkstra's algorithm.

Here's an ActionScript implementation.

Note that it uses a grid to track parent nodes as well as if a cell has been visited or not. It does this for performance reasons but it's possible to keep a list or dictionary of visited nodes instead.

This implementation takes the start position, a function that verifies a cell can be entered, and a function that determines if a cell is what you're looking for. It returns an array of points from the start position to the end position or an empty array if no path was found. Using canEnter and check functions means that there's no dependancies on details of your game code - which is a very good thing. Passing in your game details means that if you want this to work with land creatures, water creatures, and amphibians, just pass different versions of canEnter depending on who's searching. And since you pass your own check function, you can search for whatever you want. Injured creatures could search for the nearest healing potion. Fleeing creatures could look for the closest tile that isn't visible from the player. Exploring creatures could look for the nearest tile that they haven't seen before. There's a lot of potential uses for this algorithm.

Saturday, February 16, 2013

Field Of View (FOV) in ActionScript

One of the simplest ways of calculating Field Of View (FOV) in a roguelike is also my favorite. There's several different algorithms but I like to keep it simple. Just check every tile within a view radius of the player. If you know how to calculate Line Of Sight, then it's very easy. If the line to the end point isn't blocked, then the end point is visible. Once you can check line of sight between arbitrary points, then it's easy.

Here's a Flash implementation. Use your mouse to see what's viewable from a location.

It's probably the least efficient way to do it - which is why it takes a second or so to calculate. It is super simple to understand and implement though. I also think it looks the best. Not only can this be used for seeing which tiles are visible from a specific tile but it can also be used for seeing what's affected by an explosion or other effect.

Once you have performance problems you can switch to a more efficient algorithm or rely on caching.

Thursday, February 7, 2013

Line Of Sight (LOS) in ActionScript

One of the simplest algorithms in any roguelike is line of sight (LOS). It's basically drawing a line from one point to another and seeing if anything obscures it. Here's an Actionscript implementation of the Bresenham line algorithm (invented in 1962!).

It's not super obvious what's going on. Basically, figure out which direction the line always goes, and how often it goes in the other axis. Then go.

This is the basis for simple field of view (FOV) algorithms and is a quick and easy way of seeing if a tile, item, monster, or event can be seen by the player or another creature. It can also be used to calculate where a projectile will go, corridor generation, or simple pathfinding in open spaces.

I'm sure there are low-level ways to make this perform faster like bit shifting or breaking each octant into it's own function. It could also return an iterator that calculates points as-needed. This would allow really long lines - or even infinitely long lines - while only calculating what's actually needed.

Monday, November 19, 2012

BlogPost blogPost = BlogPostFactory.MakeBlogPost(NewBlogPostOptions.BlogPostWithAbsurdTitle)

Don't leak useless implementation details in your variable, method, or class names. Just don't.

Sure, the name may be accurate and true, but so what? I don't need to see the class name 5 times in one line - that just clutters up the place. It also makes it harder to see similarities in code and opportunities for refactoring. These kinds of names also go against the entire point of polymorphism: you don't need to know the type, just it's capabilities. Hungarian notation obviously falls into this category of cluttering up the place with implementation details. I rarely need to know the exact type or inner working of something. What I need to know is the intent.

There is one place where a name should leak implementation details though: choosing a strategy. Not just the Strategy Pattern, but even between different methods that all do the same thing but in a different way. I'm thinking of things like depthFirst vs breadthFirst, MaximizeBenefitStrategy vs MinimizeCostStrategy vs MinimizeRiskStrategy, or calculateLevenshteinDistance vs calculateJaroWinklerDistance. These seem like good implementation leaking names to me since when I choose one, I need to choose the exact details. Of course they could be wrapped in intention revealing names which would be used most of the time:

public double PercentSimilarTo(this string myself, string other)
{
    var longest = (double)Math.Max(myself.Length, other.Length);
    return EditDistanceCalculations.CalculateLevenshteinDistance(myself, other) / longest;
}


Try it for a few weeks and see what happens. I think that replacing implementation revealing names with intention revealing names is one of the easiest ways to improve code.

var p = new Bp()

Don't use abbreviations in your variable, method, or class names. Just don't.

Sure, you save 2 or 3 seconds, and a few characters on the screen, but so what? You, or whoever is looking through your code, loose even more time when you have to look around to find out that cs is an array of Customers. Then you have to spend time trying to figure out why you have this array. Are they delinquent customers? New customers? Customers who have a birthday today? What's the intent of this thing? This is especially bad with primitives or collections of primitives because they have even less inherent meaning. It's also bad when the same variable is used for multiple things. If cs is an array of customer indexes on one line, an array of page numbers on another, and x, y, and z coordinates for an airplane on another line then you can't give it a good name and it should be split into three separate variables: customerIndexes, pageNumbers, and airplaneCoordinate.

Worst names:
cs
arr
sb
awos

Bad names:
custs
array
stringBuilder
accounts

Good names:
birthdaysToday
selectedIndexes
warningMessage
accountsWithoutOwners


A name is more than just a unique identifier: it's a way to express intent and meaning. The compiler doesn't care what you use - it's just as fine with zhqxv as it is with unwantedLocationNames - but I know which one I'd prefer.

I can only think of one reason to have a one character or abbreviated name: if it's a well known and commonly accepted part of that domain. Gui and hud may be acceptable names within a user interface domain and x and y sound acceptable when talking about cartesian coordinates. If you look at it a certain way, i and j could be considered valid names within the "looping through a collection with an index" domain, but even then, there's probably a better name.

Try it for a few weeks and see what happens. I think that replacing abbreviations with real, intention revealing names is one of the easiest ways to improve code.

Friday, August 24, 2012

Easier object setup in ActionScript

I recently thought of something that will make it easier when I'm creating instances with different values in ActionScript and thought I'd share it. It's sort of a mix of default parameter values and optional parameters and it makes it much more convenient to setup instances of things that are slightly different.

Let's suppose I have a Weapon class with some basic stats:

class Weapon
{
 public var name:String;
 public var attack:int    = 10;
 public var defense:int   = 10;
 public var speed:Number  = 1.0;
 public var heavy:Boolean = false;
 public var tags:Array    = ["weapon"];
 
 /* skipping constructor and a "describe" function that prints the values */
}

And assume I have some other code that creates a bunch of instances. They're mostly the same but ideally I could just specify what's different than the default. Something like this:

var weapons:Array = [
 new Weapon("stick"),
 new Weapon("sword", { attack: +2, defense: +2 } ),
 new Weapon("club",  { speed: -0.25, heavy: true } ),
 new Weapon("knife", { attack: -2, tags: ["sharp"] } )
];

for each (var weapon:Weapon in weapons)
 trace(weapon.describe());

It would be really cool if I could get something like this as the output:

stick = { attack=10, defense=10, speed=1, heavy=false, tags=weapon}
sword = { attack=12, defense=12, speed=1, heavy=false, tags=weapon}
club = { attack=10, defense=10, speed=0.75, heavy=true, tags=weapon}
knife = { attack=8, defense=10, speed=1, heavy=false, tags=weapon,sharp}

Well, wish no more because it's possible. Here's the function that makes it happen. It takes two things and expands the first by the second. It could be improved to handle other types, but this is enough to get started with.

public function expand(receiver:Object, expansions:Object):Object
{
 if (receiver == null || expansions == null)
  return receiver;
  
 for (var property:String in expansions)
 {
  if (receiver[property] == null)
   continue;
  
  var value:Object = expansions[property];
  
  if (value is Number || value is int)
  {
   receiver[property] += value;
  }
  else if (value is Array)
  {
   for each (var element:Object in value)
    receiver[property].push(element);
  }
  else
  {
   receiver[property] = value;
  }
 }
 
 return receiver;
}

Just use it in the constructor or some section external to the object like a Factory.

public function Weapon(name:String, values:Object = null)
{
 this.name = name;
 Util.expand(this, values);
}

I'm sure I'm not the first to do something like this but I think it's a more convenient way to create things. If I ever find myself working on a 7 day long project and need a quick way to add content, this could be useful....

Wednesday, June 6, 2012

Extract Method or Extract Class?

There's been a recent mini-revolution to what I think about refactoring.

For a few years now my most common refactoring was Extract Method. Got a big method? Extract sub methods. Got a deeply nested method? Extract each level into a new method. Got any other problem? You should probably look for methods to extract.

I've change my mind; these days I'm all about Extract Class, or more accurately Replace Method With Class. Got a big method? Cut out it's body and paste it into a new method on a new class. Got a deeply nested method? Well... I guess Extract Method still works better for that one. Got any other problem though? Just pick the largest method (or #region for you C# folks) and extract it to a new class.

Why the sudden change of mind? Recent real world experience that is best explained with bulleted lists within a matrix:



Extract Method Extract Class
Mess Unless there's a lot of duplication that you can quickly remove, the class size stays about the same.  Immediately reduces the class size by moving code to a new class. The compiler will tell you what it depends on and what depends on it.
Power You get a new method:
  • you can call it with different parameters
You get a new class:
  • you can instantiate it with different parameters
  • you can subclass and override it
  • you can pass it around
  • you can move related behavior to the same class
  • you can shift the burden of resolving dependancies to an IOC container or factory
Concepts Small, local, procedural:
  • encapsulates a local series of statements
  • tends to aid in procedural thinking
  • few design patterns are simple methods
Large, project-wide, object oriented:
  • encapsulates a bounded-context-sized role or responsibility
  • tends to aid in object oriented thinking
  • many design patters are objects
  • moves responsibility to the new class thereby increasing cohesion of the original class

or, in prose form: Extract Class immediately reduces the amount of code you have to worry about, improves cohesiveness of the remaining class, and gives you familiar object oriented techniques to work with.

Of course it's good to see if related methods could be extracted into a new class after extracting a method and it's probably good to break up the monster method after hiding it in a new class. I just found it much easier to make progress when I relied on extracting large methods to new classes first.

Thursday, May 31, 2012

Reminder: SOLID roguelike code is good roguelike code

I have the strong suspicion that roguelike worldgen code tends to be very procedural. Even with object oriented languages, worldgen code has a natural tendency to turn into a large procedural class with procedural methods modifying procedural data in a very procedural way: little if any polymorphism and little if any interaction among objects with single well-defined responsibilities and behavior. But I recently refactored some worldgen code of mine and it's now several small classes that interact to build a world. It's of course much easier and safer to extend too. Here's how you too can turn procedural worldgen code into SOLID worlgen code.

The core idea is taken from an excellent post by the most excellent Mark Seemann where he introduces the concept of a Customization to his project AutoFixture. Here's the interface for a customization to a fixture:

public interface ICustomization
{
  void Customize(IFixture fixture);
}

And here's how it's used:

var fixture = new Fixture()
  .Customize(new DomainCustomization());

Neat. The ICustomization basically represents an arbitrary change to the default behavior of a fixture. This is very much like worldgen code - if you look at it a certain way. Start with a blank map, add a bunch of customizations, and you end up with an interesting world. One customization makes a lake, another adds a river, another adds a mountain, and on and on and on.

I took this idea and created a similar actionscript interface:

public interface Feature
{
  function addTo(grid:WorldGrid):void;
}

The various world features - lakes, rivers, towns, caves, fields, forests, etc - are each represented by a single class that implements Feature. Most are just a few lines but some are more complex and actually encapsulate logic that is only relevant to that feature. Creating a world with these features is also straightforward:

var grid:WorldGrid = new WorldGrid(width, height);
grid.add(new Shore());
grid.add(new Lake());
grid.add(new Lake());
grid.add(new Island());
// etc.

I wasn't sure if restructuring things like this would do much good or not but I'm convinced it has. Being able to add new features without touching existing code is such a great feeling that I'm trying to find more places to try out this ICustomization idea. What if customizations could change the overall world parameters like temperature or creature spawn rate? Could the core gameplay itself be customized and so that new features and subsystems like identification or poison be added just as easily?

None of this is new or difficult or all that remarkable on it's own. "Something that represents arbitrary changes" is a simple idea that won't revolutionize the roguelike world or the programming industry. You don't even have to learn any new acronym or framework or principle or anything else really. It's more like a reminder - which I need from time to time - of what happens when you consistently apply the Extract Class refactoring: good clean code.

Wednesday, March 28, 2012

Common uses for the State pattern

Of all the design patterns, I think the state pattern is one of the simplest and probably the one I use the most. It's easy to understand and easy to use but I still see many places where it could be used but isn't. Here's a few things that indicate when using state objects would be simpler.

If you have a variable that represents what 'mode' or 'state' something is in, or what the current behavior is, then you may want to use the state pattern. A common place for this is if you have a gui and the user can interact with one of many tools. Instead of:

public void onClick(int x, int y){
  if (currentTool == PAINT)
    canvas.paint(x, y);
  else if (currentTool == BLUR)
    canvas.blur(x, y);
  else if (currentTool == ERASE)
    canvas.erase(x, y);
  else if (currentTool == LINE && lineStart == null)
    lineStart = new Point(x, y);
  else if (currentTool == LINE && lineStart != null) {
    canvas.drawLine(lineStart.x, linesStart.y, x, y);
    lineStart = null;
  }
}

you could refactor to the state pattern:

public void onClick(int x, int y){
  currentTool.onClick(x, y);
}

class PaintTool extends GuiTool {
  @Override
  public void onClick(Canvas canvas, int x, int y){
    canvas.paint(x,y);
  }
}

This means that new tools could be added without having to change the gui code. The state pattern would also simplify the gui since it no longer needs to determine what clicking means. This is especially beneficial when multi-click operations are involved since the gui no longer needs extra variables to track that.

class LineTool implements GuiTool {

  private Point startPoint;

  @Override
  public void onClick(Canvas canvas, int x, int y){
    if (startPoint == null)
      startPoint = new Point(x, y);
    else {
      canvas.drawLine(startPoint.x, startPoint.y, x,y);
  }
}

That brings to another common case where the state pattern is useful: If you have variables that are used in some situations and ignored in others, then you may want to use the state pattern instead. For example, if you have a game or simulation where each agent either has a fixed home, another agent it follows, a group it considers "home", then instead of:

public void goHome(){
  if (homeLocation != null)
    goTo(homeLocation.x, homeLocation.y);
  else if (leader != null)
    follow(leader);
  else if (group != null)
    follow(group.getRandomMember());
  else
    wander();
}

you could refactor to the state pattern:

public void goHome(){
  home.goTo();
}

public class StationaryHome implements AgentHome {
  private Agent agent;
  private Point home;

  public StationaryHome(Agent agent, Point home){
    this.agent = agent;
    this.home = home;
  }

  @Override
  public void goTo(){
    agent.goTo(home);
  }
}

Once you have the different states, then the agent no longer needs all of those extra variables and is made much simpler. It also disallows states that don't make sense: what does it mean if an agent has a location it considers home and a group it considers home? If that's not a valid situation then you need to make sure you never end up with both. If it is a valid situation then you can just create a new state object that handles it.

You may have noticed something about these two examples: If you have a bunch of if/if else statements that compare variables to literal values (like enums!), then you may want to use the state pattern instead. Complex objects with complex logic can be greatly simplified by using the state pattern. In fact; it's possible to completely remove all branching and delegate behavior to multiple different state objects instead.

Since these scenarios are all cases where we want different behavior based on some runtime values, they're good candidates for the state pattern. So keep an eye out for chances to use the state pattern.

Wednesday, February 1, 2012

Java multimethods for a simple command handler

I came up with a simple way to have an event handler easily handle multiple types. It's basically a way to say a class implements Handle<DomainEvent1>, Handle<DomainEvent2>, which works fine in C# but doesn't work in java due to type erasure. My solution: reflection based multiple dispatch. I'm sure others have done this before so it's nothing new.

public abstract class Handler {

 public void handle(Object message) {
  multipleDispatch(message);
 }

 private void multipleDispatch(Object message) {
  try {
   this.getClass().getMethod("handle", message.getClass()).invoke(this, message);
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   ;
  }
 }
}

Not a good idea for high-performance applications and possibly not a good idea for any app. When you send a message to a class that extends Handler then the correct method will get called if it is capable of handling it. If you use a specific type then the specific method is called like normal, otherwise this multiple dispatcher tries to call the correct method.

Tuesday, January 17, 2012

Typefull Dynamic API: a typesafe C# facade/adapter/monad with phantom types

One of the things I came up with at home and actually got to implement at work is so useful, and novel to the C# crowd, that I thought I'd share. I call it a Typefull Dynamic API and it looks like an object that changes its public api at design time based on what would be the state of another object at runtime. Impossible? Nope. I'll even show you how you could have came up with it yourself.

The scenario

Imagine the following fictitious method:
public Account Example()
{
    var account = new Account();
    account.State = UsaState.California;
    account.Open();
    PeopleManager.SetAccountPeople(account, 0);
    MemberLevelServiceHelper.SetAccountHolderLevel(account, MemberLevel.Gold);
    new DebtCalculator().CalculateDebt(account);
    account.Complete();
    Reports.GetCompletedAccountReport().AddAccount(account);
    AccountUtil.Close(account);
    NoteAddingSingleton.Instance.AddNote(account, "I'm an example!");
    return account;
}
It looks like it creates an account, does some setup, and returns it. It's calling a bunch of things from all over the place. I know from experience that I'd have a hard time remembering where everything is and what order to call it in. Some things are on the account, some are singletons, some are helpers and utils - exactly the kind of situation that anyone who's joined a long term project with many other developers is familiar with. If only there was a unified interface for all these subsystems - oh wait - isn't that the definition of the classic Facade pattern?

The patterns

class AccountLifecycleFacade
{
    public Account RealAccount { get; set; }

    public AccountLifecycleFacade() 
    {
        RealAccount = new Account();
    }

    public void SetState(UsaState state)
    {
        RealAccount.State = state;
    }

    public void Open()
    {
        RealAccount.Open();
    }

    public void SetAccountPeople(int count)
    {
        PeopleManager.SetAccountPeople(RealAccount, count);
    }

    public void MakeGoldLevel()
    {
        MemberLevelServiceHelper.SetAccountHolderLevel(RealAccount, MemberLevel.Gold);
    }

    /* ... etc ... */
}
Having this facade lets us work through the lifecycle of an account without worrying about where that functionality is actually implemented; no more trying to remember which helper, manager, singleton, service, utility, or business class to use since we only need to look at one place. With one class for the hi-level functionality, we have a clear api and intellisense will show us what we can do with an account.
public Account FacadeExample()
{
    var account = new AccountLifecycleFacade();
    account.SetState(UsaState.California);
    account.Open();
    account.SetAccountPeople(0);
    account.MakeGoldLevel();
    account.CalculateDebt();
    account.Complete();
    account.AddToCompletedAccountReport();
    account.Close();
    account.AddNote("I'm an example!");
    return account.RealAccount;
}
And since it works with a single account at a time we can make it a wrapper. If we make the wrapper return itself at the end of each method then we'll be able to call it using a fluent interface.
class AccountLifecycleAdapter
{
    public Account RealAccount { get; set; }

    public AccountLifecycleAdapter(Account account) 
    {
        RealAccount = account;
    }

    public AccountLifecycleAdapter SetState(UsaState state)
    {
        RealAccount.State = state;
        return this;
    }

    public AccountLifecycleAdapter Open()
    {
        RealAccount.Open();
        return this;
    }
    /* ... etc ... */
}
And now our example method is a little simpler.
public Account Example()
{
    var account = new AccountLifecycleAdapter(new Account())
        .SetState(UsaState.California)
        .Open()
        .SetAccountPeople(0)
        .MakeGoldLevel()
        .CalculateDebt()
        .Complete()
        .AddToCompletedAccountReport()
        .Close()
        .AddNote("I'm an example!");

    return account.RealAccount;
}
That's much easier for me to read, understand, and test. I'm sure this facade/adapter has been done a hundred times before. I see one potential problem though: it looks like some of the methods are only valid at certain times. I'd wager that you can't complete a non-open account and that you really shouldn't add an account to the Closed Account Report until it's closed. We could rely on runtime assertions to verify the preconditions and post conditions of our new Account api, which is a fine idea, but wouldn't it be nice if we could catch this at compile time?

The magic

If the preconditions and postconditions of these methods were expressed in the type system then not only would the compiler stop us from running invalid code, but intellisence would only show the methods that are valid for the account we have. In order for that to work we need to change the type of our AccountLifecycleAdapter to expose the state of the account. For this example, certain things may only be valid when the account is new, opened, completed, or closed and certain things may only be valid for new, bronze, silver, or gold members. Not only do these methods have preconditions based on the status and member level of the account, but they also have postconditions that change the state of the account.

Some preconditions and post conditions of the domain methods.
MethodPreconditionPostcondition
Open()Status = NewStatus = Open
Complete()Status = OpenStatus = Complete
Close()Status = Open or CompleteStatus = Close
AddToCompletedAccountReport()Status = CompleteStatus is unchanged

Although we can change the state of an object, we can't change its type. Luckily we don't need to since we are returning an AccountLifecycleAdapter with each method: we can return a different type that represents the state of the account and only supports the methods that are valid for that account state.

One possible way is to have a new class for each possible state.
class AccountLifecycleAdapter_NewStatus_NoLevel
{
    public Account RealAccount { get; set; }
    public AccountLifecycleAdapter_NewStatus_NoLevel(Account account) 
    {
        RealAccount = account;
    }

    public AccountLifecycleAdapter_NewStatus_NoLevel SetState(UsaState state)
    {
        RealAccount.State = state; 
        return this;
    }

    public AccountLifecycleAdapter_OpenStatus_NoLevel Open()
    {
        RealAccount.Open();
        return new AccountLifecycleAdapter_OpenStatus_NoLevel(RealAccount);
    }

    /* ... etc ... */
}
This would make sure that the wrapper expresses the state of the account and that only valid methods are called for that account. But it could become a cartesian explosion; this example as 4 statuses and 4 member levels for a total of 16 classes you need to make. Since some things are applicable for several states (like CalculateDebt and Close from our earlier table), they'd need to be implemented in several different wrapper classes. Messy. Fortunately for C# users, the language offers a convenient way out by way of generics and extension methods. Instead of having the class name express the state, we can use a generic type parameter for each run time variable we wish to track; status and member level in this case. A method that creates a copy with the type parameters we want would let us chain the wrapped object along while changing the type parameters.

class AccountLifecycleAdapter<Status, Level>
{
    public Account RealAccount { get; set; }
    public AccountLifecycleAdapter(Account account)
    {
        RealAccount = account;
    }
   
  public AccountLifecycleAdapter<NewStatus, NewLevel> SetTypes<NewStatus, NewLevel>()
  {
    return new AccountLifecycleAdapter<NewStatus, NewLevel>(RealAccount);
  }
}


And a non-generic version will make sure we create the adapter with the correct default type parameters.

public class AccountLifecycleAdapter
{
  public static AccountLifecycleAdapter<New, NoLevel> New(Account account)
  {
    return new AccountLifecycleAdapter<New, NoLevel>(account);
  }
}


The methods that used to belong to the wrapper can now be moved into extension methods.

 public static class AccountLifecycleAdapterExtensions 
 {
  public static AccountLifecycleAdapter<New,NoLevel> SetState(this AccountLifecycleAdapter<New,NoLevel> adapter, UsaState state)
     {
         adapter.RealAccount.State = state;
         return adapter.SetTypes<New,NoLevel>();
     }
 
     public static AccountLifecycleAdapter<Open,L> Open<L>(this AccountLifecycleAdapter<New,L> adapter)
         where L : AccountLevel
     {
         adapter.RealAccount.Open();
         return adapter.SetTypes<Open,L>();
     }
  
  public static AccountLifecycleAdapter<Open,L> SetAccountPeople<L>(this AccountLifecycleAdapter<Open,L> adapter, int count)
   where L : AccountLevel
     {
         PeopleManager.SetAccountPeople(adapter.RealAccount, count);
         return adapter;
     }

    /* ... etc ... */
If we look at our extension methods then we see something I think is very interesting. With this kind of typefull api, the input parameter type represents the precondition and the return type represents the post condition.
public static AccountLifecycleAdapter<Open,L> Open<L>(this AccountLifecycleAdapter<New,L> adapter) 
    where L : AccountLevel
MethodPreconditionPostcondition
OpenStatus = NewStatus = Open

Since the valid status is expressed as a precondition and the what the method changes is expressed as the return type, the compiler and intelisense can make sure you only chain methods that make sense. If a method returns an AccountLifecycleAdapter<Open, Silver> then you can't call an extension method that expects a Closed account. Intellesence won't suggest invalid methods and the compiler won't allow them. As an added bonus, changing the preconditions or post conditions in a way that breaks code will prevent a compile instead of lying dormant until discovered, investegated, and fixed during manual or automated testing.

All we need now are the types that represent the runtime state.

The Phantom Types

These types are a little odd in that they are only used for compile time info and we never create instances of them. The Haskell community would call them Phantom Types so we should too.
namespace PhantomTypes
{
    public abstract class PhantomType {}

    public abstract class AccountStatus : PhantomType {}
    public abstract class New : AccountStatus {}
    public abstract class Open : AccountStatus {}
    public abstract class Completed : AccountStatus {}
    public abstract class Closed : AccountStatus {}

    public abstract class AccountLevel : PhantomType {}
    public abstract class NoLevel : AccountLevel {}
    public abstract class Bronze : AccountLevel {}
    public abstract class Silver : AccountLevel {}
    public abstract class Gold : AccountLevel {}
}
I like to make it double obvious that these are different than normal types with a separate PhantomType namespace and PhantomType base class.

Since the type parameters are part of the method signature, you can have different overloaded methods for different states. Here we can see that an overdraft will close the account unless it's a gold level account; they just get a warning.
    public AccountLifecycleAdapter<S,GoldLevel> Overdraft<L>(this AccountLifecycleAdapter<S,GoldLevel> adapter)
        where S : AccountStatus
    {
        NotificationService.GetInstance().NotifyOfOverdraft(adapter.Account);
        return adapter.SetTypes<S,GoldLevel>()
    }

    public AccountLifecycleAdapter<Closed,L> Overdraft<S,L>(this AccountLifecycleAdapter<S,L> adapter)
        where S : AccountStatus
        where L : AccountLevel
    {
        AccountUtil.CloseDueToOverdraft(adapter);
        return adapter.SetTypes<Closed,L>()
    }
Interfaces can be used if an extension method will work with multiple different phantom types.
  public abstract class AccountStatus : PhantomType {}
  public interface NotNew { }
  public abstract class New : AccountStatus {}
  public abstract class Open : AccountStatus, NotNew {}
  public abstract class Complete : AccountStatus, NotNew {}
  public abstract class Closed : AccountStatus, NotNew {} 
And the method that uses it would add that as a type parameter constraint.
     public static AccountLifecycleAdapter<S,L> AddNote<S,L>(this AccountLifecycleAdapter<S,L> adapter, string note)
         where S : AccountStatus, NotNew
   where L : AccountLevel
  {
   NoteAddingSingleton.Instance.AddNote(adapter.RealAccount, note);
         return adapter;
  }

Where to go from here

A lot more functionality and safety can be added. One idea is to add a check to the adapter's constructor or SetTypes method that asserts the phantom types match the actual run time state. This would let you know if your expectations of what's going on are correct or not.

public void CheckTypes<NewStatus, NewLevel>()
{
    if (typeof(GoldLevel).IsAssignableFrom(typeof(NewLevel)) && RealAccount.MemberLevel != MemberLevel.Gold)
      throw new InvalidOperationException("expected account member level Gold; got " + RealAccount.MemberLevel);
}

Another thing the adapter could do is collect all the ancillary objects that get created along the way. That way, once you're done with it you not only have your account, or whatever you were making, but any other related objects and you won't need to query for them.

One idea I haven't tried (yet...) is generating documentation about the system based on the adapter's extension methods. If you think about it, each of these methods is a transition from preconditions to postconditions. Each precondition and postcondition would be a state. You could use reflection, or old fashioned string manipulation, to capture all of the states and transitions within an adapter and create a state transition diagram. In a complex system this could be very useful for explaining the system to new hires, managers, users, other developers, or testers. Speaking of testing, knowing all of the different states transitions would also help ensure you are adequately testing all code paths.

I'm not entirely sure what to call this construct or "pattern". It's sort of the opposite of the State pattern; instead of an object changing behavior at run time, it's exposing a different api at design time. It's sort of like a Builder since you're building an object through a path that's more complex than a simple constructor. It can be a Facade and call other sub systems, but it doesn't have to be. It's also an Adapter since it exposes functionality related to the wrapped object. In my mind, the important thing is that it this is an adapter that only exposes methods that are valid for the run time state of the wrapped object. For now I'm calling this a Typefull Dynamic API but there may be a better name.

The Summary

Using the facade pattern can greatly aid in readability, understandability, and testability of a complex system with many subsystems - that's been known by many people for many years now. Using an object that returns itself in each method makes fluent interfaces possible - that's been known for a few years too. And using the signature of the method to express the preconditions and postconditions and making sure things are only called on object with the correct state has been around for decades, although I think the object oriented crowd has missed out on a lot of this since you can't change the type of an object when its state is changed. Extension methods give C# developers a chance to combine these in a useful way to get something new: a Typefull Dynamic API that changes its public api at design time based on what would be the state of another object at runtime.

Tuesday, January 10, 2012

The simplest typesafe EventBus

I'm a big fan of typesafety so while exploring messaging and events, I've also tried my own typesafe EventBus:

public static class EventBus
{
  private static Dictionary<Type, List<Action<object>>> handlers 
      = new Dictionary<Type, List<Action<object>>>();
  
  public static void Subscribe<T>(Action<T> handler){
    if (!handlers.ContainsKey(typeof(T)))
      handlers.Add(typeof(T), new List<Action<object>>());
   
    handlers[typeof(T)].Add(e => handler((T)e));
  }
  
  public static void Publish<T>(T e){
    var eventType = typeof(T);
   
    foreach (Type handlerType in handlers.Keys)
      TryPublishForType(handlerType, eventType, e);
  }
  
  private static void TryPublishForType(Type handlerType, Type eventType, object e){
    if (handlerType.IsAssignableFrom(eventType))
      handlers[handlerType].ForEach(handler => handler(e));
  }
}

It's very similar to the simplest event bus. I'm sure there are other ways of tracking what subscribers can handle each event but the Dictionary<Type, List<Action<object>>> works well enough. If you're not used to Haskell or C# type trickery then it may seem too complex either way but I think much of that is caused by how verbose C# tends to be.

One neat thing about typesafe event busses is that, if designed for it like this one is, they can respect the inheritance tree. That means if an Action<object> is subscribed, then it will get everything that get's published since all events are assignable to object. This also means that it is backwards compatible with the simplest EventBus. A few subscribers may need to explicitly state the event type they are interested in but if they use object as the type parameter when subscribing, then the behavior should be the same.

Wednesday, January 4, 2012

The simplest EventBus

I've been playing a lot with event buses, domain events, messaging, or whatever you want to call it. I've seen some open source event buses but they looked pretty complicated and often had a lot of extra baggage that clouded what I was interested in: exploring different ways to decouple collaborating classes. I had enough of that and set out to find the simplest thing that would get the job done and here's what I came up with:
public static class EventBus
{
  private static List<Action<object>> handlers = new List<Action<object>>();
  
  public static void Subscribe(Action<object> handler)
  {
    handlers.Add(handler);
  }
  
  public static void Publish(object e)
  {
    handlers.ForEach(handler => handler(e));
  }
}

That's it. No unsubscribing, multithreading, xml configuration, flexible dispatching strategies, subscription tokens, base classes, interfaces, or attributes. You don't have to use any specific interfaces to subscribe or publish. You don't even have to instantiate it - it's always ready. Anything can subscribe, anything can publish, from anywhere in your project. Anything can be published and every subscriber will get it. Want to publish an AccountClosed domain event? Go for it. Want to publish a naked string or int? Go ahead. How about publishing your entire Windows Form? I'm not sure why you would, but this won't stop you.

Just one line to wire-up a subscription (often called from Main):
public static void AddSubscriptions(ILogger logger, PopulationReport pop, MainApp app)
{
  EventBus.Subscribe(e => logger.Log(e.GetType().Name + ":" + e.ToString()));

  EventBus.Subscribe(app.HandleEvent);

  EventBus.Subscribe(e => {
    if (e is CreatureCreated)
      pop.CreatureCreated(((CreatureCreated)e).Creature);
    else if (e is CreatureDied)
      pop.CreatureDied(((CreatureCreated)e).Creature);
  });
}

And one line to publish (often called from domain objects):
public void Die()
{
  this.health = 0;
  EventBus.Publish(new CreatureDied(this));
}

It can be a bit on the slutty side since it's globally accessible and subscribers will get everything that's published, but that comes with benefits too. This is a good starting point and I haven't had any problems with it: the type checking is minimal for subscribers, I've never tried to subscribe a null, and I don't mind having my domain objects explicitly depend on it. You could add a ClearSubscribers method or a SetInstance method for unit testing, but I just use a single subscriber that dumps all events into a list when a unit test needs to ensure that specific events were created. In the last few at home projects I've worked on this has been the only static class I've used since this is one of the very few times that I'm in favor of a static class with behavior and state.

I find it much easier to learn about something when it's striped of all the unnecessary fluff. Event busses, domain events, messaging, whatever you want to call it is, in my mind at least, really just easy, ubiquitous, and loosely coupled communication.

Wednesday, December 28, 2011

From collaborator hell to dependency-free bliss

Let's say you're a developer on a C# app and just got a batch of new requirements. Let's also say that it has a fairly simple requirement: when a user closes his or her account, the account status should be set to closed. You, as a good Test Driven Developer, write your unit test, watch it fail, then add the following code to the Account class and watch your test pass:

public void Close() {
  this.Status = AccountStatus.Closed;
}

Easy-peasy.

Many weeks later you come across a requirement that says when a user closes his or her account, the account owner's IsSpecial flag should be set. To make your latest unit test pass, you do the simplest thing that could possibly work.

public void Close() {
  this.Status = Status.Closed;
  this.Owner.IsSpecial = true;
}

Your test went from Red to Green and now it's time to Refactor. Having your Account mutate some value on another object breaks encapsulation so you Control+R & E to Extract Method then Control+R & M to Move your method to the Owner class and give it a clear name.

public void Close() {
  this.Status = Status.Closed;
  this.Owner.ClosedAccount(this);
}

That's a little better. In stead of just setting some property you're now telling the other object that something happened. It's free to handle that how it wants and the Account needn't know about it - a textbook case of encapsulation and The Hollywood Principle.

You've worked in this domain long enough to know that all kinds of things are going to happen when an account is closed. Maybe the other things should be moved to a different method? Not entirely YAGNI, but modifying the account and telling others about it are two different things so you could make the argument that they should be two separate methods.

public void Close() {
  this.Status = Status.Closed;
  this.OnClosed();
}

private void OnClosed(){
  this.Owner.ClosedAccount(this);
}

It's a judgment call but this does clearly separate things. There's one method where the account modifies itself and another where all the other objects get to react to the account being updated. You know that if you have requirements that start with when an account is closed, then the code that deals with the account should go in the Close method and code that deals with other classes goes in the OnClosed method. But wait a second - doesn't this sound familiar? There's even something built into the C# language for just this scenario: events and delegates.

public delegate void ClosedEventHandler(object sender, AccountClosedEventArgs e);

public class Account {
  public event ClosedEventHandler Closed;

  public void Close() {
    this.Status = Status.Closed;

    if (this.Closed != null)
      this.Closed(this, new AccountClosedEventArgs(this));
  }
}

Now the owner can register a callback with the account's Closed event and the account can just tell whoever's listening when it has closed. The Account class no longer needs to reference the Owner class and we can rejoice.

But something about this still doesn't quite seem right. Now instead of the Account telling the Owner, the Owner has to listen to the Account. You still have one class directly referencing and depending on another - you just switched the dependency direction. A day or two later you remember you once read something about Messaging and Domain Events so you look it up and get that started.

public void Close() {
  this.Status = Status.Closed;
  EventBus.Publish(new AccountClosed(this));
}


/* ... elsewhere ... */
public class AccountClosed{
  public Account Account { get; set; }

  public AccountClosed(Account account){
    this.account = account;
  }
}


/* ... elsewhere ... */
class AccountEventsHandler {

  private IRepository repository;

  public AccountEventsHandler(IRepository repository){
    this.repository = repository;
  }

  public void Handle(AccountClosed e){
    this.repository.GetOwner(e.Account).IsSpecial = true;
  }
}


/* ... elsewhere ... */
public void WireEverythingTogether(IRepository repository){
  var accountHandler = new AccountEventsHandler(repository);
  EventBus.Subscribe<AccountClosed>(accountHandler.Handle);
}

Much nicer. Not only is the dependency completely removed from the Account and Owner classes, but each class no longer exposes methods that are just used for reacting to each other. The Account only modifies itself and creates events and the Owner only modifies itself and creates events. Now you have the Account depend on the EventBus and somewhere else you subscribe other classes to the appropriate events. You have a simple AccountEventsHandler that deals with coordinating other objects when the account changes so the domain objects themselves don't need to. It can be little bit more work, but it does reduce coupling and allow much cleaner domain objects. But the Account is still referencing the EventBus directly. You could use a service locator:

public void Close() {
  this.Status = Status.Closed;
  Services.Get<IEventBus>().Publish(new AccountClosed(this));
}

But the service locator can cause problems - like if an IEventBus wasn't registered - and is considered an anti-pattern by some people. You could use constructor injection to pass in the dependency instead.

public Account(IEventBus bus){
  this.eventBus = bus;
}

public void Close() {
  this.Status = Status.Closed;
  this.eventBus.Publish(new AccountClosed(this));
}

That's clean and a good use of the Dependency Inversion Principle, but maybe overkill since the EventBus is so simple and ubiquitous. Maybe hard coding a such a simple dependency is ok. In my limited experience this is an acceptable time for bending the rules and relying on a statefull static class. You will probably never hear me say that again since I hate working with static classes and singletons that have state or complex behavior. On the other hand, constructor injection is a great first step to using a Dependency Injection Container to wire up the EventBus and other dependencies.

Maybe months from now you can switch to actual full-scale event sourcing and CQRS. With command handlers, the Domain Objects create events and store them locally. Then the command handler would fetch all the events from the domain objects and pass them to the event bus; your domain objects don't even need to know about the event bus anymore since the command handler deals with that.



This series of slightly different ways of dealing with different objects involved in the same action is something that I've had a lot of problems with. It's all the same basic result but the important difference is in how to deal with coordinating different objects when something happens. These different designs have very different benefits and costs. The earlier examples are easy for anyone to do, easy to see exactly what happens when debugging or looking at the code, and you know exactly where to make the change: right in the method itself. The downside is that it becomes collaborator hell and all your classes quickly become so bloated that most of the class's code is actually about other classes. The classes become so interdependent that you can't change one thing without having to change everything else. Having lots of dependencies like this can also make build times suffer too. The latter examples only rely on the Event Bus, Service Locator, or Inversion Of Control Container so they are as non-dependent as possible but I can't really tell what's going to happen when the program runs. If everything is wired together with configuration in xml files or sql tables then it can also become exceedingly tedious and error prone to change. This kind of configuration becomes especially difficult if the developer's environment, qa environments, and production environments can all be configured differently. Not everyone will be familiar with or even like the event-based designs either. The whole thing is made even more confusing if different sections of the project have different ways of doing things and people mostly just do whatever they copied and pasted from - not that I've ever done that of course....

Friday, May 27, 2011

Interesting metric

Recently I did a search through some code for the expression "? true : false". Nearly 20 matches from several different developers. At least it's not breaking anything.

Wednesday, February 9, 2011

Understanding vs NUnit

Can you tell what MysteriousMethod does from looking at these C# unit tests?
  [Test]
  public void Test1()
  {
    var obj = new MysteriousObject();
    Assert.IsTrue(obj.MysteriousMethod(8));
  }

  [Test]
  public void Test2()
  {
    var obj = new MysteriousObject();
    Assert.IsFalse(obj.MysteriousMethod(11));
  }

Maybe it returns true if the input is even, or a single digit, or if it's not prime, or if it's divisible by 4 or 8, or maybe it only returns true for the number 8, I don't know. All I do know is that it returns true for 8 and false for 11.

Can you tell what mysteriousFunction does from looking at these Haskell QuickCheck properties?

  prop_test1 :: Int -> Bool
  prop_test1 x = x `mod` 4 == 0 ==> mysteriousFunction x

  prop_test2 :: Int -> Bool
  prop_test2 x = x `mod` 4 /= 0 ==> not $ mysteriousFunction x

It looks like it returns true if the input is divisible by four and false if it isn't. Pretty clear to me.



I'm working on a Haskell project and it's reminding me why I like QuickCheck so much. Not only does it do a much better job at catching unexpected cases but the meaning and intention of each function is so clear, much clearer than when using xUnit style testing. Going back to C# and NUnit feels weird; you're basically just comparing hard coded values. I find it hard to tell why one value is used instead of something else, i.e. what's essential and what's accidental, especially when the method being tested has several inputs or other variables it relies on. This can lead to bad assumptions and misunderstanding what something actually does. With QuickCheck there's less room for such confusion because the focus is on properties of the values and not the specific values themselves. The clarity of BDD tools (rspec, etc) seems to help, but I wonder what more can be done.

Wednesday, February 2, 2011

Interfaces as object contexts

Here's a possibly useful idea I came up with a few weeks ago. I've come across situations where an object needs different behavior depending on the context or how it's used. Usually the state or strategy design pattern (or a mess of if statements) can handle this, but so can explicit interfaces in C#.

First make an interface for each set of behavior you want.

interface IContextA
{
  string Property { get; }
  int Method(int data);
}

interface IContextB
{
  string Property { get; }
  int Method(int data);
}

Then create the different contexts or scenarios using the interface with the behavior you want.

static void DoStuffInContextA(IContextA example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

static void DoStuffInContextB(IContextB example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

Then create a class that implements the different behavior.

class MultiContextObject : IContextA, IContextB
{
  string IContextA.Property
  {
    get { return "called in context a"; }
  }

  int IContextA.Method(int data)
  {
    return data + 1;
  }

  string IContextB.Property
  {
    get { return "called in context b"; }
  }

  int IContextB.Method(int data)
  {
    return data - 1;
  }
}

And now you can use interfaces to select which set of behavior you want your object to use.

static void ExplicitInterfaceAsContextTest()
{
  MultiContextObject example = new MultiContextObject();
  DoStuffInContextA(example);
  DoStuffInContextB(example);
}

I think this is neat. It won't replace state and strategy patterns, but there's probably cases where those aren't possible or where this would work better.

Friday, January 14, 2011

Enum subsets in C#

After a few years of working with Haskell I've become nearly obsessed with expressing constraints in the type system. Although the C# type system isn't as expressive as Haskell's, preconditions, postconditions, ranges, complexity, and other things can be expressed. If the type is expressive enough then you don't even have to do any validation or checking when working with it because the compiler already guaranteed that the data is valid. One of the problems with C# enums is that they aren't real objects so they can't subclass; they're just pretty wrappers around primitives like ints or bytes. This means that if you only allow certain values of an enum then you have to manually check at runtime:

public void DeclareDayIsSpecial(DayOfWeek day)
{
  if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday)
    throw new ArgumentException("When declaring that a day is special, the day must be a weekday.", "day");
 
  Console.WriteLine("{0} is special.", day);
}

Even though you can't define an enum as a subclass of another and allow only that subclass, you can define an enum as subset of another.

public enum Weekday
{
   Monday = DayOfWeek.Monday,
   Tuesday = DayOfWeek.Tuesday,
   Wednesday = DayOfWeek.Wednesday,
   Thursday = DayOfWeek.Thursday,
   Friday = DayOfWeek.Friday,
}

Once you have this you can constrain your methods to just the valid subset of values.

public void DeclareDayIsSpecial(Weekday weekday)
{
  Console.WriteLine("{0} is special.", weekday);
}

The compiler won't allow you to use an invalid value so you have compile time documentation and feedback and can remove the runtime checks. This can be useful if you use enums in a scenario where only some values are valid. And since enums are wrappers around primitive types, you can safely cast from the subset (Weekday) to the superset (DayOfWeek).