You are on page 1of 22

Java vs. PHP vs.

Pascal
Programming Paradigms
1/10/2012 Bogdan Popescu MSc. Software Engineering

Contents
Introduction .................................................................................................................................................. 2 Overview ................................................................................................................................................... 2 Programming Languages Used.................................................................................................................. 2 Pascal .................................................................................................................................................... 3 PHP ........................................................................................................................................................ 3 Java........................................................................................................................................................ 4 The 3 Paradigms ............................................................................................................................................ 4 Application .................................................................................................................................................... 0 Java Application ........................................................................................................................................ 0 PHP Application......................................................................................................................................... 6 Pascal Application ..................................................................................................................................... 9 Conclusion ................................................................................................................................................... 12 Bibliography ................................................................................................................................................ 13

Introduction
Overview
Since their inception, computers have played an increasingly important role in todays society. Advancements in technology have enabled computers to become faster and cheaper. Today, the majority of families own a home computer that is vastly more powerful than giant mainframes of years gone by. Computer hardware has been evolving rapidly with no end in sight, and with all of the advancements in computer hardware come advancements in computer software; gone are the days when FORTRAN and COBOL were the languages of choice. Today, two hot new programming languages have entered the computer programming arena, Java and PHP. This paper will examine the similarities and differences between these two languages together with another one that it is most used in the educational environment nowadays, Pascal. This document will not concentrate on the theoretical part, but on the practical one since I developed an application with almost the same functionality in all these three programming languages. The practical part of this entire work consists of a small application that simulates the behavior of a MiniBlog. The owner of the blog is able to login in the application and post new articles. Also the owner and other users that visit this blog will have the possibility to view a list of articles and read the entire text of the articles. But all these restricted possibilities are represented better by the Use Case diagram in Figure 1.

Figure 1 Use Case Diagram

Programming Languages Used


As I mentioned in the previous sub-chapter, for developing this small application I used three programming languages from different paradigms. The programming languages used together with the paradigms to which they belong are as follows: Pascal Procedural Paradigm PHP Scripting Paradigm Java Object Oriented Paradigm

Pascal Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring. The name of this program was given by the honour of the distinguished french mathematician, physicist and philosopher Blez Pascal. The speciality of the language is the strict classification of the types and the existence ways of the structual programming. Pascal was one of the first such languages. Pascal, like many programming languages of today (but unlike most languages in the C family), allows nested procedures definitions to any level of depth, and also allows most kinds of definitions and declarations inside procedures and functions. This enables a very simple and coherent syntax where a complete program is syntactically nearly identical to a single procedure or function (except for the keyword itself, of course.) PHP PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. It is among one of the first developed server-side scripting languages that is embedded into a HTML source document, rather than calling an external file to process data. Ultimately, the code is interpreted by a web server with a PHP processor module which generates the resulting web page. PHP can be deployed on most web servers and also as a standalone shell on almost every operating system and platform free of charge. A competitor to Microsoft's Active Server Pages (ASP) server-side script engine and similar languages, PHP is installed on more than 20 million websites and 1 million web servers. PHP was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the formal reference to the PHP language.

Java Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere," meaning that code that runs on one platform does not need to be edited to run on another. Java is currently one of the most popular programming languages in use, particularly for clientserver web applications, with a reported 10 million users.

The 3 Paradigms
This work was actually intended so that we, the students, should improve our knowledge about different methods of writing applications and be aware of the upsides and downsides of each programming language. Table 1 presents a comparison between the three programming languages I used for this project, taking into consideration the main aspects of each of them.

Paradigm History

Object Oriented language Developed in 1995; originally intended for client software and in browser applets

Scripting language Developed in 1995; intened for web application since is scripting language and can be easly embeded into HTML Server-Side executed Dynamic typing instead: variables assume the type of the value currently contained in them

Procedural language Published in 1970; intended to encourage good programming practices using structured programming and data structuring Delphi uses Pascal Server Pages, that are Server-Side executed Static typing: variables must have a declared type Functions (returns a result) and Procedures (does not return a result)

Execution

Server-Side executed

Static typing: variables must have a declared type

Sub-programs

Methods

Functions

Certainly the strength of Java; On the one hand, Java itself is almost Industry Standard, on the other hand, there are many standards implementations in Java.

Integration

If a PHP Web application should communicate with a specific protocol, the selection of libraries is rather limited. Integration of PHP applications with other services usually happens through the db layer.

Pascal is used rarely today and only in some educational systems for giving the students a general idea of programming,

Reflection (process by which a computer program can observe (do type introspection) and modify its own structure and behavior at runtime) Connection Pooling Threads Annotations Rich API

Provided (reverse-engineer classes, interfaces, functions )

Provided since PHP 5

Provided in Delphi

Native support Native support Native support Too much

Default Secure programming practices

Java puts a lot of conformations on early checking for possible problems, later dynamic checking, and eliminating situations that are possibly causing error. Robustness and good memory management. No pointers

mod_php in Apache N/A N/A Very little Most of these PHP-related vulnerabilities can be exploited remotely: they allow crackers to steal or destroy data from data sources linked to the Web server (such as an SQL database), send spam or contribute to Denial of Service attacks using malware, which itself can be installed on the vulnerable servers As PHP is easy and popular, more bugs are written with it - PHP application developers do not make a good job at securing their code: they do not care, or they do not know how, or they try but fail.

N/A N/A N/A Very little

Pascal is used rarely today and only in some educational systems for giving the students a general idea of programming,

Java has strong presence between client side and server side. Servlet API leverages the advantages of Java platform to correct and solve the issues of APIs and CGI. Web applications development Java web applications can be run anywhere and all you need is a Java Virtual Machine (JVM) running on clients side. The problem with Servlet is bit complicated and you have to write, compile and deploy life cycle, from this reason Java Server Pages (JSP) considered to be the third generation solution.
Table 1 Paradigms Comparison

PHP is a general-purpose scripting language, but is especially suited for server-side web development. PHP is mainly focused on serverside scripting, so it can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies PHP can be deployed on most web servers, many operating systems and platforms (Windows, Linux, Unix, Mac OS X, etc.), and can be used with many relational database management systems.

Delphi uses Pascal for web applications, but this type of applications are rarely known or written because better solutions are available for developers.

Application
In order to fulfill the requests of this task I wrote three applications having the same functionalities, one for every programming language that are mentioned in the previous chapter. Thus, for Java and PHP I created two web applications that connect to a database in which the user data and articles contents are stored. Taking into consideration that Pascal is an old programming language, mostly used in educational systems for building the basis of programming, for the application implemented in this programming language I decided to store and read data to and from files. The Pascal application does not have a graphical interface; it uses windows console for displaying information and interaction with the application.

Java Application
Since Java is an Object Oriented programming language, I managed to develop a complex solution, by creating different objects for encapsulating the attributes and methods used to construct the application. I made use of the Model View Controller (MVC) architecture (Figure 2), thus managing to separate the components of the application. The Model encapsulates core data and logic. Model is often related with the business logic of the application. It knows all the data that needs to be displayed. It is always isolated from the User Interface (UI) and the way data needs to be displayed. The View is the UI part of the application. It uses readonly methods of the model and queries data to display them to the end users. It may be a window GUI or a HTML page. View encapsulates the presentation of the data, there can be many views of the common data The Controller acts as a interacting glue between models and views. It accepts input from the user and makes request from the model for the data to produce a new view. Figure 2 Model View Controller Architecture

The structure of the application written in Java is presented in the figure from the right side. I decided to create this application as a Maven project and use the facilities of SpringFramework. One of the most used facilities was the Dependency Injection because Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes (Unit Testing). To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather that the class itself creates / finds this object.

Figure 3 Java Application Structure

Since the code of the application isnt quite smaller I decided to show just two elements of the code, an object class and a controller class.
package msc.se.pp.data; import java.util.Date; /** * Class used to define the Article object * @author bogdan.popescu * */ public class Article { private int articleId; private String text; private Date dateEntered; private User user; public int getArticleId() { return articleId; } public void setArticleId(int articleId) { this.articleId = articleId; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getDateEntered() { return dateEntered; } public void setDateEntered(Date dateEntered) { this.dateEntered = dateEntered; } public User getUser() { return user; } public void setUser(User user) { this.user = user; }

Controller class:
package msc.se.pp.web; import java.util.HashMap; //imports /** * Controller class for rendering the model used by the * view to display the home page. * @author bogdan.popescu * */ public class HomeController implements Controller, InitializingBean { /** Logger for this class and subclasses */ private final static Logger log = Logger.getLogger(HomeController.class); private BlogDao service; public void setService(BlogDao service) { this.service = service; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("handleRequest - Generating the Home page..."); List<Article> articles = service.getAllArticles(); log.debug("handleRequest - List of all articles retrived. Size: "+articles.size()); Map<String, Object> modelMap = new HashMap<String, Object>(); modelMap.put("articlesSize", articles.size()); modelMap.put("articles", articles);

return new ModelAndView("viewHome", "model", modelMap); } /** @see InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { Assert.notNull(service, "Service not set!"); } }

Below I will present you some screen-shots of the application, which, you will notice later that it is very similar to the one written using PHP.

Figure 4 Application Home Page

Figure 5 Application Read Article Page

Figure 6 Application Login Page

Figure 7 Application Post New Article Page

PHP Application
PHP belongs to the class of scripting paradigms, thus the PHP scripts are easily embedded into the HTML pages using the start and end tags for code fragments (<?php and ?>). The MiniBlog application written in PHP has the following structure: The common folder contains the header and footer elements of the application. The pages folder contains PHP files in which HTML and PHP code are mixed for rendering views. The scripts folder contains pure PHP files used for validation the login, the article post etc.
Figure 8 Application Structure

The PHP code is executed on the server side, making the browser not aware about the PHP code. Code examples: Home page:
<?php // load the header require_once("../common/header.php"); ?> <div id="content" class="rounded-corners"> <!-- content --> <table id="contentTable"> <? if(!isset($_SESSION["articles"])) { ?> <tr> <td> No articles. </td> </tr> <? } else { foreach ($_SESSION["articles"] as $article) { echo $article; } } ?> </table> </div> <?php require_once("../common/footer.php"); ?>

Getting the Articles for home page script:


<?php session_start(); include 'connection/config.php'; include 'connection/opendb.php'; $articleId=$_GET['articleId']; $sql = "SELECT a.ArticleId, u.Username, a.DateEntered, a.Text FROM Articles a, Users U WHERE u.userid = a.userentered and a.articleId = $articleId"; $result = mysql_query($sql); $article = mysql_fetch_assoc($result); $html = "<tr><td><h1>Article #" . $article['ArticleId'] . "<h1></td></tr>"; $html .= "<tr><td><p>" . $article['Text'] . "</p></td></tr>"; $html .= "<tr><td style='font-style: italic;'>Entered by " . $article['Username'] . " on " . $article['DateEntered']; $_SESSION['article'] = $html; header("Location: ../pages/view-article.php"); include 'connection/closedb.php'; ?>

As mentioned in the previous subchapter, the application looks almost the same with the one written in Java.

Figure 9 Application Home Page

Figure 10 Login Page

Figure 11 Article Page

Figure 12 Post Article Page

Pascal Application
Since Pascal is an old programming language and not very often used nowadays, I could not connect the application to the databases used for the previous two programming languages, so I made use of reading and writing to files. The application also, does not have a GUI, but instead it uses the windows console. Belonging to the class of procedural paradigms, the code of this application is structured into procedures and functions that call each other in order to obtain the required functionalities. This solution of the problem statement is not a suitable one and it was done only for having a comparison between the paradigms.

Code Example:
program pascalApp; uses Dos, Sysutils; var headerFileName, contentFileName, footerFileName, login, usersFileName, path, loginUser: String; { procedure used to display the content of files } procedure displayFile(fileName: String); var fileC: Text; line: String; begin assign(fileC, fileName); reset(fileC); {open file} repeat readln(fileC, line); writeln(line); until eof(fileC); close(fileC); end; { function for verifying the login and returns the username } function execLogin(usersFileName:String) : String; var username, password, line, usernameF, passwordF: String; fileC: Text; flag: boolean; begin write('Username: '); readln(username); write('Password: '); readln(password); assign(fileC, usersFileName); reset(fileC); flag := false;; while not eof(fileC) do begin readln(fileC, line); usernameF := copy(line, 1, pos('|',line)-1); passwordF := copy(line, pos('|',line)+1, length(line) - pos('|',line)); if (username = usernameF) and (password = passwordF) then flag := true; end; close(fileC); if flag = true then begin execLogin := usernameF; end

else begin writeln('Wrong username/password'); execLogin(usersFileName); end; end; { procedure for posting a new article } procedure postArticle(username: String); var content, timeStamp: String; year, month, day, wday: word; fileC: Text; begin writeln('Please enter the article content and press Enter:'); readln(content); getDate(year,month,day, wday); assign(fileC, contentFileName); append(fileC); writeln(fileC, ''); writeln(fileC, 'Entered by ', username, ' on ', day, '/', month, '/', year, ':'); writeln(fileC, ''); writeln(fileC, content); close(fileC); end; {main procedure} procedure run(headerFileName, contentFileName, footerFileName, usersFileName: String); begin displayFile(headerFileName); displayFile(contentFileName); displayFile(footerFileName); write('Do you want to login to post a new article?[y/n]'); readln(login); if login = 'y' then begin loginUser := execLogin(usersFileName); if length(loginUser) > 0 then begin postArticle(loginUser); run(headerFileName, contentFileName, footerFileName, usersFileName); end; end; end; begin path := getCurrentDir + '\'; headerFileName := path + 'header.txt'; contentFileName := path + 'content.txt'; footerFileName := path + 'footer.txt';

usersFileName := path + 'users.txt'; run(headerFileName, contentFileName, footerFileName, usersFileName); end.

Since it does not have any GUI, the application design is completely different from the previous two.

Figure 13 Pascal Application View

Conclusion
It is important to make technology decisions at the right time and for the right reasons. Good business decisions provide good people with appropriate supporting tools so they can produce good products. In my opinion, which is a subjective one, I will always choose Java as a programming language over any other one and I think that a good programmer is one that has knowledge about more than one programming language but practices only one.

Bibliography
http://www.oracle.com/technetwork/java/index.html http://www.springsource.org/ http://www.php.net/ http://www.freepascal.org/ Comparing Selected Criteria of Programming Languages Java, PHP, C++, Perl, Haskell, AspectJ, Ruby, COBOL, Bash Scripts and Scheme Revision 1.0 - Pawel Pietrzynski Concordia University Montreal, Quebec, Canada

You might also like