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 35: Line 35:
     end
     end


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
 
 
===Python===
  f = open('outputfile.py', 'w')      // Open the file for writing
  f.write('#!/usr/bin/python \n')
  for i in range(1, 100):
      f.write('print' + i + '\n')      // Write the string to a file
  f.closed                            // Close the file
 
===JavaScript===
  f = fopen('outputfile.js', 3);      // Open the file for writing
  if(f!=-1) {                          // If the file has been successfully opened
      for (i=0;i<=100;i++) {
        str = 'document.write' + i;
        fwrite(f, str);                // Write the string to a file
      }
      fclose(f);                        // Close the file
  }
 
===Ruby===
  f = File.open(outputfile.rb, 'w')    // Open the file for writing
  1.upto 100 do |i|
      f.write("puts #{i}")              // Write the string to a file
  end
  f.close                              // Close the file


==Dynamic Typed Programming Languages==
==Dynamic Typed Programming Languages==
Dynamic typed programming languages are often referred to as 'weak typed' languages since it is not required for the variables to bound to a particular type at compile time instead each variable is bound to an object. Another unique characteristic of dynamic languages is that while variables need to be defined before they can be used, you don’t need to define them at the beginning of the program, just define it before its first usageThese characteristics are allowed because it is not the compiler that checks for proper variable declaration, these type errors will only occur at runtime and potentially the program will suddenly stop due to a crash.
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.  


==Metaprogramming in some Dynamic Languages==
==Metaprogramming in some Dynamic Languages==

Revision as of 02:14, 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

Dynamic 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.

Metaprogramming in some Dynamic 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.

Python

  class SomeClassThatAlreadyExists
     def some_method
        print "some code"
     end
  end

JavaScript

  SomeClassThatAlreadyExists.prototype.some_method = function () {
     document.write("some_code");
  }

Ruby

  class SomeClassThatAlreadyExists
     def some_method
        puts "some code"
     end
  end

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: