Научная статья на тему 'Comparing Oberon and Java by a Simple Data Structure'

Comparing Oberon and Java by a Simple Data Structure Текст научной статьи по специальности «Компьютерные и информационные науки»

CC BY
221
44
i Надоели баннеры? Вы всегда можете отключить рекламу.

Аннотация научной статьи по компьютерным и информационным наукам, автор научной работы — Heuberger Philipp, Malioukov Alexander

In this paper, we compare two computer languages: Oberon and Java. We have carefully tried to avoid any judging statement. Our goal is to show similarities and differences between them: both languages have syntactical differences but similar concepts. We give an overview and some details of the major language features and would like to encourage in particular educational institutions to do an own comparison. For that we include all necessary references to the literature. We illustrate our comparison by using a binary tree example.

i Надоели баннеры? Вы всегда можете отключить рекламу.
iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.
i Надоели баннеры? Вы всегда можете отключить рекламу.

Текст научной работы на тему «Comparing Oberon and Java by a Simple Data Structure»

быть получено, если X« располагается слева от зоны ВК и решение получается если X справа от зоны ВК. Получение двух различных решений, в зависимости от того с какой стороны ВК располагается ближайшая свободная колонка, связано с тем, чтобы одновременно с ликвидацией ВК минимизировать длину соединений.

Дальнейшие правила по ликвидации ВК 3-го типа полностью совпадают с правилами №

4, 5, 6 ддя ликвидации ВК 1-го, 2-го рода. Только в данном случае дни получат номера соответственно 5,6,7. 3 F

Особо стоит вопрос о ликвидации ВК 4-го типа. Несмотря на то, что в тактических задачах ВК 4-го типа встречаются крайне редко, их ликвидация представляет наибольшие сложности. В рабо-те предлагается подход к решению указанных ВК на композиции и приведению к ВК 1-го, 2-го и 3-го типов с после-дующей°Сликви^циЛей последних на основе вышеописанной технологии. w “

Отаетим, что возможны два варианта ВК 4-го типа. Для того, чтобы определить вапиант

ВК 4-го типа необходимо организовать просмотр направленных дуг ГВО Есл

по номеру вершины ГВО существует направленное ребро к первой

вложенного типа. Если такого ребра не существует, то ВК секпитшп™

- лциинн°го типа с числом секций

равным числу ребер, организующим путь из n-вершины в 1-ю ггои

выбирается то ребро среди альтернативных, которое ведет' к п*п каждом шаге

возможным номером. Вершине с минимально

Решение секционных ВК 4-го рода очевидно. Необходимо разбить такой ВК на секции и обрабатывать каждую секцию по отдельности (заметим, что ВК и«*« я , " секции и

гчг * \ л может быть 1-го, 2-го 3-го а

так же ВК 4-го рода вложенного типа). » J 1 “

ВК вложенного типа можно решить последовательным "Dae™«™».." ..

первом шаге применено правило 4 для ВК 3-го типа. На втором шаге ли внешних ВК. На типа путем применения правила 2 для ликвидации ВК 1-го типа квидирован ВК 1-го

В результате произведен анализ существующих алгоритмов его основе сделан выбор в пользу применения в САПР без трзесировки и на трассировщиков ввиду того, что в мире разработано большое число бе^оГы* трассировщиков с широким спектром характеристик от очень бысто канальных

решения до точных получающих решения близкие к оптимальнм«МХтС Низким качеством возможность гибкой тактике применения различных трассиров СИТ^ация дает

безизломные канальные трассировщики наиболее широко применяют 0В' Кроме того того, что безизломные канальные трассировщики имеют реэервы*СЯ п^актически Ввиду решения, а также исключают возможность решения ВК предлагав повышения качества автоматической трассировки на основе метода систем продукций^П0ВЫШение качества содеркит эвристические полиномиальные процедуры ликвидации Rif л ^®длагаемая система решающих правил по форме "ЕСЛИ" "ТО" для ликвидации ВК и с азработань| фуппы свойств ВК и декомпозиции горизонтальных сегментов. Форма °Кращения m 33 счет

позволяет легко их модифицировать ИЛИ изменить В CITVuoa г, а пРедставления правил предметной области. появления новых знаний о

УДК 658.512

Philipp Heuberger (M.Sc) Alexander Malioukov (M.Sc) Comparing Oberon and Java by a Simple Data Structure.

Abstract

In this paper, we compare two computer languages: Oberon anH ja„- « to avoid any judging statement. Our goal is to show similarities and differenr e/‘ave carefuIIy 111641 languages have syntactical differences but similar concepts We uivp 9n CS ween ^em: both

' g e an overview and some details of

the major language features and would like to encourage in particular educational institutions to do an own comparison. For that we include all necessary references to the literature. We illustrate our comparison by using a binary tree example.

Introduction

Developers of Java emphasize the syntactic similarity of Java to C/C++ and do not mention Oberon even though both languages and environments have many concepts in common which make the language robust, i.e. type extension, type safety (unforgeable pointers), dynamic loading, compile-and run-time checking, garbage collection and etc.

In spite of the semantic similarity, we are faced with many syntactical differences between the two languages. Consider pointers for example. Pointers have been omitted in Java, but the usage of Java classes is similar to the one of Oberon record pointers.

Historically there are two main approaches to imperative computer languages: Pascal and C. We decided to compare two recent members from each family: Oberon and Java.

Oberon belongs to the Algol-family of languages, e.g. Algol 60 (1960), Pascal (1970), Modula-2 (1975), Oberon (1988), Modula-3 (1989), Oberon-2 (1991) and Component Pascal (1997). Oberon has introduced the concept of type extension [12]into the Algol-family. The development of Oberon is documented in the scientific literature [10-13].

Java has a history which starts from C (1970, 1989 - formal standardization) after that C++ (1979 C with classes, 1983 C ++, 1986 1-st book) until Java (1991 Oak, 1995 - Java). Nowadays, Java is one of the most popular computer languages due to the wide-spread use of Internet.

Whereas there is a couple of books on Oberon [2, 3, 4], there is a huge amount about Java available and the ones we found reasonable are [5-9].

There is also on-line documentation available:

• for Java - http://java.sun.com/

• for Oberon - http://www.oberon.ethz.ch/

Both languages have a programming environment that is freely available on many software platforms and hardware architecture.

We base our comparison on the well-known data structure of binary trees. The example presented here has first been implemented in Oberon in [14] and then in Java. A binary tree is a tree in which the nodes are labeled with elements of a set. The important properly of a binary tree is that all elements stored in the left subtree of any node x are all less than the element stored at x, and all elements stored in the right subtree of x are greater than the element stored at x [1]. Note the interesting property that if we list the nodes of a binary tree in inorder, then the elements stored at those nodes are listed in sorted order. A binary tree can support the set operations Insert and Traverse. The operation Insert adds a new node. The operation Traverse takes our tree as an input parameter and returns sorted list of nodes.

2. General Overview

Lets start with a general overview of correspondences of the two languages:

Java Oberon

package <-> module

class <-> record

method <-> procedure

object <-> record pointer

Next, you will find sections which describe similarities and differences between Java and Oberon in detail.

3. Pointers

Java developers stress that Java does not support pointers meaning that the language does not support pointer-arithmetic. Pointer-arithmetic means that you can calculate arbitrary addresses in memory and dereference them. This can be dangerous because you have a possibility to destroy an arbitrary structure in the memory. In other words, you can not guarantee interprocess security other than having separate address spaces.

Pointer-arithmetic has never been available in the Algol-family. So in Oberon, a pointer cannot point to arbitrary variables but only to an instance of a given array or record type. We can get absolutely the same results in Java if we use classes for such purpose. Fig. 1 shows semantically equivalent code fragments in Java (left side) and in Oberon (right one).

Oberon has a keyword POINTER. The declaration of a pointer variable does not produce a record to point to. Such a record is explicitly allocated on the heap by invoking the predeclared procedure NEW. The actual parameter TheNode is a pointer of type Node which points to the record NodeDesc. In difference to Java, a record might not only be allocated on the heap but as well on the stack.

In Java objects are created by using an expression containing the "new" keyword. Creating an object from a class definition is also known as instantiation [5]. For example, we create TheNode using "new" operator. In other words we specify that the type of our object TheNode is Node. In general, "new" says "make me a new one of these objects" [6], in other words we have an instance of the base type of Node and we have precisely Oberon pointers.

class Node Node* POINTER TO

NodeDesc;

{ NodeDesc* = RECORD

Node left, right; left, right: Node;

} END;

Node TheNode new Node(); VAR TheNode

Node; NEW (TheNode);

Fig. 1

4. Object, Class / Record, Record Type

Java, like any object-oriented programming language, provides a tool to solve programming problems by using the notion of classes and objects [5]. Each class contains two kinds of members, named fields and methods.

A Java class is a combination of the two Oberon types - POINTER and RECORD. An Oberon object is of type POINTER and is described in RECORD. Instances of Oberon pointers behave in the same way as Java objects that are known as class instances. As you can see in Fig. 1, there are some syntactical differences in the Java class and Oberon POINTER/RECORD definitions, but as a result we have got the two instances with identical structure. Their assignments behave in the same way. Java type-casts corresponds to type-guards in Oberon (see section Type Extension).

A useful feature of both languages is the concept of an abstraction. The abstraction is helpful when some of the behavior is true for most or all objects of a given type, but some behavior makes sense only for particular types of objects and not a general superclass. In Java such a class is declared as "abstract", and each method not implemented in the class is specially marked "abstract" Oberon supports procedure variables in a record. We can say that the abstract methods in Java correspond to procedure variables in the record.

In our example (Fig. 2), we want to create two operations "equal" and "less" for comparing nodes in our tree. We can not say anything about the type of nodes yet. That is why we are making these methods as abstract in Java and we are using procedure variable in a record with name CompareFunction in Oberon.

abstract class BinTree {

Node root; abstract boolean BOOLEAN;

equal (Node a, Node b) ; BinTreeDesc;

abstract boolean

less(Node a, Node b);

CompareFunct i on;

}

TYPE

CompareFunction*

PROCEDURE(a,b: Node)

BinTree* POINTER TO

BinTreeDesc RECORD root : Node ;

equal, less:

END;

Fig. 2

5. Methods / Procedures

Java methods and Oberon procedures can be visualized as a named statement sequence. In particular, it encompasses:

• the concept of local variables;

• the concept of result;

• the concept of parameters.

In general, methods and procedures have similar concepts but there are some differences also. Java does not support nested methods which may be used in Oberon. Fig. 3 (right) shows a nested procedure in Oberon. For building a similar construction in Java, we should divide this procedure in two methods. The nested procedure would be a fully independent. You can find the result in Fig. 3 (left).

public void traverse()

{

ApplyProcedure);

if (root != null) traver(root);

)

private void traver(Node r) {

if (r.left null) traver(r.left); apply(r);

if (r.right null) traver(r.right);

PROCEDURE

traverse*(T: Tree; proc:

PROCEDURE traver(r: Node); BEGIN

IF r.left # NIL THEN traver(r.left) END; apply(r);

IF r.right # NIL THEN traver(r.right) END;

END traver;

BEGIN

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

IF T.root # NIL THEN traver(T.root)

END

END traverse;

Fig. 3

Java has no variable parameters, only value parameters. Value parameters are used to pass values into a procedure. Variable parameters serve to return also results from the procedure. Observe that without variable parameters e.g. a swap procedure is hard to implement. Fig. 4. shows the difference between the two parameters in detail.

PROCEDURE P (x: INTEGER, VAR y: INTEGER)

x

У

VAR a, b: INTEGER a 1;

b 2;

P(a, b);

RESULTS : a 1 b 0

Fig. 4

6. Constructor/Destructor, Finalize

Now we would like to emphasize on differences between Java and ... . j _ : - . Jdva ana Oberon. Oberon supports

neither constructors nor destructors. Java has constructors and does not have destructors Both

languages use garbage collection. In simple terms, when an object is no longer referenced the snace it

occupies can be reclaimed. This similarity is rather important, because, for instance C/C++ which is

claimed to have roots in the language Java, doesn't support any garbaee i u

"finalize" method. This method is executed before an object/s^T 2ÍSS’ ^5 1

"finalize" method for class Node. You can replace dots on some code. For

monitor screen phrase: "The End"

Class Node

instance, you can print on

{

Node left, right;

Node()

{

this.left null; this.right null;

}

protected void finalizeO {

Fig. 5.

7. Overloading

In Java, each method has a signature, which is its name together with the ^ .

its parameters. Two methods can have the same name if their signature.« h and lyPes °f

types of parameters. This feature is called overloading and works also fn ^ numbers of

example of overloading you can see on Fig. 6. Oberon does not sunn™ °rS' A Pnnutlve

implementation of Fig. 6 would require two differently named procedures ^ 8 T*1C ®ljeron

Class Math {

int sqrt(int x) { .. }

float sqrt(char x) { }

}

a sqrt('a');

Fig. 6

8. Type Extension

Both languages support type extension which is a useful feature. In our example, we decided that our nodes should have type Integer. In such case we extend basic class Node into NodeEx by adding new field of type integer named y. Both languages support assignment of extended type and base type in the same way. At this stage we can implement our abstract compare function equal. We should extend type of input parameters from Node to NodeEx. Fig. 7 describes Oberon and Java syntax for such extensions.

class NodeEx extends Node

{

int y;

)

(NodeDesc)

public boolean equal(Node a, Node b) b: Node)

{

NodeEx aEx (NodeEx) a;

NodeEx bEx = (NodeEx) b; b(NodeEX).y

return (aEx.y bEx.y);

}

Fig. 7

Note that both type-cast and type-guard mean that the execution is aborted if a and b are not extended nodes.

9. Packages / Modules

Name conflicts are a major problem when developing reusable code. No matter how carefully you pick names for classes and methods, somebody else is likely to use that name for a different Purpose [5]. The standard solution for name collisions is to use a package prefix. Packages in Java are named and can be imported (Fig. 8 (Left)). There is the * notation. Star means that you want to import everything from a package. Java also has access control. It means that you can use such keywords for classes and methods as "public" and "private" You can not import any private class or method.

In Oberon we have similar structure named module. Module defines a scope and provides export/import marks. You can import only these elements which were marked by *. Note the difference between star notations in the two languages. Star in Oberon corresponds to the access control, module to a package.

TYPE

NodeEx Pointer TO NodeEx Desc;

NodeEx Desc = RECORD

y INTEGER END

PROCEDURE equal(a,

BEGIN

RETURN

a(NodeEx).y

END equal;

package BinTree; MODULE BinTree-

class BinTree '

L: Node); PROCEDURE insert*(T: Tree,

public void insert(Node x) END BinTree

}

import java.BinTree.*; MODULE VoronoiElem*-

import java.BinTree.BinTree; IMPORT «us.,

class VoronoiElems {. .} BinTree-

Fig. 8 Conclusion

Java and Oberon are comparable and have similar concepts:

• type extension;

• garbage collection;

• type safety.

In particular, we have identified the following corresponding concepts-

• classes = pointers and records

• method = procedure with an object parameter

• abstract method = procedure variable in a record

• package = module

• access control = scoping

There are some additional features in Oberon:

• VAR parameters;

• procedure type;

• records allocated on the stack.

The conceptual similarities between both languages is indeed rath to the fact that both have learned lessons from previous systems (Lisp Module d* ^ m'g*U due

Acknowledgment

We would like to thank our supervisor Prof. Ralph-Johan Back anH TUCS seminar on Software Engineering for their critical comments ° P^ticipants of the

References

1. A. Aho, J. Hopcroft, J. Ullman, Data Structures and Algorithms aaa-

2. M. Reiser, N. Wirth, Programming in Oberon. Steps Bevond IS0"'^es,ey. 1983.

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

and Addison-Wesley, 1992. P ЄУ°П(1 Pascal and Modula,ACM Press

3. N. Wirth, J. Gutknecht, Project Oberon. The Design of an On*«.- c

ACM Press and Addison-Wesley, 1992. ngSystem and Computer,

4. M. Reiser, The Oberon System. User Guide and Programmed x,

Addison-Wesley, 1991. Manual,ACM Press and

5. K. Arnold, J. Gostling, The Java Programming Language ahhu™ ліг ,

6. В. Bckel, Thinking m Java. hnp://www.EckelObj« ”m 1996.

7. P. Naughton, H. Schildt, Java: The Complete Reference, McGraw-Hill iqot

8. P. Naughton, The Java Handbook, McGraw-Hill, 1996 *.1997.

9. J. Manger, Essential Java *, Developing InteractiveApplications for The World-Wide Web, McGraw-Hill, 1996.

10.N. Wirth, From Modula to Oberon, Software Practice and Experience,volume 18, number 7, July, 1988.

1 l.N. Wirth, The Programming Language Oberon, Software Practice and Experience, volume 18, number 7, July, 1988.

12. N. Wirth, Type Extensions, ACM Transactions on Programming Languages and Systems, volume 10. number 2, April, 1988.

13. N. Wirth, J. Gutknecht, The Oberon System, Software Practice and Experience, volume 19, number 9, September, 1989

14. Ph. Heuberger, A Constructive Approach to Sweep Algorithms for Voronoi Diagrams, University of Victoria, Canada, May, 1991.

УДК 658.512

Чурова А.Г.

Задача выбора стратегии для организации в условиях противодействия

внешней среды.

В предлагаемой статье обсуждается подход к решению задачи построения модели системы принятия решений по управлению государственным или коммерческим учреждением.

Решением этой задачи, является выяснение законов появления, поведения, развития и исчезновения (законов функционирования) системы управления, т.к. последняя определяется этими законами, а также своей структурой (своими элементами и способами их взаимодействия). Законы функционирования системы управления должны, с одной стороны, быть направлены на обеспечение ее бесперебойной деятельности, и, с другой стороны, обеспечивать выполнение основной задачи (или задач), стоящей перед учреждением. Чаще всего, попытки решить такую задачу лежат в русле качественных теорий и выводов, полученных путем обобщения исторического опыта, и не подкрепляются должным математическим обоснованием. Подобное положение вещей обусловлено не только новизной задачи (понимание чрезвычайной важности и полезности которой пришло только с введением рыночной системы экономических отношений) для российской науки, но и объективными причинами, связанными с трудностью учета “человеческого фактора” при построении математической модели системы управления. Ниже предлагается подход к исследованию, являющийся попыткой преодолеть проблему теоретического учета “человеческого фактора”

Систему управления организацией можно представить в виде классического “черного

ящика”.

i Надоели баннеры? Вы всегда можете отключить рекламу.