Action selector – interesting approach

I decided to share with you an interesting approach which I constantly use
to replace switch statement in a nice and readable way. Colloquially speaking, it is called an action selector.

Without further ado, here’s an example. I think that code is self explanatory.

Example is a fiction with an abstract problem, which car buying decision you should make.

Very simple Car entity

public class Car
        public int Age { get; set; }
        public decimal Price { get; set; }

Action selector itself

public class ActionSelector
        private readonly Dictionary<Func<Car, bool>, CarBuyDecision> _actionSelector;

        public ActionSelector()
            _actionSelector = new Dictionary<Func<Car, bool>, CarBuyDecision>
                {ShouldBuyACar, CarBuyDecision.BuyACar},
                {ShouldAskForBetterPrice, CarBuyDecision.AskForBetterPrice},
                {ShouldCollectSomeMoreMoney, CarBuyDecision.ShouldCollectMoreMoney}

        private bool ShouldAskForBetterPrice(Car car) =>
            car.Price > 20000m && car.Price < 25000m && car.Age < 12;

        private bool ShouldBuyACar(Car car) =>
            car.Age < 10 && car.Price <= 20000m;

        private bool ShouldCollectSomeMoreMoney(Car car) => true;

        public CarBuyDecision PerformAction(Car car)
            foreach (var key in _actionSelector.Keys)
                if (key.Invoke(car)) return _actionSelector[key];

            return CarBuyDecision.NoDecision;

Action selector is:

  • easlily extensible with another, even very complex conditions and actions
  • fancy
  • allowing code developer to explain the code flow

Leave a Reply

Your email address will not be published. Required fields are marked *