CSC/ECE 517 Fall 2009/wiki2 13 StaticDynamic: Difference between revisions
Line 95: | Line 95: | ||
To illustrate, I'll examine some patterns often used with Objective-C, but not usually used (or used differently) with C++. Both languages are object-oriented extensions of C. The main difference between them is that C++ has compile-time binding and fairly strong typing while Objective-C uses the Smalltalk object model of dynamic binding and weak typing. I'll start by examining two idioms commonly found in Objective-C programming. While simple, these idioms illustrate some of the key Objective-C programming techniques (although I use NextStep classes and frameworks to illustrate points, what I say also holds true for more generic Objective-C environments). I'll also examine how three standard design patterns -- Visitor, Command, and Facade -- are implemented in Objective-C. | To illustrate, I'll examine some patterns often used with Objective-C, but not usually used (or used differently) with C++. Both languages are object-oriented extensions of C. The main difference between them is that C++ has compile-time binding and fairly strong typing while Objective-C uses the Smalltalk object model of dynamic binding and weak typing. I'll start by examining two idioms commonly found in Objective-C programming. While simple, these idioms illustrate some of the key Objective-C programming techniques (although I use NextStep classes and frameworks to illustrate points, what I say also holds true for more generic Objective-C environments). I'll also examine how three standard design patterns -- Visitor, Command, and Facade -- are implemented in Objective-C. | ||
==== | ====Objective- C Idiom 1==== | ||
Use Weakly Typed Delegation to Implement Secondary Roles of Framework Objects. A framework is a set of objects designed to help users create a specific type of application or a specific part of an application. For most problem domains, there is a set of core abstractions that are independent of the framework. For example, consider a framework that helps you create a GUI. Almost every such framework includes an "Application" object. In NextStep and it is an Application, in Delphi's VCL it is TApplication, but the basic abstraction is the same. Similarly, all such frameworks contain some form of "Window," "Subview," "Button," and "Textfield." These framework objects are often the leaves on the framework's object graph. | |||
Framework objects have a clearly defined role within any application. Application objects route events, and Window objects provide a place to draw. However, programmers often subclass objects to allow them to play a secondary role within an application. For example, Textfields are often subclassed within an application, giving them the ability to validate user input. | |||
Standard object-oriented design principles suggest that secondary roles be implemented via the Strategy pattern. Since frameworks are usually developed separately and implemented as shared libraries, using a strongly typed language results in Figure 1. However, Figure 1 can cause problems over the application life cycle. NextStep's Application object, for example, acquired nine new delegate methods between versions 2.0 and 3.3 of the framework. These were gradual modifications brought about by changes in how people use computers, as well as changes made to remedy oversights in the original design. In Figure 1, each of these changes would have required a recompilation of the application and a new release. Moreover, existing copies of the application installed on users' machines would need to be updated. | |||
One solution to this problem is to implement a strict versioning system. For example, the Windows machine I use has three distinct versions of MSVCRT**.DLL, and five versions of MFC**.DLL. If I try to launch my copy of Visual Eiffel, an alert dialog tells me I have the wrong version of CT13D32.DLL. | |||
At best, strict versioning is a stop-gap solution. Depending on my applications, I might load all five versions of MFC**.DLL into memory, defeating the point of shared libraries. Additionally, older applications won't automatically inherit new functionality (or have bugs repaired) -- they still use the older version of the framework. Moreover, minor updates to an application can become complex; if you want to use a feature found in the new version of the framework, you must update every object that depends on the framework (including all the strategy objects). | |||
The Objective-C approach removes the abstract base class, giving the framework object a more complex setDelegate method. The framework object defines a set of strategic methods it will call if they are defined. Then, inside the setDelegate method, run-time type information (RTTI) determines which methods the delegate has implemented. If the delegate doesn't implement the strategic method, the framework object doesn't call it. This is illustrated in Listing One where the new delegate object is queried about each function. If the new delegate implements the function, the method pointer is obtained. | |||
This approach eliminates the versioning problem -- older applications work with new frameworks. For example, most applications compiled under NextStep 2.0 can run using the shared libraries of NextStep 3.3. If the application needs to be updated to take advantage of a new feature in the framework, the necessary code change is minimal because only the object getting updated needs to be modified. | |||
The essence of this idiom is the principle that the framework and application should evolve independently. It is not easy to see how to do this in a statically typed language. | |||
== Conclusion == | == Conclusion == |
Revision as of 01:53, 9 October 2009
Design Patterns from a Static/Dynamic Point of View
Clearly, Ruby offers more concise realizations of certain design patterns than Java does. Is this typical of dynamic o-o languages? Are there design patterns that any dynamically typed language can realize better than a statically typed language? Are there instances when a different pattern should be used in a dynamic language than a static language?
Introduction
Design Pattern
A design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.
[1]
Name | Description |
---|---|
Creational Patterns | |
Abstract Factory | Creates an instance of several families of classes |
Builder | Separates object construction from its representation |
Factory Method | Creates an instance of several derived classes |
Prototype | A fully initialized instance to be copied or cloned |
Singleton | A class of which only a single instance can exist |
Structural Patterns | |
Adapter | Match interfaces of different classes |
Bridge | Separates an object’s interface from its implementation |
Composite | A tree structure of simple and composite objects |
Decorator | Add responsibilities to objects dynamically |
Facade | A single class that represents an entire subsystem |
Flyweight | A fine-grained instance used for efficient sharing |
Proxy | An object representing another object |
Behavioral Patterns | |
Chain of Resp. | A way of passing a request between a chain of objects |
Command | Encapsulate a command request as an object |
Interpreter | A way to include language elements in a program |
Iterator | Sequentially access the elements of a collection |
Mediator | Defines simplified communication between classes |
Memento | Capture and restore an object's internal state |
Observer | A way of notifying change to a number of classes |
State | Alter an object's behavior when its state changes |
Strategy | Encapsulates an algorithm inside a class |
Template Method | Defer the exact steps of an algorithm to a subclass |
Visitor | Defines a new operation to a class without change |
Static/Dynamic Type Languages
Types usually have associations either with values in memory or with objects such as variables. Because any value simply consists of a sequence of bits in a computer, hardware makes no distinction even between memory addresses, instruction code, characters, integers and floating-point numbers. Assignment to a type informs programs and programmers how those bit collections should be treated.
Major functions provided by type systems include:
- Safety - Use of types may allow a compiler to detect meaningless or probably invalid code. For example, we can identify an expression "Hello, World" as invalid because the rules of arithmetic do not specify how to divide an integer by a string. As discussed below, strong typing offers more safety, but generally does not guarantee complete safety (see type-safety for more information).
- Optimization - Static type-checking may provide useful compile-time information. For example, if a type requires that a value must align in memory at a multiple of 4 bytes, the compiler may be able to use more efficient machine instructions.
- Documentation - In more expressive type systems, types can serve as a form of documentation, since they can illustrate the intent of the programmer. For instance, timestamps may be represented as integers—but if a programmer declares a function as returning a timestamp type rather than merely an integer type, this documents part of the meaning of the function.
- Abstraction (or modularity) - Types allow programmers to think about programs at a higher level than the bit or byte, not bothering with low-level implementation. For example, programmers can think of a string as a collection of character values instead of as a mere array of bytes. Or, types can allow programmers to express the interface between two subsystems. This helps localize the definitions required for interoperability of the subsystems and prevents inconsistencies when those subsystems communicate.
Static Type Languages
A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.
C++, C#, Java
Dynamic Type Languages
A programming language is said to be dynamically typed, or just 'dynamic', when the majority of its type checking is performed at run-time as opposed to at compile-time.
Ruby, Python
Example
[2] Many software designers view patterns as a form of language-independent design. Pattern-Oriented Software Architectures: A System of Patterns, edited by Frank Buschmann (John Wiley & Sons, 1996), for instance, divides patterns into three main groups -- architectural patterns, design patterns, and idioms. Only the idioms (defined as "low-level patterns specific to a program language") are language dependent -- the other patterns (and the implicit pattern language) rise above the level of programming language, much as the unified modeling language (UML) provides a common way to express designs.
This idea of language independence is seductive. It is also misleading. While patterns are language independent, language choice limits the patterns that are possible, easily supported, and useful. Language also affects how applications are structured.
To illustrate, I'll examine some patterns often used with Objective-C, but not usually used (or used differently) with C++. Both languages are object-oriented extensions of C. The main difference between them is that C++ has compile-time binding and fairly strong typing while Objective-C uses the Smalltalk object model of dynamic binding and weak typing. I'll start by examining two idioms commonly found in Objective-C programming. While simple, these idioms illustrate some of the key Objective-C programming techniques (although I use NextStep classes and frameworks to illustrate points, what I say also holds true for more generic Objective-C environments). I'll also examine how three standard design patterns -- Visitor, Command, and Facade -- are implemented in Objective-C.
Objective- C Idiom 1
Use Weakly Typed Delegation to Implement Secondary Roles of Framework Objects. A framework is a set of objects designed to help users create a specific type of application or a specific part of an application. For most problem domains, there is a set of core abstractions that are independent of the framework. For example, consider a framework that helps you create a GUI. Almost every such framework includes an "Application" object. In NextStep and it is an Application, in Delphi's VCL it is TApplication, but the basic abstraction is the same. Similarly, all such frameworks contain some form of "Window," "Subview," "Button," and "Textfield." These framework objects are often the leaves on the framework's object graph.
Framework objects have a clearly defined role within any application. Application objects route events, and Window objects provide a place to draw. However, programmers often subclass objects to allow them to play a secondary role within an application. For example, Textfields are often subclassed within an application, giving them the ability to validate user input.
Standard object-oriented design principles suggest that secondary roles be implemented via the Strategy pattern. Since frameworks are usually developed separately and implemented as shared libraries, using a strongly typed language results in Figure 1. However, Figure 1 can cause problems over the application life cycle. NextStep's Application object, for example, acquired nine new delegate methods between versions 2.0 and 3.3 of the framework. These were gradual modifications brought about by changes in how people use computers, as well as changes made to remedy oversights in the original design. In Figure 1, each of these changes would have required a recompilation of the application and a new release. Moreover, existing copies of the application installed on users' machines would need to be updated.
One solution to this problem is to implement a strict versioning system. For example, the Windows machine I use has three distinct versions of MSVCRT**.DLL, and five versions of MFC**.DLL. If I try to launch my copy of Visual Eiffel, an alert dialog tells me I have the wrong version of CT13D32.DLL.
At best, strict versioning is a stop-gap solution. Depending on my applications, I might load all five versions of MFC**.DLL into memory, defeating the point of shared libraries. Additionally, older applications won't automatically inherit new functionality (or have bugs repaired) -- they still use the older version of the framework. Moreover, minor updates to an application can become complex; if you want to use a feature found in the new version of the framework, you must update every object that depends on the framework (including all the strategy objects).
The Objective-C approach removes the abstract base class, giving the framework object a more complex setDelegate method. The framework object defines a set of strategic methods it will call if they are defined. Then, inside the setDelegate method, run-time type information (RTTI) determines which methods the delegate has implemented. If the delegate doesn't implement the strategic method, the framework object doesn't call it. This is illustrated in Listing One where the new delegate object is queried about each function. If the new delegate implements the function, the method pointer is obtained.
This approach eliminates the versioning problem -- older applications work with new frameworks. For example, most applications compiled under NextStep 2.0 can run using the shared libraries of NextStep 3.3. If the application needs to be updated to take advantage of a new feature in the framework, the necessary code change is minimal because only the object getting updated needs to be modified.
The essence of this idiom is the principle that the framework and application should evolve independently. It is not easy to see how to do this in a statically typed language.
Conclusion
There are various levels of design recognition for generating repeatable solutions to commonly occurring programming problems in software design. Design patterns in this case have been met with criticism in whether it negates the agile product development process. From our example above we have shown that when implementing patterns across various languages of varying type systems a design pattern may not always resolve common problems efficiently. Thus, the idea of a language independent pattern recognition solution must be evaluated thoroughly when in considering from a static and dynamic point of view.