February 01, 2005

Strong/Weak vs Static/Dynamic typing

During the past week, while imbuing myself with Ruby knowledge, I came across a few discussions about the nature of Ruby vs that of other languages such as Java, Python, Perl, etc. Most of those discussions centered around the type systems in each language.

It seems quite common for people to mix the concepts of strong/weak and static/dynamic language typing. Let me clarify, these are two different categories, almost orthogonal to each other. A language can be strongly-typed and dynamically-typed at the same time.

Static vs Dynamic

Informally, a statically typed language enforces type consistency at compilation time, whereas a dynamically typed language defers this until runtime. In reality, there's a wide gamut of "typing dynamism" so it would be incorrect to say that every language falls into either category. At one end of the spectrum lie languages such as ML or Haskell; at the other end, languages like Lisp. Java and C++ lie close to the statically-typed end, whereas Ruby and Python lie close to the opposite end.

Here's an example of dynamic typing, in Ruby:

class Car
     attr :price
end

class Apple
     attr :price
end

def calculateTotalPrice(item, quantity)
     item.price * quantity
end

car = Car.new
car.price = 300
calculateTotalPrice(car, 2)

apple = Apple.new
apple.price = 2
calculateTotalPrice(apple, 12)


The type of the arguments to calculateTotalPrice are not bound or even checked at compile type. That determination is left till the moment the method is actually called.

With a statically typed language, on the other hand, the type of the actual parameters must match those of the formal parameters in a call. The example above could be rewritten in Java as:

class Item {
     float price;
}

class Car extends Item { }

class Apple extends Item { }

class Calculator {
     float calculateTotal(Item item, int quantity)
     {
         return item.price * quantity;
     }
}


The difference here is the introduction of the Item superclass and typed arguments for calculateTotalPrice. Trying to call that function with anything that is not an Item will fail at compile time. Disclaimer: this is not a good way to use inheritance, since it involves bringing two unrelated classes under the same hierarchy just for interface compliance. It's just an example to illustrate static typing without excesive boilerplate.

Here's a simpler example. In Ruby it we can do:

class Car; end
class Apple; end

obj = Car.new
obj = Apple.new


The type of obj is determined at runtime, based on what object it points to.

The Java equivalent would be:

class Car {}
class Apple {}
...

Car car = new Car()
Apple apple = new Apple()


car and apple are variables of type Car and Apple, respectively. Attempting to assign new Car to apple would fail at compile-time.

Of course one could replace the type of all variables with Object, effectively turning the language into a dynamically-typed one. That's one of the reasons why Java is not at the end of the spectrum, but close to it.

Strong vs Weak

It is a little harder to define what a strongly vs weakly typed language is, but it revolves around the notion of how much effort does the language put into checking type consistency (either at runtime or compile time). In this sense, Java and Ruby are both strongly typed, whereas Javascript is weakly typed.

In Ruby, it is possible to access only to methods and attributes that have been defined in a class or added to an object at runtime:

def ColoredObject
     attr :color
end

obj = ColoredObject.new
obj.color = "blue"


Attempting to access a method or attribute not defined explicitly for the class or object will cause a runtime error.

On the other hand, in weakly typed languages such errors will go unnoticed. For example, in JavaScript it is possible to access an attribute that doesn't exist in an object (it will be created on the fly):

var obj = new Object();
obj.color = "blue";


Some may say this is a feature. But it has its dangers (a simple typo can be very hard to detect and find).

Ruby seems to capture the best of both worlds. While being a strongly typed language, it has a mechanism for adding methods and attributes to objects at runtime (whether even compile time exists in Ruby is the topic of another discussion :) ):

class Car
end

car = Car.new
car.color = "blue" # fails with "NoMethodError: undefined method `color=' for #"

# let's add an attribute named "color"
def car.color= (value)
     @color = value
end

car.color = "blue" # succeeds

13 Comments:

Anonymous Anonymous said...

That's not actually what weak typing is about.

Weak typing is when the same object/referance/whatever can be interpreted in multiple ways.

The best example of this is perl, where "2" can be the string "2" or it can be the number 2 - you can concatente another string onto it, or you can add another number to it, without type conversion.

This doesn't work in javascript - if you try:
"2"+4
you get "24" - the number is promoted to a string, and then
the two are added (concatenated) together.

However, in Perl, if you try it, you get the number 6.

The fact that you can add a property at any time to any object in javascript is just because that's they way javascript is - it has nothing to do with strong or weak typing.

February 03, 2005 9:11 AM  
Blogger Martin said...

I think you are right, but I also think what you described is just one aspect of weak typing and my point is still valid. Let me explain.

You said "weak typing is when the same object/referance/whatever can be interpreted in multiple ways". Well, in Ruby that does not apply. An object *can* be interpreted in multiple ways (see my post on duck typing) but that doesn't make Ruby's typing any less strong. On the other hand, in Javascript you can access an attribute that does not exist (i.e. you're interpreting the object as having that attribute... and consecuently, as being of a certain type) and the interpreter will not complain. Yes, it is true that attributes are added on the fly if you assign to them and that's a feature of the language. But you can also do:

var obj = Object();
var y = obj.someAttribute;

and the interpreter will not complain one bit.

So, again, I think what you and I described are two different aspects of weak typing and both are valid.

February 03, 2005 9:41 AM  
Anonymous Anonymous said...

The deal with javascript is it's a prototype based language. So the assignment operator is actually slot update, not value set. Slots are just generic object references in the same way as a variable. So the fact that you can assign a value to a previously unmentioned slot doesn't mean that slot isn't strongly typed at runtime. Try assigning to a slot then invoking an invalid operation on it. Try it in Self too.

Because it's prototype based, there's really no reason to treat things different: you conjure objects ex nhilo in procedures as a matter of course, just as in ruby you might conjure up a global variable within a stand alone method body by assigning to it, not by first declairing it.

I'm still getting used to Ruby's object model, but so far the metaphor that makes the most sense is that it's a prototype based system pretending it's a class based system. 'New' methods are the constructor procedures. .class is the .parent delegate. Mixin's create invisible anonymous proxies within the delegation chain.

I think less confusion is used by the terms 'strict' vs 'weak' typing.

February 05, 2005 5:54 PM  
Anonymous Anonymous said...

I am so happy to get some aion kina from my friends. They know I need aion online kina, they give me. So I always can get some aion gold from my friends. I buy aion kina with my spare money. It makes me happy that I can still earn some cheap aion kina.

My friends like to play it and buy aoc gold. If you have money to buy age of conan gold, you will find it is very useful. Earning conan gold is not so hard. Try your best and then you can get it. I buy cheap aoc gold, just because I like it. So simple the aoc money is.

April 15, 2009 2:14 AM  
Anonymous Anonymous said...

I am so happy to get some aion kina from my friends. They know I need aion online kina, they give me. So I always can get some aion gold from my friends. I buy aion kina with my spare money. It makes me happy that I can still earn some cheap aion kina.

May 04, 2009 11:26 PM  
Anonymous Anonymous said...

Do you know fiesta Gold? I like it. My brother often go to the internet bar to buy fiesta money and play it. After school, He likes playing games using these fiesta online gold with his friend. I think that it not only costs much money but also spend much time. One day, he give me many buy fiesta Gold and play the game with me. I came to the bar following him and found fiesta online money was so cheap.

May 04, 2009 11:45 PM  
Anonymous Anonymous said...

Life Experience Degree | online masters degree | associate degree

December 03, 2009 10:16 PM  
Anonymous Anonymous said...

Nice work and thanks!
Running
Adidas currently manufactures several running shoesNike shoes, including the adiStar Control 5, the adiStar Ride
Cheap nike shoes
Discount nike shoes
the Supernova Sequence and the Supernova Cushion 7, among others.
Nike shox r4
nike shox shoes
Adidas also uses kangaroo leather to make their more expensive shoes.
Association football
One of the main focuses of Adidas is football kit and associated equipment.
puma cat
cheap sport shoes
Adidas also provides apparel and equipment for all teams in Major League Soccer. Adidas remain a major company in the supply of team kits for international football teams.
cheap nike shox
cheap nike max
Adidas also makes referee kits that are used in international competition and by many countries and leagues in the world. In the United States, referees wear the Adidas kits in MLS matches even though the primary referee supplier is Official Sports.
nike tn dollar
nike running shoes
The company has been an innovator in the area of footwear for the sport with notable examples including development of the Copa Mondial moulded boot on firm dry pitches for forty years.
nike air max tn
puma shoes
Adidas became renowned for advancing the "Predator" boot design.This design featured a ribbed rubber structure for the upper leather of the shoe, used to accent the movement of the ball.
discount puma shoes
puma mens shoes
The Predator also features the Craig Johnston invented "Traxion" sole. As the development and popularity of Football continued Adidas played a leading role in shaping the style of the play itself.
puma running shoes
puma shoes
FIFA, the sports governing body, commissioned specially designed footballs for use in its own World Cup tournaments to favour more attacking play.
ghd hair straighteners mk4
hair straightners
ghd iv styler hair straightener
ghd hair straightners
cheap ghd hair straighteners

December 08, 2009 7:07 PM  
Anonymous Anonymous said...

We brought together the world's top fashion trends of designer jeans to display their charming fashion

imagination, creative unique design, to explore the city a unique atmosphere of casual upstart. With its

fashion sense, he was ahead of the sensitive integration of the brand concept, the shackles of the

traditional dress once released, infiltrated fashion, leisure elements, breaking the traditional

framework, and vividly show the self-style, to bring traditional costumes outside the the trend of

choice. We have diesel jeans, Ed-hardy jeans, D & G jeans, Levi's jeans and other brands of jeans, first

of all to ensure adequate quality and comfort and make the product style and the beautiful, comfortable,

classic European and American avant-garde style of the performance of most vividly Cheap jeans allow you to reduce overhead at the same time leading

the fashion in our series of jeans, you can create their own unique personality delightful charm.Our

center also has NFL Jerseys, as well as a variety of clothing

cheap polo shirts

Air jordans shoes itself work very well,Wear after will feel

elasticity, very comfortable,"The function is walking shoes, so when the design will comfort in the

first,And when the sports shoes is lightsome feeling more comfortable, durability and wearing

comfortable, walk the portability of new products, etc.To what extent can actually cheaper
,Our sports Chaussures at the Sports Chaussures and Cheap Nike Shoes etc all kinds ofcheap

shoes
our 2010 what you love design,our Sports Chaussures look

at the welcome your presence
Anothre set of ralph lauren polo in three colors. Ralph Lauren Polo Shirts come with a graduation of colors on the chest. The new shiki Cheap polo shirts logo is on the chest. Comes in all layres and can be worned tucked in or out Wholesale Polo Shirts -50% OFF.
Also comes with sculpted collar and arm cuffs.Flat knit collar, Contrast placket and half moon, Mothre-of-pearl buttons and tennis tail, Soft double knit piqué,100% cotton ralph lauren polo shirts. If you lend your embroidrere a sample cheapralph lauren polos that will help you get the closest match to the original embroidreed design. The artwork you provide will sreve as a template for your embroidrey set-up but discount ralph lauren polos can't be used to identify some stitch types, cheap polo shirts Cheap Polo Shirtsgive precise sizing of embroidreed elements and show thread polo clothing colors.
Wholesale Polo Shirts
Ralph Lauren Polo Shirts
Discount Ralph Lauren Polos

February 01, 2010 1:12 AM  
Blogger star said...

In computer science, a type system may be defined as a tractable syntactic frame work for classifying phrases according to the kinds of values they compute.[1]. A type system associates types with each computed value. By examining the flow of these values, a type system attempts to prove that no type errors can occur.
greetings
Cialis online

February 26, 2010 6:25 AM  
Blogger Unknown said...

I would like to buy somethings from here low prices and high quilitytn chaussures I would like to buy somethings from here low prices and high quilityChaussures Sport I would like to buy somethings from here low prices and high quilityNFL Jerseys I would like to buy somethings from here low prices and high quilityCheap Polo Shirts I would like to buy somethings from here low prices and high quilitychaussures puma
I would like to buy somethings from here low prices and high quilitychaussures puma I would like to buy somethings from here low prices and high quilityTn Requin I would like to buy somethings from here low prices and high quilityCheap Polo I would like to buy somethings from here low prices and high quilityAir Max I would like to buy somethings from here low prices and high quility Nike Chaussures

March 09, 2010 11:29 PM  
Blogger Unknown said...

dynamic typing with a lot of practice you can get very fluently and dynamic
thanks

generic Viaga Online

March 23, 2010 2:14 PM  
Anonymous Anonymous said...

Great site,this information on buy viagra really helped me , I really appreciate it.Thanks a lot for a bunch of good tips. I look forward to reading more on the topic in the future. Keep up the good work! This blog is going to be great resource. Love reading it.

March 30, 2010 9:50 AM  

Post a Comment

<< Home