Enumerated Types in Java



Similar documents
History OOP languages Year Language 1967 Simula Smalltalk

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CS 111 Classes I 1. Software Organization View to this point:

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Chapter 1 Java Program Design and Development

Functional Programming

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java Interview Questions and Answers

Programming Languages CIS 443

AP Computer Science Java Subset

CS170 Lab 11 Abstract Data Types & Objects

J a v a Quiz (Unit 3, Test 0 Practice)

Limitations of Data Encapsulation and Abstract Data Types

The Interface Concept

Java from a C perspective. Plan

public static void main(string[] args) { System.out.println("hello, world"); } }

Moving from CS 61A Scheme to CS 61B Java

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Course Title: Software Development

Java Programming Language

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Schema Classes. Polyhedra Ltd

Software Engineering Techniques

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Java CPD (I) Frans Coenen Department of Computer Science

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

COMP 110 Prasun Dewan 1

Sudoku puzzles and how to solve them

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Syllabus for CS 134 Java Programming

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

C++ INTERVIEW QUESTIONS

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Object-Oriented Software Specification in Programming Language Design and Implementation

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

The C Programming Language course syllabus associate level

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Java Application Developer Certificate Program Competencies

Java Classes. GEEN163 Introduction to Computer Programming

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Description of Class Mutation Mutation Operators for Java

Part I. Multiple Choice Questions (2 points each):

Fundamentals of Java Programming

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Lab Experience 17. Programming Language Translation

Pemrograman Dasar. Basic Elements Of Java

Java (12 Weeks) Introduction to Java Programming Language

Part 3: GridWorld Classes and Interfaces

Tools for Integration Testing

Concepts and terminology in the Simula Programming Language

El Dorado Union High School District Educational Services

Computing Concepts with Java Essentials

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Crash Course in Java

Advanced OOP Concepts in Java

Semantic Analysis: Types and Type Checking

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

The «include» and «extend» Relationships in Use Case Models

Friendship and Encapsulation in C++

Checking Access to Protected Members in the Java Virtual Machine

Exercise 8: SRS - Student Registration System

Dealing with Roles. Martin Fowler.

Teach Yourself Java in 21 Minutes

An Incomplete C++ Primer. University of Wyoming MA 5310

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

C++FA 3.1 OPTIMIZING C++

13 File Output and Input

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

CS506 Web Design and Development Solved Online Quiz No. 01

11 November

Approach of Unit testing with the help of JUnit

Java the UML Way: Integrating Object-Oriented Design and Programming

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Explain the relationship between a class and an object. Which is general and which is specific?

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

The Online Grade Book A Case Study in Learning about Object-Oriented Database Technology

Lecture J - Exceptions

Singletons. The Singleton Design Pattern using Rhapsody in,c

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Source Code Translation

3 Improving the Crab more sophisticated programming

Programming Languages

Syntax Check of Embedded SQL in C++ with Proto

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Building a Multi-Threaded Web Server

Programmation 2. Introduction à la programmation Java

Java Server Pages and Java Beans

A Meeting Room Scheduling Problem

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

Transcription:

Enumerated Types in Java Paul A. Cairns School of Computing Science, Middlesex University, The Burroughs, Hendon, London, NW4 4BT e-mail: p.cairns@mdx.ac.uk tel: +44 (0) 181 362 6852 fax: +44 (0) 181 362 6943 1

SUMMARY Java does not contain enumerated types. This paper demonstrates how to produce classes that behave like enumerated types with secure, strong typing. Additional Pascal-like operations are easily incorporated into the enumerated types without repeating code. Full listings of the classes are given. Keywords: Java, enumerated type, enum INTRODUCTION Enumerated types (enums) are a useful tool when programming in high-level languages. They improve the readability of code by associating mnemonic names with constants; they are more efficient because the programmer need not be concerned with the assignment of values and the compiler can optimise their implementation; and they are more secure as a compiler can apply strong type-checking rules to them 1,2,3. This is not to say that enums are a universal requirement of programming languages. Enums need special treatment by a compiler, which can make a compiler less conceptually simple and as a consequence larger. For this reason they are explicitly omitted from Oberon 4. However, compiler elegance is an issue orthogonal to those listed above. Java is intended by its creators to be both easy and safe to use 5. Thus it is somewhat surprising that Java has no facility for defining enums. Indeed, the absence of enums provokes barely any comment 5,6, which is all the more surprising when investigation of the Java class libraries reveals many lists of public final static int s that could have been defined more efficiently and more securely with enums. The main aim of this paper is to describe how to define classes that behave like enums and have secure, strong typing. Kalev 7 produced an enum type in a natural way but this does not guarantee that the only constants of the enum type are the enum constants and so the typing in this technique is not secure. A secondary goal is that any errors when using the new enum classes should be made known directly and immediately rather than as side-effects. A SINGLE ENUMERATED TYPE The basic example of an enumerated type that we try to reproduce would be given in C as: 2

enum Colour {Red, Green, Blue; This means the Red, Green and Blue are constants (in fact, integers) with distinct values and of the type Colour. The two classes Palette and Colour, defined in Figure 1 and Figure 2 respectively, achieve the same result. Palette acts as a container class for the constants of type Colour. public final class Palette{ public static final Colour Red = Colour.newColour(); public static final Colour Green = Colour.newColour(); public static final Colour Blue = Colour.newColour(); Figure 1 - The class Palette import java.io.*; public final class Colour{ private final static int ENUM_SIZE = 3; private static int fnummade = 0; private Colour(){ public static Colour newcolour(){ Colour lnextelement; if( fnummade < ENUM_SIZE ){ lnextelement = new Colour(); fnummade++; else{ System.out.println( "All Colours are instantiated" ); lnextelement = null; return lnextelement; Figure 2 - The class Colour The constructor of class Colour is private so new instances of Colour can only be created through the public method newcolour(). This method restricts the number of instances of Colour that can be made to the maximum of ENUM_SIZE, in this case three. As long as Palette instantiates three Colours, there can be no other objects of class Colour and the strong-typing is secure. There is much room for expanding on these basic classes. By requiring appropriate parameters in newcolour, it is possible to associate meaningful data with a constant such as 3

a string for tostring() conversions and debugging and also an integer value, for example, Red could hold the value 0xFF0000, its RGB value. Of course, the proviso that Palette creates all possible instances of Colour is non-trivial to enforce. The constants are created in a separate class from the ENUM_SIZE and could get out of step. If too many are created by Palette then newcolour()alerts the programmer via the system console. If too few, then the program is open to corruption by an unexpected agent creating an invalid Colour 8. This problem is addressed in the next section. The system console is used to report errors because of the strict way in which Java traps exceptions. All calls to functions that may throw exceptions must be surrounded by exception catching routines. Such routines cannot be part of a final static declaration. Thus, if newcolour() were to throw exceptions there would have to be some call to the Palette class to create the constants before they could be used. This is not necessary with the current classes and there is the added bonus that Palette has a particularly simple form. A further drawback with these classes is that the constants cannot be used as case identifiers in switch statements but, as Java does not allow anything other than constants of a fundamental type as case identifiers, there is no way around this. PROLIFERATING ENUMERATED TYPES In any application of reasonable size, there are generally more than one enumerated types. Using the above technique, each such type requires two public classes and so two corresponding files in the project. Kalev believes that even one extra file per enum is worse than having no enums at all, but experience 3 and experiment 9 indicate that the advantages of strong-typing are not to be dismissed lightly. We contend therefore that the advantages of having enums outweighs the disadvantages of having two files to define them. However, it is good practice to reduce repeating code. The obvious solution would be to use inheritance and make a general super-class for all enumerator constants that handles how many of each constant type can be made. This does not work because the super-classes constructor must be protected or public for the sub-class to be created. But as soon as this is done, the sub-class s constructor also becomes public to the project containing its definition. Thus, even when the sub-class s constructor is declared private, it is possible to directly create instances of the sub-class and so have invalid instances. 4

import java.io.*; public class Registrar{ private int fnummade = 0; private String fclassname; private Hashtable fconsttable = new Hashtable(); public Registrar( String pname ){ fclassname = pname; public void Register( Object pnewel ){ fconsttable.put( new Integer( fnummade++ ), pnewel ); private class EnumerateEnumElement implements Enumeration{ private int fcurrentitem = 0; public boolean hasmoreelements(){ return(fcurrentitem < fnummade ); public Object nextelement(){ Integer lindex = new Integer( fcurrentitem++ ); return fconsttable.get( lindex ); public Enumeration elements(){ return new EnumerateEnumElement(); //other enum features... Figure 3 - The class Registrar Instead, the new class Registrar, defined in Figure 3, controls the creation of instances. public class Palette{ private static final Registrar freg = new Registrar( "Palette" ); public static final Colour Red = Colour.newColour( freg ); public static final Colour Green = Colour.newColour( freg ); public static final Colour Blue = Colour.newColour( freg ); public static Enumeration elements() { return freg.elements(); Figure 4 - The new definition of Palette 5

The Palette has a private Registrar that it uses to create all the Colours, see Figure 4. The Colour class still has a private constructor but now newcolour() simply tries to Register() any new elements with the given Registrar. In order to be consistent, the first Registrar that is used to create a Colour must be used in creating all subsequent Colours. Failure to do so results in an error, see Figure 6. The collaboration required to set up the Palette class is described using UML in. Figure 5 - Collaboration diagram to define Palette Provided Palette gets in first at creating Colours no-one else can do so as its Registrar is not available to anyone else. This registration is still not foolproof but if someone goes to all the effort of creating a Registrar to pass to Colour before Palette does, then they obviously do not want their program to work! Even in this case, when Palette comes to be used, error messages are generated. public final class Colour{ private static Registrar fregistrar = null; private Colour(){ public static Colour newcolour( Registrar preg ) { Colour lnewelement = null; if( fregistrar == null) fregistrar = preg; if( fregistrar == preg ) { lnewelement = new Colour(); preg.register( lnewelement ); else System.out.println( "Invalid registrar for Colour" ); return lnewelement; Figure 6 - The new definition of Colour 6

Note, with this technique the number of constants in the enum does not need to be explicitly stated thus avoiding the possibility of the number of constants created getting out of step with the expected size of the enum. The Registrar class comes into its own in providing more sophisticated enum operations such as those supported by Pascal. Here Registrar can create an Enumeration object for the enum so that the enum can be treated as an ordered list of constants. The Enumeration is made public via the Palette class. In a similar way, it would be possible to have methods corresponding to the Pred and Succ methods of Pascal. To create more enumerated types is now a simple exercise. The modifications to Palette should be obvious. As for Colour, it is simply a matter of replacing all references to Colour with references to the new type. This is a self-contained task, which throws up compiler errors if not done correctly. Sub-ranges are another way of employing enums. With these, the original list of constants is restricted to some special subset, for example, Colour might have the sub-range NotBlue made up of only Red and Green. Cardelli proposes a method of defining sub-ranges using inheritance 10 however in this scheme the elements of the original enum are not constants but types. In Java, this would translate to one file for every enum constant! Building on the classes given here, sub-ranges could be crudely defined as shown in. Supporting operations, such as checking for membership of the sub-range and an Enumeration only over the sub-range, could also be provided by using a variation on Registrar. These are issues away from the aims of this paper and are left as an exercise for the interested reader. public final class NotBlue{ public static final Colour Red = Palette.Red; public static final Colour Green = Palette.Green; Figure 7 - The sub-range NotBlue 7

CONCLUSIONS It is possible to create objects in Java that behave like enumerated types with secure strongtyping. They can even be embellished to support more sophisticated features such as those supported in Pascal and even tostring() conversions. Moreover, it can be done so that only a small amount of code must be repeated for each new type. Some code must always be repeated as inheritance is not an available technique. The main problem of course is with the Java language itself 11. It seems that in eliminating the variety of types available to C and Pascal, Java has thrown the baby out with the bath-water. ACKNOWLEDGMENTS Many thanks to Prof. Harold Thimbleby and Dr. Matt Jones for their helpful advice and suggestions. REFERENCES 1. S. McConnell, Code Complete, Microsoft Press, 1993 2. B. W. Kernighan and D. M. Ritchie, The C Programming Language, 2 nd edn., Prentice- Hall, 1988 3. N. Wirth, An Assessment of the Programming Language Pascal in A. Feuer and N. Gehani (eds.), Comparing and Assessing Programming Languages, Prentice-Hall, 1984 4. N. Wirth, From Modula to Oberon, Software - Practice and Experience, 18(7), 661-670 (1988) 5. K. Arnold and J. Gosling, The Java Programming Language, 2 nd edn., Addison-Wesley, 1998 6. J. Gosling, B. Joy and G. Steele, The Java Language Specification, Addison-Wesley, 1996 7. D. Kalev, Porting C++ Applications to Java C/C++ Users Journal, 16(2), 73-82 (1998) 8. T. Pratchett, The Colour of Magic, Corgi (Paperback), 1983 9. J. D. Gannon, An Experimental Evaluation of Data Type Conventions CACM, 20(8), 584-593 (1977) 10. L. Cardelli, A Semantics of Multiple Inheritance, Information and Computation 76, 138-164 (1988) 11. H. Thimbleby, Java - a critique, Software - Practice and Experience, to appear In the code listings, all variables have prefix of either f, l or p. f denotes a field in an object, l denotes a variable local to a method and p denotes a parameter passed to a method. Thus, rather than a more usual 8

Hungarian notation denoting the type of the variable, the prefix denotes the scope of the variable. In objectoriented languages where types abound, the author has found this to be more useful information. 9