Thursday, 12 February 2015

Learning OO programming in a day

Since I come from a background of AngularJS and PHP web development, I have almost no experience designing object-oriented program, skipped CSC108, and haven't taken a single comp sci course in my life. Although PHP does have a an Object-Oriented side to it, I've never used it much before learning Python's OO. I had a few books on Python and decided to read a few to get a solid understanding of OO as I pretty much had no idea what was happening in class.

I learnt that OO in Python is very similar to OO in PHP and an "emulation" of AngularJS. First, Python supports multi-inheritance while PHP does not. AngularJS does not really use the concept of "objects" much and uses the MVC model. I quickly caught the concept of OO in Python after reviewing and learnt that Python calls a "parent" object to create a new object. This parent object contains callable methods such as init and new, but can re-defined by Python:

Python:
class X:
    def __init__(self, x):
        self.x = x
        self.y = x + 1

PHP:
class X {
    public function __construct(x) {
          $this->x = x;
          $this->y = x + 1;
    }
}

As you can see, PHP uses the term this instead of self. Also, PHP does not need to pass self into the parameter while Python separates these two processes in that you must include self inside the parameters of the function. Furthermore, PHP immediately declares a function as public, private, or protected, while Python uses @property to emulate this. By learning Python OO, I was able to apply it immediately into PHP and boost my knowledge it. It also helped reinforce the concept of MVC in AngularJS, the same code in AngularJS:

var myMod = angular.module('myMod', []).
config(function($provide) { //$provide is an injectable parameter in the config attribute
$provide.provider('exampleProvide', function() {
this.$get = function(x) {
                         return x + 1
};
});
});

myMod.controller('x', ['$scope', 'exampleProvide', function($scope, exampleProvide) {
//Dependency injection from $scope and the provider function that will be used to reference a service from the creation of the module
//Set up initial scopes from the ng-init module
        $scope.xInit = function(x) {
                    $scope.x = x;
        }
        $scope.y = exampleProvide($scope.x);
}]);

AngularJS uses dependency injection to allow functions into a controller or module. The controller can be viewed as a function in Python. The ng-init module defines a directive (a function that sends code) to receive a parameter and define it as x, ($scope is a service that manipulates the "Pyhton shell" (HTML) of the code)

I'm glad I was able to learn OO and apply to lots of my code in PHP and AngularJS. It especially helps as I'm currently Node.js and MonogoDB and most of them deal with objects encoded into JSON.



No comments:

Post a Comment