Thursday, November 3, 2011

Design Pattern : behavioural

  1. Chain of responsibility
    1. The purpose for this is for high cohesion. This means, to increase the reusability.
    2. This can be visualized with the specialization in manufacturing world. Each function performs specialized task, and chained together to perform a bigger task.
    3. These functions can be reused in other scope since they are doing specialized and simpler task.
  2. Command
    1. This is to encapsulate requests.
    2. Thus, for a program to call any command, it has the similar interface.
  3. Interpreter
    1. This will translate the context passed by client and perform necessary task on it.
  4. Iterator
    1. This to enable to parse through the whole data structure.
  5. Mediator
    1. As a middle man between 2 sub-program to enable low coupling, or for decoupling purpose.
  6. Momento
    1. This is to capture the state of the class and stored in another object
    2. Good for undo to restore the object to its previous state
  7. Observer
    1. It’s for event driven.
    2. As listener, or “don’t call me, I’ll call you”
    3.  (After reading the online notes, I am not convinced by what was told in the class, so, please see d)
    4. objects need to be registered, the changes will be applied to all objects
  8. State
    1. This is to allow control on the behavior of the object when its internal state changes.
  9. Strategy
    1. Similar to state, but in different context.
    2. Different algorithms are implemented in child classes.
  10. Template method
    1. Preparing the abstraction/skeleton of the classes in the base class.
  11. Visitor
    1. To improve for high cohesion
    2. Slightly similar to Mediator, but mediator create the element class, while visitor does not. The element is created by client, and visitor is accepted by client to perform operation on element.
  12. Null object method
    1. This is used to handle “null object”. This null object is a real object, while it will not be set or do nothing when it is called.

Design Pattern : structural

  1. Composite
    1. It looks like tree structure, the end node is called leaf.
    2. All the node has uniform interface, thus they can be used/called via uniform operation/data structure
  2. Adaptor
    1. This is using another class to encapsulate the class to be accessed. Thus the caller will see/use the same interface regardless on how the class to be assessed being implemented.
  3. proxy
    1. This is acting as a middle man to handle the client requests and sever response.
  4. Façade
    1. This is using an interface to reduce the complexity.
    2. It packages the objects and methods
  5. Decorator
    1. This is for dynamically to add new responsibility / variation on the methods
    2. It will hold the base class pointer, and the real implementation on the child class or actual object.
  6. Bridge
    1. This is acting like multi-purpose adapter.
    2. It serves for multi-platform.
  7. Flyweight
    1. It handles the pool of resources that are shared by the clients.
  8. Private Class Data
    1. This is to put the private and readonly data into a class, and being initialized by construtor.

Design Pattern : creation

  1. Singleton
    1. this is basically suitable for single instance through out the program.
    2. it can contains the static variables used by the program.
    3. the benefits for this versus global variable is for data encapsulation purpose. You can have accessor and modifier functions as a guarding to set or read the variable.
  2. Factory
    1. The factory is a class to hold and control the creation of the class objects.
    2. The object class held by factory is the base class, thus any of the child class object can be instantiated, and transparent in the main program.
  3. Abstract Factory
    1. Similar to Factory type, but the factory is an abstract class.
    2. This is good for multi-platform support, where the right factory will be instantiated based on the platform.
  4. Builder
    1. This is to hide the complexity of the object by the builder.
    2. The program can have multiple builder with same operation but different methods.
    3. There is a “directory” to call the right builder to call for operation to produce “product”.
  5. Prototype
    1. Using abstract class to force the functions overidding (enforcement on the child classes)
    2. Thus the child classes need to have the implementation for the functions specified by the base class (the prototype abstract class)

OO concept and software development practices

I attended a 5-day Design Pattern class last year, and the summary that I published then, was the initial thought of this k-db site. I am revising them and put them here. :)

Day 1 : OO concept and software development practices

  1. OO concept revised.
      • Normally these are discussed :
        1. inheritance
        2. composition
        3. encapsulation
        4. polymorphism
      • Discussed in class :
        1. abstraction
        2. encapsulation
        3. generalization
        4. specialization
  2. Type of errors
      • compilation
        1. syntax
        2. contextual
      • linking
      • runtime
      • logical
  3. Example to show the best way to code to avoid error :
      1. if (x == 0)
      2. if (0 == x) <– using this coding style, missing a "=" in the condition statement will alarm error during compilation.
  4. Why it is a good practice to use static for variable declaration?
      1. for information hiding.
      2. so people won’t use extern to access to it in other file, to ensure the value is not overwritten by unknown.
      3. error prone during linking.
  5. Software quality measurement :
      1. reusability : code, function, user experience (dialogue box/interface), software pattern can be used in more context
      2. standardization
      3. robustness
      4. time to market
      5. stability
  6. Memory problem :
      1. memory leaks –> needs to take care by programmer
      2. memory fragmentation –> this will be based on how the heap memory is used and allocated for dynamic objects
  7. Good programming practice to have these 2 behaviour
      • low coupling
        • less dependency
      • high cohesion
        • make it smaller functions thus high reusability.
  8. Single assignment of responsibility
      • design by contract
        1. pre condition : should be caller’s responsibility, so callee need not to check and throw exception.
        2. post condition : should be callee’s responsibility, so caller can assume the result return is OK


As an introduction to design pattern in software, there are 3 categories : creation, behavioural and structural. These will be in the next few posts.

Wednesday, October 26, 2011

CDB - constant database

This is my official 3rd web job, and I got to learn a new database, CDB.

I tested freecdb in UBuntu.

To install
sudo apt-get install freecdb

To create a database file (native) :
cdbmake <db file name> <temporary file name> < <record file name>

* remember to have the record file to have a new line at the end of the file to indicate end of record.



<record file name> format :
+<key length>,<value length>:<key>-><value>

Test the database :
cdbtest < <database file name>

To dump database :
cdbdump < <database file name>

To get a record :
echo `cdbget <key> < <database file name>`

To print out database statistic
cdbstats < test.cdb

For more details on cdb : http://cr.yp.to/cdb.html

This database is good for simple database design, and data is populated during creation. As its name represent, the database should be static after creation, and used for data retrieval purpose. Thus, you don't see any update/insert/delete command in cdb.

Friday, August 12, 2011

Object oriented concept

Have been kept this post in draft for quite some times. Not sure when I'll start with my next topic. So, I decided to post this first.

Here's the first chapter, object oriented concept.

Let’s go through an example before explore the object oriented jargons.

Say, there is a book shelf. We have some books, a pen holder, pens, pencils, sharpener in the book shelf as illustrated below.



These objects are related to each other in some ways. The bookshelf contains books, pens, pencils, pen holder and sharpener. The sharpener is used to sharpen the pencil. The pen holder holds the pens and pencils. There is variety of books in the bookshelf.

How is this related to object oriented concept?

Class

A class is a collection of objects that has something in common. Say, we have a class of book. All books are classified in the class of book.

Object

Object is something real that exists. It is classified with other objects that share some common attributes into class. We can have Mind Maps by Tony Buzan as an object of book. We can have Harry Potter and the Order of the Phoenix by J.K Rowling as an object of book. We can also have exercise books and dictionaries as objects of book.

There are 2 types of relationship here. Is-a (inheritance), the Mind Maps is a book. Has-a (composition), the pen holder has a pencil in it.

Information hiding (encapsulation)

Let’s take the sharpener as example here. You know the function of this object is to sharpen a pencil. You put in a pencil, apply forces and turn the side handle, after a while, you’ll have the pencil with a pointed end. The side handle and the hole that hold the pencil are interfaces that we could reach. How exactly it works within the sharpener, doesn’t really matter to us. Besides, it also helped to safe guard, that the blade in the sharpeners will not hurt us. And we need not to know how many blades in the sharpener to do the function. This is what we called information hiding.

Inheritance

Inheritance is a concept in object oriented design that helps in classified the objects. Book is a big class. We can have dictionary, exercise book, fiction and non-fiction book to be categorized under this general class, book. We classified each object based on the common attributes. We can further classify based on other shared attributes. As illustrated in the diagram below, all books have number of pages as its common attribute. Dictionary would hold the number of word entry where the exercise books or fiction books doesn’t share this attribute. However, these 3 classes (dictionary, exercise book and fiction book) share the same attributes in the book class. Thus, they can exist as sub-class of book, and inherit the attribute from the book class.



Polymorphism

Let’s say we want to write something on an exercise book. We can use a ballpoint pen, a pencil, a fountain pen, a charcoal pencil to write. Polymorphism is a concept that allows the replaceable objects to do the same thing.

This passage is focusing on object oriented concept in using SystemVerilog. There are more jargons for software engineering which are not discussed here.

Jaa, till next.

Saturday, June 18, 2011

Code coverage in Perl

To get code coverage percentage :


/usr/perl -MDevel::Cover <perl scripts> <arguments>


The code coverage database will be stored at a directory called :


cover_db/


It will report out how many percentage hit per run. If you would like to view the total percentage hit result, you'll need to use another command :


/usr/bin/cover


This will report out the overall hit result. However, somehow I can’t' find which line of my perl scripts has not been hit to put more test for my test suite.

Example output :

----------------------------------- ------ ------ ------ ------ ------ ------
File stmt branch cond sub time total
----------------------------------- ------ ------ ------ ------ ------ ------
hello2.pl 90.9 50.0 n/a 100.0 100.0 85.7
Total 90.9 50.0 n/a 100.0 100.0 85.7
----------------------------------- ------ ------ ------ ------ ------ ------



Another way of doing this, but this doesn't report the hit in percentage, but list out how many hits on each "effective" line.


/usr/bin/perl -d:Coverage <perl scripts> <arguments>


This will store the result into a special file, no special report or output on the screen from the run is expected.


<perl scripts>.cvp


To view the result :


/usr/bin/coverperl <perl scripts>.cvp


This will list out the effective line number and how many hits on the runs that you have fired.

Example output :

3    line 5
        1    line 7
        1    line 8
        1    line 13
        1    line 15
        1    line 17
        1    line 18
        0    line 21
        1    line 24

Note :

Monday, April 11, 2011

Enable syntax highlight in vi

Open a file, then type the following commands :

:syntax on
:set syntax=verilog

The syntax files are the .vim files, you can use locate to look for it.

Example :

locate verilog.vim

In the directory, you'll see the list of syntax that your vi is supporting.

To make the syntax turn on by default to the language that you preferred, you can edit this file :

vi ~/.vimrc

Put these lines into the .vimrc file.

syntax on
set syntax=verilog

Thanks to YZ shared this tips with me December last year. :)

Wednesday, March 30, 2011

Convert string format to date format in MySQL

I was lazy to do conversion from a source to MySQL database record, thus it is in original format, stored as string. E.g : Aug 23 2010 07:00PM

Later, after a long while, I was requested to sort the query output from MySQL database, sort by the date! It is too late to do conversion, and repopulate the table, so... I found this : str_to_date.

str_to_date(`date_str`, '%b %d %Y %h:%i%p')

Example usage :

SELECT str_to_date ('Aug 23 2010 07:00PM', '%b %d %Y %h:%i%p') as date

It will return you this :

2010-08-23 19:00:00

Then you can sort the date accordingly. :)

ORDER BY str_to_date(`date_str`, '%b %d %Y %h:%i%p')

For the specifier, you can refer to http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format

Wednesday, March 9, 2011

Path comparison check in Perl

Problem statement : Checking 2 paths if they are from the same path.

In UNIX, we sometimes have softlinks to path. This has caused the path checking using pattern mathching is insufficient.

After much workarounds in my codes, finally, I found this. I just get the absolute path from the 2 given paths, then make comparison.

use Cwd 'abs_path';

if (abs_path($path1) eq abs_path($path2)) {
...
...
}

:)