CSC/ECE 517 Fall 2012/ch1b 1w53 kc: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 37: Line 37:
This code creates a file called punishment.c with the expected 1,000+ lines of C source code
This code creates a file called punishment.c with the expected 1,000+ lines of C source code


==Dynamic Typed Programming Languages==
==Dynamically Typed Programming Languages==
Before defining what dynamic typing is, it is easiest to define its opposite. [http://www.sitepoint.com/typing-versus-dynamic-typing/ Statically typed languages] are those which define and enforce types at compile-time. Statically typed languages typically have clearly distinct compile-time and run-time phases, with program code converted by a compiler into a binary executable which is then run separately. Dynamically typed languages have distinct compilation and execution phases and therefore we  use the terms compile-time and run-time identically for both statically and dynamically typed languages. In most dynamically typed languages (e.g. Ruby, Perl, and Python) ‘running’ a file both compiles and executes it.
Before defining what dynamic typing is, it is easiest to define its opposite. [http://www.sitepoint.com/typing-versus-dynamic-typing/ Statically typed languages] are those which define and enforce types at compile-time. Statically typed languages typically have clearly distinct compile-time and run-time phases, with program code converted by a compiler into a binary executable which is then run separately. Dynamically typed languages have distinct compilation and execution phases and therefore we  use the terms compile-time and run-time identically for both statically and dynamically typed languages. In most dynamically typed languages (e.g. Ruby, Perl, and Python) ‘running’ a file both compiles and executes it.


==Metaprogramming in some Dynamic Languages==
==Metaprogramming in Dynamically Typed Languages==


We have already seen how some languages can be used for programs to write programs, now lets examine how they handle one of the other characteristics of metaprogramming:  Manipulate itself at runtime. Each of the following will take a class (SomeClassThatAlreadyExists) that was already defined and add an new method (some_method) to it.
Metaprogramming can not only be used for programs to write programs, it can also be used to manipulate itself at runtime. Let us look at some examples that do this in ruby and the equivalent code in Javascript and Python.
 
We can reopen an already existing class/prototype and add a new method to it dynamically. In ruby we reopen the class simply using the class keyword. In Javascript we grab the prototype for our object and just attach a new function.  


===Python===
===Python===
   class SomeClassThatAlreadyExists
   def battle_cry(self):
      def some_method
    print '%s says zing!!!' % self.name
        print "some code"
    Ninja.battle_cry = battle_cry
      end
  drew.battle_cry()
   end
  # => Drew says zing!!!
  adam.battle_cry()
   # => Adam says zing!!!


===JavaScript===
===JavaScript===
   SomeClassThatAlreadyExists.prototype.some_method = function () {
   Ninja.prototype.battleCry = function () {
      document.write("some_code");
    puts(this.name + " says zing!!!");
   }
   }
  drew.battleCry();
  // => Drew says zing!!!
  adam.battleCry();
  // => Adam says zing!!!


===Ruby===
===Ruby===
  class SomeClassThatAlreadyExists
  class Ninja
      def some_method
    def battle_cry
        puts "some code"
    puts "#{name} says zing!!!"
      end
    end
  end
  end
  drew.battle_cry
  # => Drew says zing!!!
  adam.battle_cry
  # => Adam says zing!!!


==Putting it all together==
==Putting it all together==

Revision as of 02:28, 28 September 2012

Metaprogramming in dynamically typed languages


Introduction

One of the most under-used programming techniques is writing programs that generate programs or program parts. Code-generating programs are sometimes called metaprograms; writing such programs is called metaprogramming. Writing programs that write code has numerous applications. In this article, we will learn why metaprogramming is necessary and look at some of the components of metaprogramming in dynamically typed languages.

What is Metaprogramming?

Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In some cases, this allows programmers to minimize the number of lines of code to express a solution (hence reducing development time), or it gives programs greater flexibility to efficiently handle new situations without recompilation. Typically, you use a metaprogram to eliminate or reduce a tedious or error-prone programming task. So, for example, instead of writing a machine code program by hand, you would use a high-level language, such as C, and then let the C compiler do the translation to the equivalent low-level machine instructions.

Metaprogramming Example

Let us consider one big main function with 1,000 printf instructions.

   #include <stdio.h>
   int main(void) {
     printf("1. I must not chat in class.\n");
     printf("2. I must not chat in class.\n");
     /* 996 printf instructions omitted. */
     printf("999. I must not chat in class.\n");
     printf("1000. I must not chat in class.\n");
     return 0;
   }

Taking the above pseudo code example, we can see how that can be made much simpler and elegant using a metaprogram in Ruby.

   File.open('punishment.c', 'w') do |output|
     output.puts '#include <stdio.h>'
     output.puts 'int main(void) {'
   1.upto(1000) do |i|
     output.puts "    printf(\"#{i}. " +
     "I must not chat in class.\\n\");"
   end
     output.puts '    return 0;'
     output.puts '}'
   end

This code creates a file called punishment.c with the expected 1,000+ lines of C source code

Dynamically Typed Programming Languages

Before defining what dynamic typing is, it is easiest to define its opposite. Statically typed languages are those which define and enforce types at compile-time. Statically typed languages typically have clearly distinct compile-time and run-time phases, with program code converted by a compiler into a binary executable which is then run separately. Dynamically typed languages have distinct compilation and execution phases and therefore we use the terms compile-time and run-time identically for both statically and dynamically typed languages. In most dynamically typed languages (e.g. Ruby, Perl, and Python) ‘running’ a file both compiles and executes it.

Metaprogramming in Dynamically Typed Languages

Metaprogramming can not only be used for programs to write programs, it can also be used to manipulate itself at runtime. Let us look at some examples that do this in ruby and the equivalent code in Javascript and Python.

We can reopen an already existing class/prototype and add a new method to it dynamically. In ruby we reopen the class simply using the class keyword. In Javascript we grab the prototype for our object and just attach a new function.

Python

  def battle_cry(self):
   print '%s says zing!!!' % self.name
   Ninja.battle_cry = battle_cry
  drew.battle_cry()
  # => Drew says zing!!!
  adam.battle_cry()
  # => Adam says zing!!!

JavaScript

  Ninja.prototype.battleCry = function () {
   puts(this.name + " says zing!!!");
  }
  drew.battleCry();
  // => Drew says zing!!!
  adam.battleCry();
  // => Adam says zing!!!

Ruby

 class Ninja
   def battle_cry
   puts "#{name} says zing!!!"
   end
 end
 drew.battle_cry
 # => Drew says zing!!!
 adam.battle_cry
 # => Adam says zing!!!

Putting it all together

How does metaprogamming work with dynamic typed languages?

  • Interpreted Languages

Most dynamic languages are interpreted, not compiled. The basic idea here is for the code to be interpreted at run-time, allows generic objects to dynamically interact with each other. This interaction in itself is potentially manipulating the behavior of the program as it is executing. Generic objects are not the only uniqueness of an interpreted language, the 'eval' statement is something else to consider. The ability to evaluate an expression via the 'eval' statement allows for the program to redefine functions at run-time. These two capabilities for dynamic languages have become immensely valuable to programmers.

  • Dynamic methods

These types of methods are very flexible. The program have have an object created from a class, then you can add additional methods to the instance of that class. Therefore manipulating the program at run time by allowing for only this instance of the object to have additional methods. Not to be confused with extending classes or adding additional methods to classes.

  • Singletons classes

Singleton classes should not be mistake for the Singleton design pattern. These types of classes available in some dynamic languages allow for dynamic dispatching. An common technique often used on singleton classes is to add dynamic methods to the instance.

  • "Everything is an object"

Many languages a 'weak-typed' which means that potentially anything can be anything else. The most obvious way to have this behavior is by making everything an object. What historically are considered primitive data types now are all considered objects (e.g. string, integers, etc). In some of these languages even functions and procedures are considered objects. In some languages such as Ruby, even classes are Objects since they (as well as everything else) inherits from Object. Since classes can be used to define, extend, or redefine other classes (often referred to as a metaclass) this is also potentially changing the behavior of the original program.

Some other traits of some common dynamic languages worth mentioning are: the use of method_missing, introspection, lazy loading, declarative code, extensible type system, and method aliasing.

Conclusion

Dynamic languages are increasingly recognized for playing a major role in software development, specifically for quick prototyping because of the forgiveness of the languages letting requirements evolve. These languages are historically looked at as scripting languages that are inexpensive and not scalable. Allowing for these types of behavior comes at a price. The price is the potential for poor performance since the code is runtime optimized. Another downfall is that rapid development is great but the flexibility allowed between type conversions means that there is a higher probability for runtime errors. While understanding these limitation and accepting the risks, these languages can be very powerful specifically in the area of Metaprogramming.

What’s Next?

In the next article for which the link does not exist yet, we will look at static-analysis tools for Ruby.

References

Websites:

Books/Articles: