Monday, September 29, 2008

comparing class syntax in C++, Java, PHP, Perl and Python

As I recently started learning Python one of the things I noticed which I didn't like is the class syntax. So I wrote some minimal hello world programs in the languages I recently used to show the difference:

C++ hello.cc

#include <iostream>

class Hello {

private: char *value;

public: Hello(char *newvalue) {
value = newvalue;
}

public: void hello() {
std::cout << this->value;
}
};

int main() {
Hello hello("hello\n");
hello.hello();
}
I like the C++ syntax, it is the language which introduced me to OOP and it it clearly states what bits are what without too wordy syntax.

Java: hello.java

class Hello {
private String value;

public Hello (String newvalue) {
this.value = newvalue;
}

public void hello(){
System.out.println(this.value);
}
}

class main {
public static void main(String args[]){
Hello hello = new Hello ("hello");
hello.hello ();
}
}
Also very nice, a bit clearer than C++.

PHP: hello.php

<?php

class Hello {
private $value;

function __construct($newvalue) {
$this->value = $newvalue;
}

function hello() {
echo $this->value;
}
}

$hello = new Hello("hello\n");
$hello->hello();
From the dynamic languages this one is the clearest. Except of the __construct() constructor, where I prefer the ClassName() syntax (which still works in PHP5)

Perl: hello.pl

package Hello;

sub new {
my ($class,$newvalue) = @_;
bless { newvalue => $newvalue }, $class;
}

sub hello {
my $this = shift;
print $this->{newvalue};
}

package main;

$main::hello = new Hello("hello\n");
$main::hello->hello();
I always hated objects (and functions) in Perl, there is no parameter syntax for functions or methods. Most of it is not enforced and you can use functions in objects in thousands different ways.

Python: hello.py

class Hello:
_value = ""

def __init__(self,newvalue):
self._value = newvalue

def hello(self):
print self._value;


hello = Hello("hello")
hello.hello()
A lot clearer than Perl, but also a lot of convention instead of forced syntax. I got used to the indention by now. But I hate that I have to specify "self" as the first parameters, the __init__ syntax and the underscore prefixing of private or protected variables. At least it has proper function parameters.

No comments:

Post a Comment