Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Monday, December 29, 2008

GoF Design Patterns [5]

Adapter


Decorator


Visitor




(will be updated on demand)

Sunday, December 28, 2008

PureMVC framework notes

PureMVC is a lightweight framework for creating applications based upon the classic Model, View and Controller concept; based upon proven design patterns



This free, open source framework which was originally implemented in the ActionScript 3 language for use with Adobe Flex, Flash and AIR, has now been ported to nearly all major development platforms. It seems PureMVC is more popular in other languages (Java, C#, Ruby, ... ) than its competitor (Cairgorm) .





(to be updated)

Wednesday, December 24, 2008

GoF Design Patterns [4]

Abstract Factory

Proxy

Mediator





(will be updated on demand)

Saturday, December 20, 2008

GoF Design Patterns [3]

Tiếp tục với những design patterns dễ gặp:


Factory Method (creational)

Facade (structural)

Observer (behavioural)





(will be updated on demand)

Wednesday, December 17, 2008

GoF Design Patterns [2]

Hãy bắt đầu bằng những Design Pattern đơn giản và dễ gặp nhất :-) .




Singleton (creational)

Bridge (structural)

Command (behavioural)



(will be updated on demand)

Sunday, December 14, 2008

GoF Design Patterns

Có lẽ không cần giới thiệu nhiều về Design Patterns (Mẫu Thiết kế), cũng như quyển sách kinh điển của Gang of Four (Bộ Tứ - a.k.a Bè lũ 4 tên) vì bây giờ đã quá nổi tiếng rồi.

Việc nắm được các Design Patterns ngoài việc cải thiện tư duy hướng đối tượng, nó giúp dự án nhanh chóng có được thiết kế tốt, vì thế reduce cost & development interval, đồng thời improve productivity & customer satisfaction. Đối với bản thân developer thì ít ra cũng hấp dẫn ở chỗ là có thể làm thay đổi đáng kể mức lương :D .
Do đó bạn nào muốn tìm hiểu kỹ hơn thì nên nghiền ngẫm sách và code nhiều vào, chứ các bài blog như bài này chỉ nêu như cưỡi ngựa xem hoa thôi :D


Trong sách DP của GoF, 23 mẫu được phân thành 3 categories là: Creational (khởi tạo) - 5 mẫu , Structural (cấu trúc) - 7 mẫu, và Behavioural (hành vi) - 11 mẫu còn lại .

Tuy nhiên theo tớ thì không nên tiếp cận các DP the thứ tự tên ABC, hoặc theo từng category như trên, mà nên tiếp cận theo 1 trong 2 hướng: hoặc là dễ hiểu nhất, hoặc là dễ gặp nhất.
Ngoài ra không nên chạy theo các "xxx Design Patterns" khác (VD: Enterprise), vì đa số các pattern dạng này thuộc loại bùng nổ, hầu như cái gì cũng quơ vào làm pattern, hiệu quả thực tế chẳng bao nhiêu mà còn dễ dẫn đến "tẩu hỏa nhập ma" :D .


=== Creational DP ===


C. Singleton

Ensure a class only has one instance, and provide a global point of access to it.



C. Factory Method

Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.



C. Abstract Factory

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.



C. Prototype

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.



C. Builder

Separate the construction of a complex object from its representation so that the same construction processes can create different representations.



=== Structural DP ===


S. Bridge

Decouple an abstraction from its implementation so that the two can vary independently.



S. Facade

Provide a unified interface to a set of interfaces in a system. Façade defines a higher-level interface that makes the subsystem easier to use.



S. Adapter

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatibility interfaces.



S. Decorator:

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.



S. Proxy

Provide a surrogate or placeholder for another object to control access to it.



S. Composite

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.



S. Flyweight

Use sharing to support large numbers of fine-grained objects efficiently. A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context; it’s indistinguishable from an instance of the object that’s not shared.



=== Behavioural DP ===


B. Strategy:

Defines a family of algorithms, encapsulates each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients who use it.



B. Chain of Responsibility

Avoid coupling the sender of a request to its receiver by giving more then one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.



B. Template Method

Define a skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.



B. Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.



B. Command

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.



S. Observer

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.



B. Mediator

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently.



B. State

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.



B. Interpreter

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.



B. Memento

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.



B. Visitor

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.



( từ từ tớ sẽ giới thiệu cụ thể từng cái pattern sau... nếu có thời gian :D )

Sunday, November 23, 2008

Object-oriented programming principles

Sau khi đã biết được các nguyên lý cơ bản để phát triển phần mềm, một lập trình viên nên biết qua về các nguyên lý lập trình hướng đối tượng.

Một số bạn thì gọi cái này là các nguyên tắc thiết kế hướng đối tượng (OOD principles) . Theo tôi thì gọi như vậy là không chính xác. Các nguyên tắc OO này áp dụng cho lập trình (programming), từ thiết kế (design) đến viết mã (coding) đến kiểm thử (testing) , đều cần biết các nguyên tắc này và nên áp dụng ở từng giai đoạn luôn chứ không chỉ ở giai đoạn design.

Nói một cách ví von, so với cờ thì: các nguyên lý KISS, DRY, YAGNI,... là các thế tàn cuộc cơ bản, các nguyên lý OOP là các cách chơi trung cuộc, còn như Design Patterns thì là các kiểu khai cuộc . Mặc dù ngày nay Design Patterns được nhắc đến nhiều nhưng thực sự thì để nâng cao nội lực thì nên nắm vững OOP principles , còn DP thì ban đầu chỉ cần biết một ít đủ để áp dụng OOP là được.


Trong vài bài post sau này chúng ta sẽ thảo luận về Design Patterns , còn bây giờ tôi sẽ nêu 4 nguyên lý OOP cơ bản :

1/ Nguyên lý đóng mở - OCP : (open close principle)
Open for extension, but closed for modification.

Tạm dịch: Dễ mở rộng các hành vi, mà không cần phải sửa lại (class/interface/method)


2/ Nguyên lý thay thế Liskov - LSP : (Liskov substitute principle)
Derived classes must be substitutable for their base classes.

Tạm dịch: Các lớp dẫn xuất phải có khả năng thay thế hẳn lớp cơ sở


3/ Nguyên lý nghịch đảo phụ thuộc - DIP : (dependency inversion principle)
Depend on abstractions, not on concretions.

Tạm dịch: Nên phụ thuộc ở mức trừu tượng, tránh phụ thuộc cụ thể


4/ Nguyên lý phân tách giao diện - ISP : (interface segregation principle)
Make fine grained interfaces that are client specific.

Tạm dịch: Tạo các interfaces đã lọc kỹ và hướng tới người dùng


4 revisited/ Nguyên lý trách nhiệm đơn định - SRP: (single responsibility principle)
(Cái này là 1 góc nhìn khác của ISP, nếu bạn thích gọi là nguyên lý 5 thì cũng không sai mấy)
A class should have one, and only one, reason to change.

Tạm dịch: Khi thay đổi, mỗi lớp chỉ nên có 1 và chỉ 1 lý do



Ngoài ra còn các nguyên lý về phân gói (package), chia làm 2 nhóm:
+ tăng độ kết dính (increase cohesion) : REP, CCP, CRP
+ giảm độ ghép cặp (decrease coupling) : ADP, SDP, SAP

Tuy nhiên nên nắm vững 4 nguyên lý cơ bản ở trên trước khi tìm hiểu các nguyên lý về package & granuality .

Sunday, October 12, 2008

Tips for Unit Test

Today, I would like to recommend 12 tips for Unit Testing to every developer :) .
(A good case study for Unit Test is the Craftsman story, you can read the Vietnamese translation here: http://diendantinhoc.net/?cat=se_craftsman )



Unit Testing is one of the pillars of Agile Software Development. First introduced by Kent Beck, unit testing has found its way into the hearts and systems of many organizations. Unit tests help engineers reduce the number of bugs, hours spent on debugging, and contribute to healthier, more stable software.

In this post we look at a dozen unit testing tips that software engineers can apply, regardless of their programming language or environment.



1/ Unit Test to Manage Your Risk


2/ Write a Test Case Per Major Component


3/ Create Abstract Test Case and Test Utilities


4/ Write Smart Tests


5/ Set up Clean Environment for Each Test


6/ Use Mock Objects To Test Effectively


7/ Refactor Tests When You Refactor the Code


8/ Write Tests Before Fixing a Bug


9/ Use Unit Tests to Ensure Performance


10/ Create Tests for Concurrent Code


11/ Run Tests Continuously


12/ Have Fun Testing!


Probably the most important tip is to have fun. When I first encountered unit testing, I was sceptical and thought it was just extra work. But I gave it a chance, because smart people who I trusted told me that it's very useful.

Unit testing puts your brain into a state which is very different from coding state. It is challenging to think about what is a simple and correct set of tests for this given component.

Once you start writing tests, you'd wonder how you ever got by without them. To make tests even more fun, you can incorporate pair programming. Whether you get together with fellow engineers to write tests or write tests for each other's code, fun is guaranteed. At the end of the day, you will be comfortable knowing your system really works because your tests pass.



(Full credit of this article belongs to Alex Iskold and ReadWriteWeb)

(^o^)

Wednesday, October 08, 2008

Quick Java quiz

Tuần trước có vào đọc thấy bài Quiz ở blog Weiqi Gao, cũng hay hay, show cho bà con xem:

Q: Compile, or no compile?

public class Foo {
public static void main(String[] args) {
Integer Object = new Integer(1024);
Object Integer = Object;
System.out.println(Integer);
}
}


Kết quả chạy thử thì Compile được, không có vấn đề gì.


Kết luận: Các tên lớp (Ojbect, Integer, ...) không phải là từ dành riêng (reserved word) trong Java, vì thế ta có thể đặt làm tên biến như bình thường, biên dịch không báo lỗi.


Còn bây giờ là 1 bài Quiz khác cho các bạn :-)

/* Given the following code what is the effect of a being 5: */

public class Test {
public void add(int a) {
loop: for (int i = 1; i < 3; i++) {
for (int j = 1; j < 3; j++) {
if (a == 5) {
break loop;
}
System.out.println(i * j);
}
}
}
}

Chọn lựa:

A. Generate a runtime error
B. Throw an out of bounds exception
C. Print the values: 1, 2, 2, 4
D. Produces no output


Your choice?

Sunday, October 05, 2008

Software development principles

A good software, in the developer POV, should satisfy below criteria:

* FUNCTIONAL (as specified, with reasonable resource) : of course, trivial assumption.

* REUSABLE : currently the most notable criteria, which is the father of OOP and RAD.

* EXTENSIBLE : the brother of "reusable", in other words, it's the good side of "flexible" (the bad side is "modifiable/shrinkable" which requires more efforts).

* RELIABLE : even when the software is run in non-specified conditions, it should not lead to system crash/hanging/exploitation, and should produce the most accurate result, while giving the user some warning/caution.


Hence, the pragmatic software development, after LOTS of failed projects, has proven some paradigms to achieve the above criteria in a predictable way. That's why we have now programming philosophies, conventions, OOP, OOAD, principles, and also a bunch of design patterns.


And here are my notes about some useful development principles:

* KISS: Keep It Simple, Stupid (làm đơn giản thôi, lũ ngốc)
This is not only useful in software development, but also in a wide array of disciplines, such as animation, journalism, photography, engineering, and strategic planning. As Einstein's maxim: "everything should be made as simple as possible, but no simpler." .
Surprisingly, there are numerous so-called developers who forget this principle in serious development.


* DRW: Don't Reinvent Wheels (đừng có phát minh lại cái bánh xe)
This is also a general principle for gaining solutions in shorter time. It is emphasized in software development in which the human cost, which is highest part of software TCO, is proportional to development time and maintenance efforts. If there is a good solution we can get, just take it instead of creating a new solution from scratch, that's the economical way.


* DRY: Don't Repeat Yourself (đừng lặp lại cái đã làm rồi)
This principle is about re-use, not about re-invent. Yet it is similar in the economical sense. When re-use some components, we should avoid duplicated information as much as possible, because duplication increases the difficulty of change, may decrease clarity, and leads to opportunities for inconsistency.


* YAGNI: You Ain't Gonna Need It (còn lâu mới cần đến chức năng đó)
After some experience in programming, a developer usually impose himself on foreseeing unspecified usage and preparing for changing requests. Some even go further by adding functionality (without any request), which usually turns out to break the rate of process. Therefore a developer, though is encouraged to think out of the box, should only implement things when he actually need them, never when he just foresee that he need them.



Well, let's call it a day.
Design principles and design patterns will be mentioned in next entries .

(^o^)