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

From Expertiza_Wiki
Jump to navigation Jump to search
(Created page with "<p>A brief introduction to your article. The table of contents, which is generated automatically, will show up just below this introduction.</p> = Introduction= <p><ref>http://...")
 
No edit summary
Line 1: Line 1:
<p>A brief introduction to your article. The table of contents, which is generated automatically, will show up just below this introduction.</p>
==Introduction==
Describe what Design pattern is and what are we going to discuss in this article.


= Introduction=
==Decorator Pattern==
<p><ref>http://en.wikipedia.org/wiki/Citing_sources Wikipedia's Article on Citing Sources</ref>.</p>
Explanation of Decorator pattern
===Example of its Usage//change the title===


<p>For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].</p>
===Implementation===


= Section 1 =
====Ruby====
<p>Development of the concept your article describes can be created in sections and subsections.</p>
brief explanation and Sample Code:
<pre>
    type the code here
</pre>


== Section 1, Subsection 1 ==
====Java====
<p>This is a subsection of section 1.  Obviously, you name each of your sections and subsections as appropriate for your article.</p>
brief explanation and Sample Code:
<pre>
    type the code here
</pre>
====Disadvantages====


== Section 1, Subsection 2 ==
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.
<p>Like an outline, you shouldn't have a single section or subsection. Your subsections can go many levels deep!</p>


= Section 2 =
*<b>Performance Overhead</b>
<p>Another section for your article.</p>
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.


= Section N =
*<b>Security Restrictions</b>
<p>Create as many sections and subsections as necessary to support your article.
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].


= Conclusion/Summary =
*<b>Exposure of Internals</b>
<p>Articles generally end with a conclusion or summary section.</p>
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>


= Definitions =
===C#===
<p>For any definitions where you don't have inline hypertext links to the definition you can place the definition of those terms here.</p>


= References =
====Key Features====
<p>Your references go here.  You should allow the WIKI to create your references list automatically by using inline citations.</p>
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:
<pre>
    public class TestDataType
    {
        public TestDataType()
        {
          counter = 1;
        }
        public TestDataType(int c)
        {
          counter = c;
        }
        private int counter;
        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>
TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();
</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:
<pre>
Type objectType = testObject.GetType();
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>
Now, the above program returns a list of methods and constructors of TestDataType class.
====Disadvantages====
*<b>Exposes Implementation Details</b>
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>
w := Workspace new.
w openLabel:'My Workspace'
w inspect
</pre>
Here we can inspect all the methods available to the instance 'w'.
===PHP===
Example in [http://en.wikipedia.org/wiki/PHP PHP]<pre>
$reflector = new ReflectionClass("SimpleXMLElement");
echo $reflector;
</pre>
Output of this example is the complete class map of the class SimpleXMLElement.
==Comparison of Reflection in different languages==
{| class="wikitable" border="1"
|-
! Java
! Ruby
! C#
! PHP
! C++
|-
| Supports Reflection
| Supports Reflection
| Supports Reflection
| Supports Reflection
| 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
|}
==Applications of Reflection==
*Reflection has become invaluable to programmers who need to connect code with data. For example in a [http://en.wikipedia.org/wiki/Graphical_user_interface 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 [http://en.wikipedia.org/wiki/Serializer 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 [http://en.wikipedia.org/wiki/Test_method test methods] for different scenarios.
*Reflection provides the ability to [http://en.wikipedia.org/wiki/Code_morphing morph the code] based on dynamic situations. This provides a sense of [http://en.wikipedia.org/wiki/Artificial_intelligence artificial intelligence] to the program as whole.
*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===
* <b>Extensibility:</b> Reflection provides the capability of using external and user defined classes by instantiation of extensibility objects using their fully qualified names.
* <b>Class browsers in [http://en.wikipedia.org/wiki/IDE IDEs]:</b> The ability to examine the members of classes makes implementation of visual aids , [http://en.wikipedia.org/wiki/Autocomplete auto-completion] and [http://en.wikipedia.org/wiki/Software_documentation documentation] easy in development tools for programmers.
* <b>[http://en.wikipedia.org/wiki/Debugging Debugging]:</b> Reflection allows the user to observe the private members in classes. This capability can be used to debug classes and their interactions.
* <b>[http://en.wikipedia.org/wiki/Test_harness Test Harness]:</b> Reflection can be used to call a set of testing APIs defined on a class for maximum coverage of testing.
* <b>Correctness</b> : 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>[https://docs.google.com/a/ncsu.edu/viewer?a=v&q=cache:bnm9xJhl8EkJ:www.ics.uci.edu/~lopes/teaching/inf212W12/lectures/INF212-Reflection.pptx+reflection+analysis+over+ruby+java+c%23&hl=en&gl=us&pid=bl&srcid=ADGEESgNhIwaccNOPEKsCXmB8wZYIb4ZkP7HfShvDyrJOrI2z1Octe68TIM-DszvvTM5MZdFcJkT5NV5cSHrkxNICJya-VcIfqB22M2AvoBT5KmpvNV3lwUfhOgSKEGBu0gqtxJOK-aq&sig=AHIEtbTsPbOfryUJKCgMqZ6W2wbA522bCQ 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 [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming].
==References==
<references />
<references />
==Additional Reading==
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]

Revision as of 22:21, 16 November 2012

Introduction

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

Decorator Pattern

Explanation of Decorator pattern

Example of its Usage//change the title

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

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.

  • Performance Overhead

Because reflection involves types that are dynamically resolved, certain 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.

  • Security Restrictions

Reflection requires a run-time permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

  • Exposure of Internals

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 portability. Reflective code, breaks abstractions and therefore may change behavior with upgrades of the platform <ref>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

  • Signature Based Polymorphism

C# programmers are familiar with polymorphism based on interface inheritance. Reflection provides an alternative where we can invoke methods having same signature, from different classes not having a common interface.

  • Inspecting and Manipulating Classes

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.

  • Creating Adaptable and Flexible Solutions

It is possible to write code for 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.

Example:

To write a C# .Net program which uses reflection, the program should use the 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:

    public class TestDataType
    {
        public TestDataType()
        {
           counter = 1;
        }

        public TestDataType(int c)
        {
           counter = c;
        }

        private int counter;

        public int Inc()
        {
           return counter++;
        }
        public int Dec()
        {
           return counter--;
        }

    } 

At first we should get type of object that was created. The following C# .Net code snippet shows how to do it <ref>C# Reflection</ref>

	TestDataType testObject = new TestDataType(15);
	Type objectType = testObject.GetType();

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:

	Type objectType = testObject.GetType();

	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);
	}

Now, the above program returns a list of methods and constructors of TestDataType class.

Disadvantages

  • Exposes Implementation Details

Use of reflection exposes much of the implementation details such as the methods, fields, accessibility and other metadata of the class used.

  • Performance

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 Smalltalk

w := Workspace new.
w openLabel:'My Workspace'
w inspect

Here we can inspect all the methods available to the instance 'w'.

PHP

Example in PHP

$reflector = new ReflectionClass("SimpleXMLElement"); 
echo $reflector;

Output of this example is the complete class map of the class SimpleXMLElement.

Comparison of Reflection in different languages

Java Ruby C# PHP C++
Supports Reflection Supports Reflection Supports Reflection Supports Reflection Poor support for Reflection <ref>Tharaka Devadithya, Kenneth Chiu, Wei Lu, "Reflection for High Performance Problem Solving Environments", 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 RTTI support which provides only a very restricted subset of reflection
Uses Reflection Ability to 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 typeid and 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>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

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