CSC/ECE 517 Fall 2012/ch2b 2w39 ka: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 3: Line 3:


==Decorator Pattern==
==Decorator Pattern==
Explanation of Decorator pattern
brief overview
===Example of its Usage//change the title===
===Intent===
 
===Problem===
===Solution===
===Example===
===Implementation===
===Implementation===


Line 19: Line 21:
     type the code here
     type the code here
</pre>
</pre>
====Disadvantages====


Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
==Adapter Pattern==
brief overview
===Intent===
===Problem===
===Solution===
===Example===
===Implementation===


*<b>Performance Overhead</b>
====Ruby====
Because reflection involves types that are dynamically resolved, certain [http://en.wikipedia.org/wiki/Java_performance#Virtual_machine_optimization_techniques Java virtual machine optimizations] can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
brief explanation and Sample Code:  
 
<pre>
*<b>Security Restrictions</b>
    type the code here
Reflection requires a run-time permission which may not be present when running under a [http://en.wikipedia.org/wiki/Information_security_management security manager]. This is in an important consideration for code which has to run in a restricted security context, such as in an [http://en.wikipedia.org/wiki/Applet Applet].
</pre>
 
*<b>Exposure of Internals</b>
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy [http://en.wikipedia.org/wiki/Software_portability portability]. Reflective code, breaks [http://en.wikipedia.org/wiki/Data_abstraction abstractions] and therefore may change behavior with upgrades of the [http://en.wikipedia.org/wiki/Computing_platform platform] <ref>[http://docs.oracle.com/javase/tutorial/reflect/index.html Disadvantages of Java Reflection API]</ref>
 
===C#===
 
====Key Features====
It enables you to do simple things like:
Check the type of an object at runtime (simple calls to typeof() for example)
Inspect the Attributes of an object at runtime to change the behavior of a method (the various serialization methods in .NET)
To much more complicated tasks like:
Loading an assembly at runtime, finding a specific class, determining if it matches a given Interface, and invoking certain members dynamically.
====Advantages====
*<b>Signature Based Polymorphism</b>
[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C#] programmers are familiar with [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] based on interface inheritance. Reflection provides an alternative where we can invoke methods having same [http://en.wikipedia.org/wiki/Type_signature signature], from different classes not having a common interface.
 
*<b>Inspecting and Manipulating Classes</b>
If we need to write code that depends on class details known only at run time, then reflection comes as an easy way to proceed.
 
*<b>Creating Adaptable and Flexible Solutions</b>
It is possible to write code for [http://en.wikipedia.org/wiki/Factory_method_pattern factory design pattern] by loading classes using reflection instead of writing fixed code depending on specific static types with if-else statements inside the factory method.
 
<b>Example:</b>
To write a C# .Net program which uses reflection, the program should use the [http://en.wikipedia.org/wiki/Namespace namespace] System.Reflection.
To get type of the object, the typeof operator can be used. There is one more method GetType() which also can be used for retrieving the type information of a class. The Operator "typeof" allows us to get class name of our object and GetType() method is used to get data about object's type. Suppose we have following class:


====Java====
brief explanation and Sample Code:
<pre>
<pre>
    public class TestDataType
    type the code here
    {
</pre>
        public TestDataType()
        {
          counter = 1;
        }


        public TestDataType(int c)
==Proxy Pattern==
        {
brief overview
          counter = c;
===Intent===
        }
===Problem===
===Solution===
===Example===
===Implementation===


        private int counter;
====Ruby====
 
brief explanation and Sample Code:  
        public int Inc()
        {
          return counter++;
        }
        public int Dec()
        {
          return counter--;
        }
 
    }
</pre>
At first we should get type of object that was created. The following C# .Net code snippet shows how to do it <ref>[http://www.codersource.net/microsoft-net/c-basics-tutorials/c-net-tutorial-reflection.aspx C# Reflection]</ref>
<pre>
<pre>
TestDataType testObject = new TestDataType(15);
    type the code here
Type objectType = testObject.GetType();
</pre>
</pre>


Now objectType has all the required information about class TestDataType. We can check if our class is abstract or if it is a class. The System.Type contains a few properties to retrieve the type of the class: IsAbstract, IsClass. These functions return a Boolean value if the object is abstract or of class type. Also there are some methods that return information about constructors and methods that belong to the current type (class). It can be done in a way as it is done in next example:
====Java====
brief explanation and Sample Code:  
<pre>
<pre>
Type objectType = testObject.GetType();
    type the code here
 
ConstructorInfo [] info = objectType.GetConstructors();
MethodInfo [] methods = objectType.GetMethods();
 
// get all the constructors
Console.WriteLine("Constructors:");
foreach( ConstructorInfo cf in info )
{
  Console.WriteLine(cf);
}
 
Console.WriteLine();
// get all the methods
Console.WriteLine("Methods:");
foreach( MethodInfo mf in methods )
{
  Console.WriteLine(mf);
}
</pre>
</pre>


Now, the above program returns a list of methods and constructors of TestDataType class.
==Composite Pattern==
brief overview
===Intent===
===Problem===
===Solution===
===Example===
===Implementation===


====Disadvantages====
====Ruby====
*<b>Exposes Implementation Details</b>
brief explanation and Sample Code:  
Use of reflection exposes much of the implementation details such as the methods, fields, [http://en.wikipedia.org/wiki/Class_(computer_programming)#Member_accessibility accessibility] and other [http://en.wikipedia.org/wiki/Metadata_(CLI) metadata] of the class used.
 
*<b>Performance</b>
The code that is reflective is slow than the direct code that performs the same functionality. As reflection performance also depends on the kind of operations that are done in the code like creating objects, accessing members, making method calls, etc.
 
===Smalltalk===
Example in [http://en.wikipedia.org/wiki/Smalltalk Smalltalk]
<pre>
<pre>
w := Workspace new.
    type the code here
w openLabel:'My Workspace'
w inspect
</pre>
</pre>
Here we can inspect all the methods available to the instance 'w'.


===PHP===
====Java====
Example in [http://en.wikipedia.org/wiki/PHP PHP]<pre>
brief explanation and Sample Code:  
$reflector = new ReflectionClass("SimpleXMLElement");
<pre>
echo $reflector;
    type the code here
</pre>
</pre>
Output of this example is the complete class map of the class SimpleXMLElement.
==Comparison of Reflection in different languages==


{| class="wikitable" border="1"
{| class="wikitable" border="1"


|-
|-
! Java
! Decorator
! Ruby
! Adapter
! C#
! Proxy
! PHP
! Composite
! C++


|-
|-
| Supports Reflection
| Supports abc
| Supports Reflection
| Supports def
| Supports Reflection
| Supports ghi
| Supports Reflection
| Supports bla
| Poor support for Reflection <ref>[http://grid.cs.binghamton.edu/projects/publications/c++-HPC07/c++-HPC07.pdf Tharaka Devadithya, Kenneth Chiu, Wei Lu, <i>"Reflection for High Performance Problem Solving Environments"</i>, Computer Science Department, Indiana University, 2007]</ref>


|-
|-
| Not Powerful and flexible as Ruby Reflection
|  
| Provides powerful and flexible Reflection mechanism
|  
| Not Powerful and flexible as Ruby
|  
| Powerful and flexible
|
| Provides [http://en.wikipedia.org/wiki/Run-time_type_information RTTI ] support which provides only a very      restricted subset of reflection


|-
|-
| Uses Reflection
|  
| Ability to [http://en.wikipedia.org/wiki/Type_introspection introspect ] as it is a dynamic language
|  
| Uses Reflection
|  
| Ability to type introspect as it is a dynamic language
|
| C++ supports type introspection via the [http://en.wikipedia.org/wiki/Typeid typeid] and [http://en.wikipedia.org/wiki/Dynamic_cast dynamic_cast] keywords


|-
|-
| Variable's type determines its class and methods.
|  
| Ruby supports liberated objects(cannot tell exactly what an object can do until you look under its hood)
|  
| Variable's type determines its class and methods.
|  
| Uses Reflection class
|
| It is possible to get object run-time type only if object class contains virtual functions(using RTTI)


|-
|-
| Java Reflection API (is a bit higher level than the C# Reflection API) <ref>[http://mydov.blogspot.com/2012/05/reflection-in-java-c-but-not-in-c.html Difference between Java and C# Reflection APIs]</ref>
|  
| Ruby has a rich set of Reflection APIs
|  
| Has Reflection APIs
|  
| Has Reflection APIs
|
| Has no Reflection APIs


|}
|}

Revision as of 22:27, 16 November 2012

Introduction

Describe what Design pattern is and what are we going to discuss in this article.

Decorator Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

Adapter Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

Proxy Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

Composite Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here
Decorator Adapter Proxy Composite
Supports abc Supports def Supports ghi Supports bla

Applications of Reflection

  • Reflection has become invaluable to programmers who need to connect code with data. For example in a GUI environment, a button might need to invoke different methods in different classes. Reflection can be used here to call the method on any given class.
  • Programmers who deal with a multitude of classes at the same time can use reflection to create a serializer that for a given class uses reflection to go through all the instance variables and processes them accordingly.
  • Reflection is used in large test frameworks where reflection helps in identifying the test methods for different scenarios.
  • Reflection can be used to debug and verify code as it provides access to the insides of a program.
  • Reflection is very useful when the software is upgraded regularly. It provides an easy method to check for available methods and classes. This prevents the errors caused by the absence of methods and classes when they are deprecated.

Advantages and disadvantages of reflection

Advantages

  • Extensibility: Reflection provides the capability of using external and user defined classes by instantiation of extensibility objects using their fully qualified names.
  • Class browsers in IDEs: The ability to examine the members of classes makes implementation of visual aids , auto-completion and documentation easy in development tools for programmers.
  • Debugging: Reflection allows the user to observe the private members in classes. This capability can be used to debug classes and their interactions.
  • Test Harness: Reflection can be used to call a set of testing APIs defined on a class for maximum coverage of testing.
  • Correctness : Reflection improves the robustness and the correctness of a program especially in dynamically typed languages as run time checks can be added to check the availability of the methods or classes.

Disadvantages

  • Reflection introduces lot of performance overhead when compared to non-reflective code. Hence it should be used judiciously.
  • Since it provides access to the internals of a class or an encapsulated object security becomes a major issue.
  • Since it is run-time binding we lose the security of compile time checks and verification <ref>Analysis of Programming Languages</ref>

Conclusion

This article makes an attempt to explain the concept of Reflection in Object Oriented Programming. The article mentions the different approaches to reflection in Ruby and other languages.It mentions the usage of Reflections and the advantages and disadvantages of using Reflection. A follow up to this article would be to study the concept of Metaprogramming.

References

<references />

Additional Reading