Showing posts with label strategy. Show all posts
Showing posts with label strategy. Show all posts

Friday, August 11, 2017

Friday Challenge #6: Which Way Should We Go?

Lets say you've got some decisions to make. You have a bunch of stuff to get done but you aren't so good at managing your priorities...so you create a system to keep your priorities in order.


Ok that's cool. But how do you prioritize those taks? Maybe you want to take care of the one that's the latest first - if there are any that are late. Or how about the most important? The one closest to due date that isn't late?


Make a Priorities class with a method called GetHighest that gives back the highest priority item depending on the aforementioned conditions.


Lets try this two ways:


1: Write an algorithm that takes into account all those ways to prioritize using 'if' statements.


2: Use a class for each way you want to prioritize and pass it into the GetHighest method. The class should have a Rank method that takes the array (or whatever) and gives back the ordered array (or whatever).
You should have 1 class for each way and pick the way in a different method.


Now go back to way 1 and add a new condition and ranking. And do the same for way 2.


Ok so maybe you have to add and if statement either way or use a map of conditions to class for way 2. But how about this...combine conditions. Or maybe chain filters...make filter classes to remove those that are late and those with low value...combine those two filters in different ways with the soonest due ranking. Now you can create different filter and ranking strategies based on different conditions...


Now if you have 2 hours to spare and the top priority task takes 4 hours, you can apply a strategy that takes into account how much time you've got, how many people are available, what skills are required, or whatever else you need...do that with procedural code and you'll wind up with a twisted mess to sort through anytime you need to add a way to do rank or filter! Go ahead...try it with way 1!


In this challenge you've exercised the strategy pattern and possibly the factory pattern if you've used a factory to retrieve the appropriate strategy.


A few things to try with the factory - use contextual information from the real world - time of day, number of tasks to prioritize, time available, etc. Re-use the filters in the factory to get percentages of tasks that are late and chose a certain ranking strategy based on the percentage...you can see how various strategies can be combined to create new strategies and even reused in other ways that a procedure cannot. This also works in functional programming, in fact it's how functional languages work best...map, filter, etc. The strategy is the map function you pass into map or the filter function you pass to filter, etc.