CSC/ECE 517 Fall 2009/wiki1b 2 sk

From Expertiza_Wiki
Jump to navigation Jump to search

Advantages Of Statically Typed vs. Dynamically Typed Languages

Introduction

Dynamically Typed Languages

Dynamically typed languages are those in which type checking is done at run-time. In other words, the same entity does not always have the same form during the execution of the program and the type of the object assigned to a variable can be changed at run-time. Variable need not be defined before they are used. Some examples of dynamically typed languages are Ruby, Python, PHP, Smalltalk, Lisp, Prolog, JavaScript, Objective-C. Lisp and Smalltalk were not quite success, but both had a huge influence on later languages- including many statically typed languages and both are used till today. They form important history of dynamically typed languages.
/* Ruby code sample */
a = [1, 2, 3, 4, "Hi"]

The above code declares array that holds mix of integer and string types. Note that there was no need to specify array type and this would be evaluated automatically during run-time. However such a declaration is not possible in statically typed language like C, C++, Java, etc. doing so would give compile time errors.

Statically Typed Languages

Statically typed languages are those in which type checking is performed during compile-time as opposed to run-time. In static typing, all expressions have their types determined prior to the program being run (typically at compile-time). For example, 1 and (2+2) are integer expressions; they cannot be passed to a function that expects a string, or stored in a variable that is defined to hold dates. In other words, types are associated with variables and not values. This Static typing is a limited form of program verification. Accordingly, it allows many type errors to be caught early in the development cycle.
Some examples of Statically typed languages are Ada, C, C++, C#, JADE, Java, Pascal, Scala.

Types of Statically Typed Languages

Statically typed languages can be either manifestly typed or type-inferred.

1. Manifestly typed

In manifestly typed, the programmer must explicitly write types at certain textual positions (for example, at variable declarations).
Most mainstream statically typed languages fall under the category of manifestly typed.
Some of the examples are C++, C# , Java

2. Type-Inferred

In type-inferred, the compiler infers the types of expressions and declarations based on the context.
Many manifestly typed languages support partial type inference.
For example, Java and C# both infer types in certain limited cases

Combination of Dynamic typing and Static typing

There are some statically typed languages that defer certain checks to runtime. On other hand, some dynamically typed languages often perform some checks statically to warn users. The presence of static typing in a programming language does not necessarily imply the absence of all dynamic typing mechanisms. For example, Java, and various other object-oriented languages, while using static typing, require for certain operations (such as downcasting) the support of run-time type tests, which is a form of dynamic typing.

Advantages of Statically Typed

1. In static type languages, type checking is done at compile time so that helps catching type errors early in development life cycle. Static type checking hence improves program robustness.
2. Once the type of all variables have been checked, the process of type checking is not repeatedly perform over different runs of the same program.
3. Statically typed program runs faster as overhead of type checking during run-time is already performed during compile time.
4. Programs developed in statically typed languages are more safe and reliable.

Disadvantages of Statically Typed

1. The static typing is too rigid and this feature does not make them ideally suited for prototyping systems with changing or unknown requirements or that interact with other systems that change unpredictably(for e.g, data and application integration)
2. The statically typed systems programming languages make code less reusable and also are more verbose.
3. They sometimes make code less expressive than dynamically typed scripting languages.

Advantages of Dynamically Typed

1. Compilation of dynamically typed porgram is faster.
2. Dynamically typed programming languages are simplified.
3. Dynamically typed programming languages have some features that are not available in statically typed languages like Duck Typing (Unbounded Polymorphism).
4. Major advantages of dynamically typed languages is reduced development time and their flexibility.
5. Dynamically typed language makes it easier to develop and deploy web applications.
6. Dynamic typing gives a lot of freedom to the programmer and lets programmer do things which would not be possible otherwise. For example, programmer can write functions to which an integer as well as floating point numbers or strings or any thing else is passed and it will be able to transparently handle all of them in appropriate ways.
7. Dynamic typing supports heterogeneity. For example, integers and strings can be contained in one array [1,2,"sam"].

Disadvantages of Dynamically Typed

1. The obvious disadvantage of dynamic typing is that the complier cannot perform complete typechecks at compile-time, therefore it is possible that bugs are hard to locate and debug.
2. The cost of dynamic typing is more compared to static typing, as tagging data values uses time and space.
3. In contrast to statically typed languages, dynamically typed languages need to perform type checking every time program is run.
4. Dynamic typed program may encounter run-time errors which are difficult to debug and tracking exact location of bug in the program may be difficult.

Choosing Between The Two

Statically Typed
Both statically typed and dynamically typed languages have important role to play. For example, when customer needs extra software reliability and is willing to pay extra cost for the same, such as software for nuclear power plant or an airplane's autopilot function. Static type systems play key role in providing extra software reliability.

Dynamically Typed
Usually it is fast to develop applications using dynamically typed languages. If rapid application development & deployment, with importance on producing incremental results, is what customer needs then probably using dynamically typed language is a good option.

Developing web applications in statically typed languages is not easy but it is easier to develop web applications in dynamically typed languages.

Dynamically typed language like Perl is suitable for both small and large systems. Python is used in variety of applications. Python is used to implement the software frameworks for major operations research methodologies. Major operations research methodologies could have been implemented in statically typed language and it may perform better than python , but doing so in dynamically typed language like Python makes it easy to develop a DSL-like environment, such as APLEpy (Algebraic Programming Language Extension for Python) and SimPy(Simulation in Python), and build applications on it. Development time in dynamically type language is lesser compared to statically type language. Integrating two applications domains would require explicit consideration and programming effort. In python it can be accomplished with no effort.

A hybrid of two
Another example of dynamically typed language is Lua. Lua helps creating hybrid solutions that combine strengths of statically typed languages with the flexibility of a dynamically typed languages. Lua helps binding existing C/C++ libraries to Lua scripts without the need of compiling and linking C programs. Lua has in-build tools to create bindings or one can write them by hand. For example window device drivers interface functions to recognize the external devices like USB can be added as one function to the Lua environment. Lua can also be integrated into an existing product by embedding Lua. Once Lua is embedded in the existing system, host program contains powerful scripting facility and can create and control as many Lua virtual machines as required. Example using Lua to maintain system configuration data. Handling data through Lua is convenient as its tables are a clean but powerful data description mechanism. Once data is structured, loading and accessing using Lua is very simple and fast.

Comparision between Statically Typed and Dynamically Typed Languages

Consider an example of dynamically typed programming language 'Python' and a statically typed programming language 'Java'.

Comparison between Python Vs Java

The following comparison shows certain features in Python that make it more productive than Java

Java Python
Statically typed

In Java, all variable names along with their types must be explicitly declared. An exception is triggered when one attempts to assign an object of the wrong type to a variable name. This infact means that Java is a statically typed language.

Dynamically typed

In Python, there is no need to declare anything. An assignment statement binds a name to an object, and the object can be of any type. If a name is assigned to an object of one type, it may later be assigned to an object of a different type. This infact means that Python is a dynamically typed language.

Container Objects

Java container objects (e.g. Vector and ArrayList) hold objects of the generic type Object, but cannot hold primitives such as int. To store an int in a Vector, one must first convert the int to an Integer. When one retrieves an object from a container, it doesn't remember its type, and must be explicitly cast to the desired type.

Container Objects

Python container objects (e.g. lists and dictionaries) can hold objects of any type, including numbers and lists. When one retrieves an object from a container, it remembers its type, so no casting is required.

Verbose

In general, Java is considered as verbose. It uses or contains more words than are necessary

Concise

In Python, expressing is done much in a few words which imply clean-cut brevity.


Example Code Comparisons

The classic "Hello, world!" program illustrates the relative verbosity of Java as compared to Python.

Hello World example in Java:
public class HelloWorld
{
    public static void main (String[] args)
    {
        System.out.println("Hello, world!");
    }
}


Hello World example in Python:

print "Hello, world!"

----------------------------------------

print("Hello, world!") # Python version 3


Example with Multiple classes
Consider an application has 20 classes. (More precisely 20 top-level public classes)
In Java:

Each top-level public class must be defined in its own file. If the application has 20 such classes, it has 20 files.


In Python:

Multiple classes can be defined in a single file. If the application has 20 classes, the entire application can be stored 
in a single file. Although, it would be better to partition it into perhaps 4, 5, or 6 files.


Example using Constructors
Consider an application having Employee class. When an instance of Employee is created, we may pass one, two, or three arguments to the constructor.

In Java: While programming in Java, it means that we write three constructors with three different signatures.

public class Employee
{
    private String myEmployeeName;
    private int    myTaxDeductions = 1;
    private String myMaritalStatus = "single";

    //---constructor #1---
    public Employee(String EmployeName)
    {
        this(employeeName, 1);
    }

    //---constructor #2---
    public Employee(String EmployeName, int taxDeductions)
    {
       this(employeeName, taxDeductions, "single");
    }

    //---constructor #3---
    public Employee(String EmployeName,
           int taxDeductions,
           String maritalStatus)
    {
       this.employeeName    = employeeName;
       this.taxDeductions   = taxDeductions;
       this.maritalStatus   = maritalStatus;
    }
...


In Python: While programming in Python, we need to write only a single constructor, with default values for the optional arguments.

class Employee():

    def __init__(self, 
        employeeName, taxDeductions=1, maritalStatus="single"):
      
        self.employeeName    = employeeName
        self.taxDeductions   = taxDeductions
        self.maritalStatus   = maritalStatus
...

As seen from the above example, in Python, a class has only one constructor. The constructor method is simply another method of the class, but one that has a special name: __init__

Conclusion

Both statically and dynamically typed languages have advantages and disadvantages. Depending on the situation and requirements, one of the languages is used for product development. Sometimes it is best to use mixture of both (as is the case with Lua) to take advantage of both the languages for product development.

Glossary

• Downcasting -   In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.
• DSL -   Domain Specific Languages.
• Lua - a language for extending applications. See also Lua
• APLEpy - Algebraic Programming Language Extension for Python
• SimPy - Simulation in Python
• Duck Typing - A method can be invoked on a variable whenever the type of object assigned to the variable has that method defined on it
• Container Objects - In object-oriented programming, a container class is any class that is capable of storing other objects. Examples of container objects include Vectors, ArrayLists, Queue, Set, Stack etc.

References

1. http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=04302684
2. http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=04302685
3. http://www.ferg.org/projects/python_java_side-by-side.html
4. http://en.wikipedia.org/wiki/Type_system
5. http://en.wikipedia.org/wiki/Programming_language
6. http://www.ibm.com/developerworks/java/library/j-diag0625.html
7. http://stackoverflow.com/questions/125367/dynamic-type-languages-versus-static-type-languages
8. http://en.wikipedia.org/wiki/Container_%28data_structure%29
9. http://www2.computer.org/plugins/dl/pdf/mags/so/2007/05/s5028.pdf?template=1&loginState=1&userData=anonymousIP%253A%253A65.190.191.228
10. http://www.cs.princeton.edu/courses/archive/fall03/cs510/notes/dyntyp.ps