Showing posts with label oop. Show all posts
Showing posts with label oop. 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.

Friday, August 4, 2017

Friday Challenge #5: Fixed Gear or 3-speed?

When I first encountered an OO language (Java) there was a tutorial that used bicycles to explain polymorphism. All bikes have some behaviors in common - you pedal them to move forward, you turn one of the two wheels using the handlebars to steer. While there are exceptions - pedal-less bikes for kids, sit down bikes with levers to steer, pedal assist (actually a moped) - the common case serves as great fodder for object oriented programming. With that, let's start the next challenge!

You don't have to use Java to take on this challenge, there are many many object oriented languages and many that have support for classes. Use whatever you would like to use - learn a new lang maybe!


Given the following types of bikes:

3-speed cruiser, id=1, type=MultiSpeedBicycle
10-speed mountain bike, id=2, type=MultiSpeedBicycle
BMX - fixed gear, id=3, type=SingleSpeedBicycle


Write a method that takes in a bike id and returns the bike. The method signature should have the base/parent type as the return type.


Bicycle getBicycle(int id);

Bicycle is an abstract type.

You can either make a static method on Bicycle if your language allows it, or make a BicycleFactory to house the method.


The basic bike (the abstract Bicycle type) has 3 methods - pedal(int pressure), applyBrakes(int pressure), steer(float angle).


A bike with gears EXTENDEDS the basic bike with two additional methods: shiftUp(), shiftDown().

*If you'd like, you can add some additional methods like getCurrentGear(), getMaxGear()...or you could return a bool from shiftUp and shiftDown to say if it changed or not...or return the resultant gear of the action. The more the internals of the object are protected the better, the consumer should not know what gear the bike is in, only that they can shift gears up or down.

Whatever you use to call getBicycle will eventually want to check what type that bicycle is...as far as it knows it only has the basic bicycle methods. Until it does know, shifting isn't an option.

Let's say we have a UI for this bicycle. Actually we would want a different UI for each type since users will interact differently with each type. The shiftable bicycles will have some way to shift gears in the UI - maybe a certain keypress or tapping the screen a certain way...how about pressing shift levers?


Fetch the proper UI for the type inside a method that has this signature...

BikeView getView(Bicycle bike); 


Inside that method, interrogate the type of bicycle and return the view for that type. Put that method into a BicycleViewFactory - do you think the constructor for it takes in all the views or maybe something that knows how to load all the views? Just stub out something for now - create the various view classes and have the method return the right one for the type of bicycle. Maybe you really only need two types of bicycles, maybe you want three - that's entirely up to you and far you want to go with the details.


So that's the challenge...write up those classes and put it altogether with some way to exercise (pun intended) the methods and verify that the right View is returned in the end. The View doesn't actually need to have anything in it, neither do the methods on Bicycle...stubs will work just fine. The lesson here is in how getBicycle and getView are implemented.


Oh! I almost forgot! There's one more thing you can do - you'll want something to load the bike and return the proper views...a BicycleController! First it needs to load up an input view to receive the bike id (maybe list them all - listBicycles() and have the user select one if you'd like). Once an id is sent to getBicycle, that method should call your _bicycleFactory.getBicycle() method to load up the bike. Pass that instance to the ViewFactory to get the view...if you got back a BicycleView return it to the user - else maybe return an ErrorView...the BicycleController should take in both the BicycleFactory and the BicycleViewFactory and hold internal references to those...they should both be set up and ready to use before they are passed into the controller.

Feel free to implement the UI in any way you see fit - heck try going for multiple UIs! Everything should be re-usable at this point...the only things that should change based on the UI you want to implement are the Views!

Let's take that a bit further... Consider different UIs. Maybe the user has certain preferences. Or maybe it's a different view per screen type. Perhaps there's a VR view with actual pedals and steering wheel as input...a stationary bike! Got it!? Those would have different Views for different user interfaces.

Alright, have fun! Happy Coding!

This challenge is all about polymorphism, factory pattern, MVC pattern, encapsulation, Dependency Injection.







Monday, March 6, 2017

Functional Programming like an OOP-er?

So, I've been learning much about Functional Programming techniques. Elm-lang is a great budding FP language that transpiles to javascript and is optimized for the browser - haven't seen much in the way of server-side packages for it...but then again, I haven't really looked.

One key feature of the FP languages I wan't to riff on is Currying - basically it's where you create a new function that does the same thing but with less parameters and you set defaults.


In javascript, for example if you had the following function...

    function saySomething(message, person){
        ...
    }

you could curry the message and create a new function to sayHello

    var sayHello = function(person) {
        return saySomething("Hello", person);
    }

Well, that's all well and fine. Our sayHello function would only be able to say "Hello" as that would basically be set in stone for this "instance" of saySomething. I said instance didn't I? Couldn't think of a better OOP way to put it. It's also called a closure isn't it? Basically we are creating a function object that has a locally scoped value of "Hello".

It could also be written like this (which is a bit more re-usable):



    var sayHello = currySaySomething("Hello");

    function currySaySomething(message) {
        return function(person){
            return saySomething(message, person);
        }
    }

//or if you like

    function currySaySomething(message) {
        return function(person){
         var _message = message;
            return saySomething(_message, person);
        }
    }

And in this way, an instance of the function object "saySomething" is returned as a closure with the locally scoped variable "message". It can be done another way...this one is straightforward OOP in javascript.


    var helloSayer = new HelloSayer();
    helloSayer.sayHello({name:"Li"});

    function HelloSayer() {
        var _message = "Hello";
        return { 
            sayHello : sayHello
        };

        function sayHello(person) {
            return saySomething(_message, person);
        }
    }

Well, that's an OOP way to do it, but it still meets the same goal of immutable state that's important to FP. But if you think about it - currying is really setting the internal "state" of a function. It's kind of like using a Factory, although in the example below it might be a bit overkill - could just use new Sayer("Hello"), but that's not the point of a Factory. If you need a Factory, there it is.


    var factory = new SayerFactory();
    var helloSayer = factory.build("Hello");
    helloSayer.sayHello({name:"Li"});

    function SayerFactory() {
        return { build : build };
        function build(message) {
            return new Sayer(message);
        }
    }

    function Sayer(message) {
        var _message = message;
        return { 
            sayHello : sayHello
        };

        function sayHello(person) {
            return saySomething(_message, person);
        }
    }

I guess what it comes down to is how you use the objects. One could have objects that hold internal immutable state. Using an OO language it's often necessary to avoid overly-complex, unreadable code.