quinta-feira, 6 de novembro de 2014

Design Patterns - Observer

This week was time to make another visit to Observer Pattern, this time implementing on "Frontent" JavaScript.

Counter is a "class" that manages an, obviously, a number counter, this counter is shown in an HTML page in a DIV.

The Observer pattern is used to observe whenever the counter changes and updates the HTML elements in charge.

HTML page look something like:

1:  <html>  
2:       <head/>  
3:       <body>  
4:            <div id="counter1"/>  
5:            <progress id="counter2" value="1" max="100"/>  
6:            <button type="button" onclick="aCounter.sum(10)">Increment</button>  
7:            <button type="button" onclick="aCounter.sub(10)">Decrement</button>  
8:            <script src="script.js"/>  
9:            <script>        
10:                 var aCounter = new Counter();        
11:                 aCounter.addObserver( new CounterObserver('counter1') );        
12:                 aCounter.addObserver( new ProgressBarCounterObserver('counter1') );      
13:            </script>  
14:       </body>  
15:  </html>  

And our counter would look like (comments and other stuff removed):

1:  var Counter = (function () {  
2:    function Counter() {  
3:      this.value = 1;      
4:            this.observerList = [];    
5:       }  
6:    Counter.prototype.sub = function( how_much ) {  
7:      this.value -= how_much;      
8:            this.executeObservers();    
9:       };    
10:       Counter.prototype.sum = function( how_much ) {  
11:      this.value += how_much;      
12:            this.executeObservers();    
13:       };    
14:       Counter.prototype.getValue = function () {  
15:      return this.value;    
16:       };    
17:       Counter.prototype.addObserver = function( aObserver ) {  
18:      this.observerList.push( aObserver );    
19:       };    
20:       Counter.prototype.executeObservers = function () {  
21:      var that = this;      
22:            this.observerList.forEach( function( item ) {  
23:        item.execute(that);      
24:            });    
25:       };    
26:       return Counter;  
27:  })();  

One of our Observers is meant for updating one DIV in HTML page:

1:  var CounterObserver = (function () {  
2:    function CounterObserver( aDOMId ) {  
3:      this.DOMId = aDOMId;    
4:       }  
5:    CounterObserver.prototype.execute = function( aCounter ) {  
6:      document.getElementById(this.DOMId).innerHTML = aCounter.getValue().toString();    
7:       };    
8:       return CounterObserver;  
9:  })();  
And the last is one Observer for a HTML Progress Bar:

1:  var ProgressBarCounterObserver = (function () {  
2:    function ProgressBarCounterObserver( aDOMId ) {  
3:      this.DOMId = aDOMId;      
4:            document.getElementById(aDOMId).value = 0;      
5:            document.getElementById(aDOMId).max = 100;    
6:       }  
7:    ProgressBarCounterObserver.prototype.execute = function( aCounter ) {  
8:      document.getElementById(this.DOMId).value = aCounter.getValue();    
9:       };    
10:       return ProgressBarCounterObserver;  
11:  })();  

The result is something like


segunda-feira, 20 de outubro de 2014

Entities

Now that we've defined how an Entity look like, thru EntityInterface, lets implement one:

Person.php

 class Person implements EntityInterface {  
   private $name;  
   private $address;  
   public function setName($name) {  
     $this->name = $name;  
   }    
   public function getName() {  
     return $this->name;  
   }  
   public function setAddress(Address $address) {      
           $this->address = $address;  
   }    
   public function getAddress() {  
     return $this->address;  
   }        
 }  

TypeScript & localStorage

Playing around with Typescript/Javascript decided to post a client-side cache method using HTML5 localStorage.

Starting with a mock how it should work the cache usage:

 export class userController {  
   public findUsers(id: string) {  
     var key: string = 'users:' + name;  
     // fetch from cache      
     var cache = new Cache.LocalStorageCache();        
     var data = cache.get(key);  
     // null = not in cache      
     if (data == null) {  
       // Make API Call        
       var request = new API.Request("/api/v1/users/", "get", {  
         "id": id  
       });  
       request.addCallback((response: API.Response) => {  
         var data = response.getData();        // store in cache   
         cache.set(key, data);  
         this.useUsers(data);        
       });        
       request.execute();      
     } else {  
       // CACHE HIT        
       this.useUsers(data);    
     }  
   private function useUsers(data: any) {  
     // do usefull stuff      
     // like display on box/html    
   }  
 }  


Cache interface must follow:

 interface CacheInterface {  
     get($key);  
     set($key, $value, $ttl);  
     delete($key);  
     exists($key);    
 }  


One possible implementation:

 export class LocalStorageCache implements CacheInterface {  
   /**  
       * determine if browser supports localStorage  
    * @returns {boolean}  
    */  
   public hasCache(): boolean {  
     return window['localStorage'] !== null;    
   }  
   /**     
    * gets value for one key, null if not found   
    * @param key     
    * @returns (string) content of key     
    */    
   public get(key: string): string {  
     var object = JSON.parse(localStorage.getItem(key));      
     if (object != null) {  
       if (this.isExpired(object)) {  
         // no need to delete, will be replaced          
         // this.delete(key);          
         return null;        
       } else {  
         return object.value;        
       }  
     } else {  
       // not on localStorage        
       return null;      
     }  
   }  
   /**     
    * checks if a item has expired     
    * @param item     
    * @returns {boolean}     
    */    
   public isExpired(item: string): boolean {  
     var item_timestamp: number = item.timestamp;      
     var now_timestamp: number = new Date().getTime();      
     var ttl: number = item.ttl;      
     return ((now_timestamp - item_timestamp) > ttl * 1000);    
   }  
   /**     
    * store one value in localStorage     
    * @param key unique key to store this item     
    * @param value string to store     
    * @param ttl time to live in seconds     
    */    
   public set(key: string, value: string, ttl: number = 60): void {  
     // @todo check ttl      
     var object = {value: value, ttl: ttl, timestamp: new Date().getTime()}  
     localStorage.setItem(key, JSON.stringify(object));    
    }  
   /**     
    * deletes a item on storage     
    * @param key     
    */    
   public delete(key: string): void {  
     localStorage.removeItem(key);    
   }  
   /**     
    * checks if a item exists in storage     
    * @param key     
    * @return (boolean) true if exists, false otherwise (also when ttl expired)     
       */    
   public exists(key: string): boolean {  
     var object = JSON.parse(localStorage.getItem(key));      
     return (object == null || this.isExpired(object));    
   }  
 }  

quarta-feira, 24 de setembro de 2014

Ubiquitous Language

Importante na aprendizagem do Domain, escrever e ser fiel ao termos aprendidos, exemplo de Race, Event, Checkpoint, etc.

Propositadamente não comecei pela Base de dados, pensar apenas no na lógica do problema e não com questões técnica.

Grande parte dos objectos descritos vão ser Entity e outros Value Object, as entity tem um referencia única e Value Object são "descartáveis". Melhor começar a ver

E um pouco de código definindo uma Entity geral para todos os nosso objectos:

EntityInterface.php


 abstract class EntityInterface {  
   private $id;   
   public function setId($id) {  
     $this->id = $id;  
   }  
   public function getId() {  
     return $this->id;  
   }        
 }  

New Project, learning the Domain

Exemplos de Design Patterns aplicados na resolução de problemas reais.



Como protótipo para as "experimentações" com design patterns decidi aplicar num pequeno projecto onde tenho algum conhecimento sobre o Domain.


Por conveniência o código ira ter nomes em Inglês.

Pragmaticamente:

  • A aplicação tem que controlar uma corrida (Event). 
  • Cada corrida pode ter várias provas (Race).
  • Cada prova tem um ou mais corredores (Participant e Person).
  • A prova tem vários postos de controlo (Checkpoint) onde os corredores tem que passar (CheckpointControl).
  • Os corredores pertencem a uma categoria (Category), de faixa etária (Age) e sexo (Gender). 
  • O critério das categorias são sobre a idade (AgeCriterion) e sexo (GenderCriterion).
  • O participante inscreve na prova (ParticipantRegister), começa (ParticipantStart) a prova (ou nao (ParticipantDidNotStart), começa a corrida (ParticipantStart) e passa (ParticipantCheckpointControl) nos postos controlos, e termina a prova (ParticipantFinish); pode ser desclassificado (ParticipantDisqualified). 

Mais algum detalhe sobre cada uns dos objectos:
  • Event - Descrição, Race(s)
  • Race - Descrição, Data Início, Participant(s)
  • Person - Nome, Gender, Data Nascimento
  • Participant - Nome, é um Person
  • Checkpoint - Race, nome
  • CheckpointControl - Checkpoint, Participant, Data e hora
  • Gender - M ou F
  • Age - Idade
  • GenderCriterion - lista de sexos no critério
  • AgeCriterion - intrevalo de idades no critério.
  • Category - Nome, Gender(s), Age(s)
  • Estados - a desenvolver...

Já dá para tirar uma ideia onde vamos começar, com o Model da aplicação. Cada item marcado a Azul será uma Classe, Entity ou , na primeira iteração, primeiro prototipo.

Trabalho de casa: procurar no amigo os termos desconhecido com a palavra Design Patterns antes.

Na próxima mensagem directo à prática!

Hello World!

Hello World!

Small talk big plans. Here you will find some PHP & JS & Other code prototypes.