File Handler program

796 views

Published on

University report documenting a Java program designed t

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
796
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

File Handler program

  1. 1. Cover page has been removed for security reasons
  2. 2. CONTENTS1. Introduction To The Problem ................................................................................................................ - 4 -2. Explanation Of Process .......................................................................................................................... - 5 -3. Section One ........................................................................................................................................... - 7 - 3.1 Features List ..................................................................................................................................... - 8 - 3.2 Context Diagram .............................................................................................................................. - 9 - 3.3 Use Case Diagram .......................................................................................................................... - 10 - 3.4 Requirements Specification Document ........................................................................................... - 12 - 3.5 Class, Responsibilities And Collaborators ........................................................................................ - 13 - 3.6 Class Diagrams ............................................................................................................................... - 15 - 3.7 Hierarchical Task Analysis............................................................................................................... - 17 - 3.8 Pseudocode – Level One ................................................................................................................ - 18 - 3.9 Pseudocode Level Two ................................................................................................................... - 19 - 3.10 Pseudocode – Level Three ............................................................................................................ - 21 - 3.11 Commented Code Listing ............................................................................................................. - 23 - 3.12 Testing (Software Validation) ....................................................................................................... - 27 - 3.13 Component Testing .................................................................................................................. - 28 - 3.14 Black Box Testing ...................................................................................................................... - 29 - 3.15 Design (Stage 2) ........................................................................................................................... - 34 - 3.16 Acceptance Testing .................................................................................................................. - 36 - 3.17 White Box Testing .................................................................................................................... - 37 -4. Section Two......................................................................................................................................... - 39 - 4.1 Features List ................................................................................................................................... - 40 - 4.2 Context Diagram ............................................................................................................................ - 42 - 4.3 Use Case Diagram .......................................................................................................................... - 43 - 4.4 Requirements Specification Document ........................................................................................... - 45 - 4.5 Class, Responsibilities And Collaborators ........................................................................................ - 46 - 4.6 Class Diagrams ............................................................................................................................... - 48 - 4.7 Hierarchical Task Analysis............................................................................................................... - 51 - 4.8 Graphical User Interface Designs .................................................................................................... - 52 - 4.9 Pseudocode – Level One ................................................................................................................ - 58 - -2-
  3. 3. 4.10 Pseudocode – Level Two .............................................................................................................. - 61 - 4.11 Possible Problems And Solutions .................................................................................................. - 64 - 4.12 Commented Code Listing ............................................................................................................. - 65 - 4.13 Testing (Software Validation) ....................................................................................................... - 84 - 4.14 Filehandler Component Test..................................................................................................... - 85 - 4.15 Defect Testing / Debugging .......................................................................................................... - 88 - 4.16 Acceptance Testing .................................................................................................................. - 90 -5. Section Three ...................................................................................................................................... - 91 - 5.1 System testing ............................................................................................................................ - 92 -6. Reflection .......................................................................................................................................... - 106 -7. Glossary ............................................................................................................................................ - 107 -8. Bibliography ...................................................................................................................................... - 108 -9. Appendix ........................................................................................................................................... - 110 - -3-
  4. 4. 1. INTRODUCTION TO THE PROBLEMPROBLEM STATEMENTDesign an application that reads a specific file / set of files. Once read they should be displayed.REQUIREMENTSR1. Design problem: design an application that reads a specific file, once read the file should be displayed.R2. Plan the design phase and develop implementation of design.R3. Test implementation.R4. Design problem: design an application that reads a sequence (set) of files, once read the files should be displayed.R5. Plan the design phase and develop implementation of designR6. Test implementationR7. Reflection -4-
  5. 5. 2. EXPLANATION OF PROCESSINTRODUCTIONThe Waterfall model, developed in the 1970’s, can be defined as having ‘distinct stages’ – namelyrequirements specification, software design, implementation and testing – whereby each stage iscompleted before the next one commences. The major disadvantage to this approach is due to its“inflexible partitioning” (Sommerville, 2007), meaning that commitments must be made early on in thedevelopment. Therefore, if requirements are likely to change during the course of the project, then theWaterfall model may not be the best approach. In 2000, a study of failure factors in IT projects in the UKshowed that ‘scope management’ 1 related to using the Waterfall model was the largest problem in 82%of all projects (Taylor, 2000).A more flexible approach is evolutionary development, in which initial solutions are developed andshown to the user of the system, then “refining it through many versions until an adequate system hasbeen developed” (Sommerville, 2007). Another way of defining it is that it encompasses “quicklyevolving towards stakeholder values and product qualities, while learning through early feedback”(FIRM, 2005). This implies that a higher quality of system will be produced as the requirements can beamended easily; therefore more time can be spent on the overall design and functionality of the system.It can be argued that evolutionary development will be the most efficient approach to solve theproblems proposed in this report. Although requirements are not likely to change radically as there areno end-users, requirements still can change as new techniques are discovered. Evolutionarydevelopment allows for new ideas to develop and be implemented which, although they may not be akey requirement, add to the overall usability and efficiency of the system. In addition to this, theproblem seems to lend itself to evolutionary development. This is because requirements 1-3 can beimplemented primarily and requirements 4-6 can be seen as the evolution of the software, and willrefine the system to produce an adequate solution to the problem. The stages of evolutionarydevelopment are displayed in Figure 1.Sommerville suggests that there are two types of evolutionary development; exploratorydevelopment and throwaway prototyping. Exploratory development involves the system beingdesigned using the requirements which are known, and then expanding and evolving this by addingnew features. Throwaway prototyping involves developing different types of system to betterunderstand the requirements. This is done by showing prototypes2 to the user and evaluating theresponse.With regard to this, it is suggested that exploratory development would be more effective for use in thisproject. This is due to the idea that throwaway prototypes are often time-consuming and concentrateon further understanding the requirements. The requirements are clear in this project but there is roomfor expansion, so exploratory development is the most appropriate tool to utilise.1Scope Management: the processes required to ensure that the project includes all the work required, and onlythe work required, to complete the project successfully. (Project Smart, 2008)2Prototype: A less formal experimental development process of a proposed application for the purpose ofdemonstrating some or all of its functional capabilities (California State University, 2005). -5-
  6. 6. REFLECTIONThis report will be separated into three main sections; section 1 (which covers requirements 1-3 3) andsection 2 (which covers requirements 4-6 4). In section 1, requirements will be gathered by using anumber of UML tools and an initial version prototype will be developed. This prototype will completerequirements 1-3. In section 2, more requirements will be elicited and the initial version will beupdated and redefined. New prototypes will be made which will aim to increase the efficiency of theinitial system and incorporate the new requirements (requirements 4-6). After the system has beendeveloped it will be tested to ensure that it satisfies all requirements. The testing stage (section 3) willbe the last stage in the report. This will also include reflection statements on the processes undertaken.To summarise, this project will follow an evolutionary development framework using exploratorydevelopment to develop a fully functioning system that fulfils all the requirements. FIGURE 13 Requirements 1-3 summarised: Design, plan and test an application that reads and displays a specific file.4Requirements 4-6 summarised: Design, plan and test an application that reads and displays a sequence of fileswith appropriate user interface. -6-
  7. 7. 3. SECTION ONEAt the end of this section the first iteration of the system will be made. The general structure of thesection comprises of:- During this stage UML diagrams will be used to determine the functionality that the system 1. Requirements elicitation must produce. A final list of requirements will be defined in order to test that the system has been designed and developed correctly. More UML diagrams will be designed at this stage to give a better understanding of how the 2. Design system will be built. The finished code listing will be in this section. 3. Implementation The code will be tested using component, system, and acceptance testing. If any errors are found 4. Testing they will be documented in this section.The final product will be evaluated and expanded in Section 2. -7-
  8. 8. 3.1 FEATURES LISTINTRODUCTION TO FEATURES LISTSA features list is an abstract tool used to gather the most basic of requirements. Essentially it is “a list offeatures that the proposed system should possess” (Neville, Feature List, 2008).FEATURES LISTThe initial program must:- 1. Read a specific file 2. Display the contents of the file 3. Display the file nameREFLECTIONAt this stage there is too little detail given to start the implementation of the system. However, ithighlights the fact that the main feature will be the system’s ability to read files. Java provides classes toimplement such tasks. Data can be encoded in three ways; text encoding, binary encoding and object-encoding (Charatan & Kans, 2006), and the different types of encoding offer different ways of readingfiles.Binary encoding is stored as the internal representation of the data (for example the number 107 wouldbe stored as 1101011). Binary files cannot be properly read by a text editor and so will not beappropriate in this project, as the files that will be used to test the functionality of the program are text(.txt) files.Object-encoding is a Java tool in which a whole object 5 can be input or output.Text encoding, where the data is stored as characters on the disk, will be the encoding used in thisproject. This is due to the aforementioned files being .txt files.The FileReader and BufferedReader are used to read text encoded files. The FileReader “dealswith the low-level details involved in the process of reading a file” (Charatan & Kans, 2006). TheBufferedReader then ‘wraps 6’ the FileReader object to a BufferedReader object. This allowsus to call methods 7 on that object to read it, e.g. the readLine() method, which reads a line of textfrom a file.Also in Java is a ‘File’ class, which is “an abstract representation of file and directory pathnames”(Sun Microsystems, 2001). It creates a File object when it is passed the path name of a file.5 Object: An instantiation of a class6 Wrapper classes in Java: Converts a primitive data type, e.g. int, to a class, e.g. Integer (Charatan & Kans, 2006)7 Method: “Performs a single, well-defined task” by implementing a particular set of instructions -8-
  9. 9. 3.2 CONTEXT DIAGRAMINTRODUCTION TO CONTEXT DIAGRAMSContext diagrams show the environment that the system (artifact) will work in (Neville, ContextDiagrams, 2008).Key: An actor 8 of the system A message that is passed Declares an interaction between system and actor Object / artifactCONTEXT DIAGRAMREFLECTIONThe main actor of the system is the user. The user inputs data to the system and is shown output fromit. The other two actors – display and keyboard – can be combined to make one actor; the ‘system’.8 Actor: The users of the system -9-
  10. 10. 3.3 USE CASE DIAGRAMINTRODUCTION TO USE CASE DIAGRAMSUse case diagrams “define the interaction between actors and the system”, and “encapsulate a set ofscenarios” 9 (Sommerville, 2007). They are a high level of abstraction and are primarily used todetermine interactions; therefore they are “not as effective for eliciting constraints and non-functionalrequirements” (Sommerville, 2007).Although there is no standard way to write a use case, a common style is to first choose the mainscenario and write a sequence of steps, written from the perspective of the user. The next stage is todefine other scenarios (extensions). From these scenarios, actors and interactions can be established.USE CASE TEXTGOAL: Display a fileMain success scenario: 1. User types file that they want to display 2. System displays the name of the file 3. System reads the file and displays its content to the user 4. User chooses to exit the programExtensions: 1. User chooses a file that does not exist a. System displays message that error occurred 3. The system cannot read the file line by line (e.g. if file was encoded in binary) a. System displays message that error occurred9 Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004) - 10 -
  11. 11. DIAGRAM:REFLECTION:It can be seen from the use-case diagram that the two actors are the user and the system, following onfrom the context diagram. More requirements have now been established which add to the functionalityof the system. One new concept is ‘displaying the file name’.This can be done if a File object is created using the pathname (location) of a file (e.g.D:DocumentsFileHandlerProject7179881TextAndSpCh.txt”). Then a method called getName() canbe called to get the name of that file.Another new requirement is the system’s ‘exception 10 handling’ requirement. When a file is read usingthe FileReader and BufferedReader classes, two exceptions can occur. One is theFileNotFoundException, which occurs if the pathname was incorrect and the file does not exist.The other is an IOException, which occurs if there was a general problem reading the file.10Exception: An event that occurs during the life of a program which could cause that program to behaveunreliably. - 11 -
  12. 12. 3.4 REQUIREMENTS SPECIFICATION DOCUMENTINTRODUCTIONThis document contains a formal list of specifications that must be adhered to, and will be used in theacceptance testing of the system. It is the “official statement of what the developers should implement”(Sommerville, 2007). Each specification will be given a number between 1 and 3 corresponding to itsimportance, i.e. level 1 requirements are essential and level 3 are optional.There are two main types of requirement; functional requirements and non-functional requirements.Functional requirements “are statements of services the system should provide” (Sommerville, 2007).Non-functional requirements are not “directly concerned with the specific functions” (Sommerville,2007). Instead, they may relate to the reliability, speed and appearance of the system.REQUIREMENTS SPECIFICATION The system must display the file name. FunctionalLevel Specification Type of requirement The system must display the file content. Functional1 The user must be given a choice of what file to load. Functional1 The system should provide error handling in case a file cannot be Non-functional1 loaded.1 The user should be informed of any errors in the program. Non-functional The system should respond quickly (within 1 second) to user Non-functional1 commands.2 - 12 -
  13. 13. 3.5 CLASS, RESPONSIBILITIES AND COLLABORATORSINTRODUCTION TO CRC DIAGRAMSCRC diagrams are used in the form of index cards, which are used as a “visual (textual) abstractionmethodology that follows a “divide and conquer” problem/solution methodology” (Neville, ClassResponsibilities and Collaborators, 2008). They aim to break down the problem into sub-problemswhich can then be used to define the structure of the classes of the system.Notation: Responsibilities are the tasks that the class will undertake. Class Name Collaborators indicate which tasks are Responsibilities Collaborators undertaken by other classes.DIAGRAMSFirst draft of diagram FileReader Displays the file name Responsibilities Collaborators Displays the file content Asks the user to input a file path Read a file line by line Check a file exists Handle errors when file is readSecond draft of diagram TextFile Read a file line by line Responsibilities Collaborators Check the file exists TextFileProgram Save the name of the file to a variable Save the content of the file to a variable Handle errors when file is read TextFileProgram Displays the file name TextFile Responsibilities Collaborators Displays the file content TextFile Asks the user to input a file path - 13 -
  14. 14. REFLECTIONThe first draft of the CRC card illustrates that there are a lot of exceptions that could occur. It wasdecided to create an object that would represent a file, as there is more cohesion in the component.Cohesion is a key principle for software design. It “describes the interactions within components” (Zeng,Software Design Methods, 2007).Another principle that Zeng suggests is ‘modularity’, where large software systems are decomposedinto smaller, more independent components. It allows complexity to be managed. Both of theseprinciples are adhered to in the redesign of the CRC cards.Thus, in the second version of the CRC cards, the system has two classes, one which will ask the user fora file location and one to store that file as an object.An interesting point to note here is the use of ‘inheritance’. Inheritance is “the sharing of attributes andmethods among classes. New classes inherit all of the attributes and methods of the first class, but alsohave attributes and methods of their own” (Charatan & Kans, 2006). A File object needs to be createdin order to get the name of the file, and to use in the FileReader class to read its content. However,the File class contains a lot of methods but does not contain all the functionality required for thisproblem. Therefore, a ‘type of’ File object will be created (called a TextFile) which inherits themethods of the File class and adds its own. This is notated in Java by: or alternatively,The location of the file that the user wants to display is passed to the TextFile class which will get itsClassB extends ClassA, TextFile extends File.name and store it, and get its content and store it (by using the FileReader and BufferedReader).Any exceptions caused by the file will be handled in this class.When the object has been created it will be passed back to the TextFileProgram class which will callmethods on the TextFile object to get its name and content.Another principle suggests maximising the information hiding, where components “hide the internaldetails and processing from one another” (Zeng, Software Design Methods, 2007). This is the reason forcalling a ‘getter’ method (e.g. getName()) rather than trying to get the name attribute of theTextFile object itself. These variables will be made private to increase the information hiding. - 14 -
  15. 15. 3.6 CLASS DIAGRAMSINTRODUCTION TO CLASS DIAGRAMSClass diagrams are widely used in software development and “describes the types of objects in thesystem and the various kinds of static relationships that exist among them” (Fowler, 2004). Attributes Class Name MethodsAttributes are represented in the form of:Methods are represented in the form of:Visibility name : type multiplicity = default {property-string}The parameters in the parameter-list are represented as:Visibility name (parameter-list) : return-type {property-string}Arrows represent an association between classes, and the numbers on the arrow represents thedirection name : type = default valuemultiplicity11 * Student 1 Class 2.1 Fig E.g. Fig 2.1 shows that a Class can have zero or more Students but a Student can only have one ClassDIAGRAM -name : String TextFile -content : String 1 1 TextFileProgram -testTextFile : TextFile +TextFile(s : String) : null +getName() : String +getContent() : String +readFile(f : File) : String11 Multiplicity: an indication of how many objects may fill the property (Fowler, 2004). - 15 -
  16. 16. REFLECTIONThese class diagrams indicate that the TextFileProgram class can have one TextFile and aTextFile can only have one TextFileProgram class. Therefore a user can only enter the pathnameof one specific file and that file is created into a TextFile object. Each of those TextFile objects canbe accessed by the TextFileProgram class that sent in the original pathname.The TextFile class contains ‘name’ and ‘content’ variables which are declared as private (representedby the – symbol). This means that they can only be accessed by the TextFile class. The getName()and getContent() methods (commonly referred to as ‘getter’ methods) enable the values of thosevariables to be passed to the TextFileProgram class when needed, but not changed directly. Tosummarise, the TextFileProgram class will only get a copy of the name and content data, and notthe ‘real’ data.Errors can occur in the readFile() method as previously discussed (see the reflection section onpage 11). The readFile() method returns a string. This string will either be a string containing anerror message, if an error occurred, or containing the content of the file if no error occurred. The reasonfor doing this is to ensure that the program does not crash for the user at any time in theTextFileProgram class. Therefore, if an error occurs then the TextFile object will still have thename and content variables for the TextFileProgram class to ‘get’, but the content itself mayindicate an error. - 16 -
  17. 17. 3.7 HIERARCHICAL TASK ANALYSISINTRODUCTION TO HTA DIAGRAMSHierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when theyare performed” (Stevens, 2008).The structure of a hierarchical task diagrams usually consists of “a goal at the top, followed by sub-goals, unit tasks and artifacts. Sub-goals may be further sub-divided as required” (ACM, 2005). Thesegoals are normally written from the perspective of the user.DIAGRAM Main Goal  Do all steps in orderREFLECTIONThis is a very simple diagram which shows the user process through the proposed system. - 17 -
  18. 18. 3.8 PSEUDOCODE – LEVEL ONEINTRODUCTIONPseudocode is used for describing algorithms. It “allows the designer to focus on the logic of thealgorithm without being distracted by details of language syntax” (Dalbey, 2003). The first level of thepseudocode is very basic as it is intended to give a better idea of program flow.PSEUDOCODE1. System prompts user to enter a pathname – user enters pathname and presses enter2. System stores pathname to variable3. System prompts user to enter a filename – user enters filename and presses enter4. System stores filename to variable5. Create TextFile object by combining pathname and filename variable to constructor i. TextFile class sends pathname to superclass File ii. If error occurs with file name 1. Save error message as name variable iii. Else, 1. Save name of file as variable iv. Save content of file as variable 1. Get File object from superclass File 2. Use FileReader on the File object 3. Use BufferedReader on the FileReader object 4. Read file line by line until end of file 5. If error occurs a. Save error message as content variable6. System uses getName() method to display the name of the file7. System uses getContent() method to display the content of the fileREFLECTIONThis pseudocode makes it easier to begin to think about the Java code for implementing this system. - 18 -
  19. 19. 3.9 PSEUDOCODE LEVEL TWOINTRODUCTIONThe second level of the pseudocode aims to use the syntax of the Java language to describe systemprocesses and artefacts that are produced by the system.PSEUDOCODE1. Open the TextFileProgram class i. In the ‘main’ method 1. Create new Scanner object to read in Strings from the user 2. System println() method – “Please enter a pathname” 3. path variable = next() method of Scanner object 4. System println() method – “Please enter a filename” 5. name variable = next() method of Scanner object 6. pathname variable = path and name combined 7. Create new TextFile and pass pathname variable as parameter2. To create new TextFile, first open the TextFile class 1. TextFile constructor method i. Send string variable into superclass by the super() method ii. name variable= getName() method of the super class iii. Get File object from superclass with getAbsoluteFile() method iv. content variable = call readFile() method, passing the File as a parameter 1. readFile() method a. try: b. Create new FileReader passing in the file as a parameter c. Create new BufferedReader passing in FileReader object as a parameter d. Variable ‘temp’ = call the readLine() method of BufferedReader e. Loop until the readLine() method returns null i. Variable ‘contentRead’ adds the ‘temp’ String to itself ii. temp = call readLine() method - 19 -
  20. 20. f. Close the BufferedReader g. catch FileNotFoundException exception i. return the String "The file was not found"; h. catch IOException exception i. return the String "There was an IO error";3. Open class TextFileProgram i. Open main method 1. System calls println() method with the following as a parameter: a. System calls getName() method of TextFile b. System calls getContent() method of TextFileREFLECTIONThis pseudocode provides a good foundation upon which entire lines of Java code can be written. - 20 -
  21. 21. 3.10 PSEUDOCODE – LEVEL THREEINTRODUCTIONThe third level of the pseudocode aims to entirely use the syntax of the Java language to describe theprocess in such a way that it can be transferred directly into a Java editor.PSEUDOCODE 1. class TextFileProgram i. public static void main(String args[]) 1. Scanner sc = new Scanner(System.in); 2. System.out.println(“Please enter a pathname”); 3. path = sc.next(); 4. System.out.println(“Please enter a filename”); 5. name = sc.next(); 6. pathname = path.trim() + name.trim(); 7. TextFile newTextFile = new TextFile(pathname); 2. public TextFile(String s) i. super(s); ii. name = super.getName() iii. content = readFile(super.getAbsoluteFile()) 1. public readFile(File file) a. try: b. FileReader textfile = new FileReader(file); c. BufferedReader textfile = new BufferedReader (textfile); d. temp = stream.readLine(); e. while (temp!=null) i. contentRead += temp + "n"; ii. temp = stream.readLine(); f. stream.close(); g. catch (FileNotFoundException e) - 21 -
  22. 22. i. return "The file was not found"; h. catch (IOException e) i. return "There was an IO error"; 3. class TextFileProgram i. public static void main(String args[]) 1. System.out.println(getName() + “nn” + getContent());REFLECTIONThis pseudocode now can be transferred to a Java editor to finish the coding. - 22 -
  23. 23. 3.11 COMMENTED CODE LISTINGINTRODUCTIONThere will be two documents in this section. One document is the code for the TextFile class, the other isfor the TextFileProgram class.CODE LISTING CLASS TEXTFILE/************************************************Class TextFileDescription: A class from which objects of TextFiles can be made*************************************************///The class is declared as part of the filehandlerproject package.package filehandlerproject;//Import statements. IO is needed in this class to handle the file readingimport java.io.*;//The classpublic class TextFile{ //Variable declaration String name; //To store the name of the file String content; //To store the content of the file /************************************************************** The constructor of the class. Takes a File object as a parameter ***************************************************************/ public TextFile(String s) { //sends the location string to the File superclass super(s); /*instantiates name by calling built-in getName() method of File class, it calls the superclass object to get this*/ name = super.getName(); /*instantiates content by calling readFile method of this class and sending it the string containing the location of the file according to the File superclass*/ content = readFile(super.getAbsoluteFile()); } /**************************************************************** - 23 -
  24. 24. The getName() method of the class. Returns a String*****************************************************************/public String getName(){ /*If the getName() method return null then a file was not found. If it is not null then a name was found*/ if (name!=null) { return name; //returns String name } else //name was null { /*Returns a string that will show when getName() method is called. It will help the user in understanding what went wrong*/ return "The name of the file could not be determined"; }}/****************************************************************The getContent() method of the class. Returns a String*****************************************************************/public String getContent(){ return content; //returns global private variable}/***************************************************************The readFile() method of the class. Returns a String and takes a File asparameter and calls it i*****************************************************************/public String readFile (File i){ String contentRead = ""; //declares local empty String variable String temp = ""; //declares local empty String variable //try-catch block is used for the code in which errors can occur try { /*makes a new FileReader object called textfile by passing in a File object variable called i*/ FileReader textfile = new FileReader(i); /*makes a new BufferedReader object called stream by passing in a FileReader object variable called textfile*/ BufferedReader stream = new BufferedReader(textfile); /*the readLine() method is called on the BufferedReader*/ temp = stream.readLine(); //do this loop until the file reaches the end while (temp!=null) - 24 -
  25. 25. { /*adds the line from the file to the contentRead variable, and adds a new line after each line so that the whole file will not be on one line*/ contentRead += temp + "n"; /*the readLine() method is called on the BufferedReader again*/ temp = stream.readLine(); } //closes the file for reading stream.close(); } //if the file was not found in the location catch (FileNotFoundException e) { /*returns string to let user know that an error occured. This variable is stored as the content of the file*/ return "The file was not found"; } catch (IOException e) { /*returns string to let user know that an error occured. This variable is stored as the content of the file*/ return "There was an IO error"; } /*if the program has reached this stage then there was no error so the content of the file can be returned as a String to be stored*/ return contentRead; }} CLASS TEXTFILEPROGRAM/************************************************Class TextFileProgramDescription: A tester class for the TextFile class which chooses files to display*************************************************///The class is declared as part of the filehandlerproject package.package filehandlerproject;//Import statementsimport java.io.*; //IO is needed in this class to handle the file creationimport java.util.Scanner; //Scanner class is used to read in characters from//the users keyboard//the main classpublic class TextFileProgram - 25 -
  26. 26. { //the main method in the class public static void main(String args[]) { //creates a new Scanner object to read the content from the user Scanner sc = new Scanner(System.in); //prints a line of code to the output window System.out.println("Please enter the location of the file, e.g D:Documents : "); //saves the String that the user types to the location variable String location = sc.next(); /*if the user forgets to put the character at the end of the location variable then it needs to be added to ensure that the file is found*/ if (!location.endsWith("")) { //the location string adds a to the end of it location+=""; } //prints a line of code to the output window System.out.println("Please enter the full name of the file: "); //saves the String that the user types to the name variable String name = sc.next(); //creates a TextFile object called testFile by passing the string location of the file TextFile testTextFile = new TextFile(location + name); //prints a line of code to the output window with the name and content of //the file that the user entered by calling the getter methods. System.out.println( "nn"+ //creates a new line "Title: " + testTextFile.getName() + //calls getName() method "nn" + //creates a new line testTextFile.getContent() //calls getContent() method ); }} //end of class TextFileProgram - 26 -
  27. 27. 3.12 TESTING (SOFTWARE VALIDATION)INTRODUCTIONThe first iteration of the system has been completed. At this stage it is essential to test that the system iserror-free and it fulfils all requirements.Software validation comprises of three distinct stages. ‘Component testing’, ‘System testing’ and‘Acceptance testing’.A diagrammatical representation of the three stages is shown in Figure 2.As the system has not been fully completed, only the first stage (component testing), and last stage(acceptance testing) will be undertaken. FIGURE 2 - 27 -
  28. 28. 3.13 COMPONENT TESTINGINTRODUCTIONComponent testing involves the testing of individual components of the system. They are tested toensure that they operate correctly.A “Test harness” will be used to assess the functionality of each of the components. Put simply, testharnesses are “a system to handle the elements you’ll repeat each time you write a test” (Rowe, 2008).It can be argued that the TestFileProgram component is a form of test harness in itself. This is dueto its dependence on the TextFile component. However, as it requires user input from the keyboardit is more susceptible for human errors. For that reason, another test harness will be created for theTextFile component.Black box testing focuses on “whether the class meets the requirements stated in the specification”(Dennis, Wixom, & Tegarden, 2005). It “assumes no knowledge of the program code or design” (Zeng,Software Testing, 2008).Test harnesses are a feature of white box testing. White-box testing is when the system developerlooks “inside the class to review the code itself to discover errors or assumptions not immediatelyobvious to someone treating the class as a black box.” (Dennis, Wixom, & Tegarden, 2005) - 28 -
  29. 29. 3.14 BLACK BOX TESTINGINTRODUCTIONIn this section, test data will be used to run the program to ensure that the system fulfils therequirements set out in the specification. TEST RUN ONEDESCRIPTION AND TEST DATAIn the first example the location that will be entered will be entered without the backslash () characterat the end of it. This is to test that the program adds a backslash character to the end as was intended. Ifthe character is not added then the program will fail. The user input is represented by an arrow.OUTPUTREFLECTIONThe test run was a success; the file was displayed correctly even though the was omitted. - 29 -
  30. 30. TEST RUN TWODESCRIPTION AND TEST DATAIn the second example the location that will be entered will be entered with the backslash () characterat the end of it. This is to test that the program doesn’t add a backslash to the end when one exists. Theuser input is represented by an arrow.OUTPUTREFLECTIONThe test run was a success; the file was displayed correctly even though the was present. - 30 -
  31. 31. TEST RUN THREEDESCRIPTION AND TEST DATAIn the third example the filename will be misspelled. The user input is represented by an arrow.OUTPUTREFLECTIONThe test run was a success, the file name was displayed to the user with a message that the file could notbe found. The file name is still shown here (7179881TextAndData.txts) so that the user notices andrectifies their mistake. - 31 -
  32. 32. TEST RUN FOURDESCRIPTION AND TEST DATAIn the third example we will test what happens when a different type of file (other than a text file) isloaded. In this example a .jpg (image) file will be loaded. Image files are stored in binary format so theprogram is expected to show a list of unreadable characters. The user input is represented by an arrow.OUTPUTREFLECTIONThe test run was a success, the file name was displayed to the user with the content of thereadLine() method. However, image files are not shown this way so this can be quite confusing forthe user. A way in which this can be avoided is to only allow text files to be entered. First, another typeof file will be loaded to see the results. - 32 -
  33. 33. TEST RUN FIVEDESCRIPTION AND TEST DATAIn the fifth example we will again test what happens when a different type of file (other than a text file)is loaded. In this example a .pdf (portable document format) file will be loaded. It is unsure what toexpect the program to display. The user input is represented by an arrow.OUTPUTREFLECTIONThe test run was a failure; the program only output this data after approximately 25 minutes. This couldbe problematic and confusing for a user. One of the specifications of the program stipulates that theprogram will respond within 1 second of user input. Therefore it shows that a filter is needed to ensurethat only .txt files are input by the user. We will now return to the design phase to resolve this problem. - 33 -
  34. 34. 3.15 DESIGN (STAGE 2)INTRODUCTIONWhen the user enters a file other than a text (.txt) file, the system behaves erratically. Therefore a test toensure that the user only enters a filename with “.txt” as the suffix will be needed.DESIGNThe constructor method of TextFile is shown below. public TextFile(String s) { //sends the location string to the File superclass super(s);As the method call to the superclass must be the first line of code, the check that the filename ends in“.txt” cannot be placed in this class. Therefore, we must incorporate this check into the class that callsthis method, namely the TextFileProgram class, shown below. //saves the String that the user types to the name variable String name = sc.next();The String class has a method called ‘endsWith()’ which takes a string as parameter to test. Thus, wecan modify the code to include this method. The pseudocode of this code snippet would be:- 1. Get String from user 2. If String does not end in “.txt” 3. Display message that it must be a .txt file 4. Prompt for another StringThe Java code for this would be:-//prints a line of code to the output windowSystem.out.println("Please enter the full name of the file: ");//saves the String that the user types to the name variableString name = sc.next();//loop until a text file is entered while (!name.endsWith(".txt")) { //prints a line of code to the output window System.out.println("Please enter a filename ending with .txt"); - 34 -
  35. 35. //prints a line of code to the output window System.out.println("Please enter the full name of the file: "); //saves the String that the user types to the name variable name = sc.next(); }RESULTThe modifications have been made to the code, and Test 5 will now be repeated to see the outcome. It isexpected that the program will loop until a text file is entered. The user input is represented by anarrow.REFLECTIONThe test was a success, now the first iteration need to be checked against its specification. - 35 -
  36. 36. 3.16 ACCEPTANCE TESTINGINTRODUCTIONThe requirements specification will be checked against the output of the program to ensure that itmeets the specificationREQUIREMENTS SPECIFICATION The system must display the file name.Level Specification Fulfils requirement? The system must display the file content.1 YES The user must be given a choice of what file to load.1 YES The system should provide error handling in case a file cannot be1 YES loaded.1 YES The user should be informed of any errors in the program. The system should respond quickly (within 1 second) to user1 YES commands.2 YESREFLECTIONThe system meets all specifications, so the black box testing is complete. - 36 -
  37. 37. 3.17 WHITE BOX TESTINGINTRODUCTIONIn white-box testing, “every path through the program is executed at some time” (Zeng, SoftwareTesting, 2008). A test harness has been written to test the methods of this class. This test harness willbe run and the results will be noted in a table. TEXTFILE COMPONENT TEST/************************************************Class TextFileTester_1Description: A tester class for TextFile which chooses files to display*************************************************///The class is declared as part of the filehandlerproject package.package filehandlerproject;//the main classpublic class TextFileTester_1{ //the main method in the class public static void main(String args[]) { /*creates a TextFile object called testFile by passing the location and name of a file*/ TextFile testTextFile = new TextFile("D:Documents7179881TextAndData.txt"); //prints a line of code to the output window with the name and content of //the file that the user entered by calling the getter methods. System.out.println( "nn"+ "Test 1, get the file name: " + testTextFile.getName() + //calls getName() method "nn" + //creates a new line "Test 2, get the content of the file:n" + testTextFile.getContent() + //calls getContent() method "Test 3, get name and content as String: " + testTextFile.toString() ); /*Test 4 creates a new TextFile with the same path name and calls the equals method to see if they equal each other*/ TextFile testTextFile2 = new TextFile("D:Documents7179881TextAndData.txt"); boolean equals = testTextFile2.equals(testTextFile); System.out.println("Test 4:does testTextFile2 equal testTextFile? " + equals); /*Test 5 creates a new TextFile with a different path name and calls the equals method to see if they equal each other*/ TextFile testTextFile3 = new TextFile("D:Documents7179881TextAndSp.txt"); boolean equals2 = testTextFile3.equals(testTextFile); System.out.println("Test 5: does testTextFile3 equal testTextFile? " + equals2); }} //end of class TextFileTester - 37 -
  38. 38. TABLE OF RESULTS Now the test harness class will be run, and the results marked down in the table below. true false Test Number 1 2 3 4 5Expected Result 7179881TextAndData.txt the content of 7179881TextAndData.txt 7179881TextAndData.txt plus an empty line and (see appendix for file then the content (see contents) appendix for file contents) Actual Result 7179881TextAndData.txt the content of 7179881TextAndData.txt true false 7179881TextAndData.txt plus an empty line and (see appendix for file then the content (see contents) appendix for file contents) Pass / Fail Pass Pass Pass Pass Pass REFLECTION All tests passed, so the white-box testing test can be concluded for TextFile. - 38 -
  39. 39. 4. SECTION TWOAfter the first iteration of the system we can see that the system functions efficiently. It successfullycreates a new object from the TextFile class (the subclass), containing only the data that it needsfrom the File superclass. The TextFile class contains the name and content of the file that the userwants to display, and it only allows them to open .txt files.The next stage of the iteration is to allow the user to get a sequence of files. In this section we will usethe first iteration of the system but increase its functionality to include this requirement. Anappropriate graphical user interface will also be designed.This section will contain the following:- During this stage, UML diagrams will be used to determine the additional functionality that the 1. Requirements elicitation system must produce. A final list of requirements will be defined in order to test that the system has been designed and developed correctly. More UML diagrams will be designed at this stage to give a better understanding of how the 2. Design system will be built. Designs of the graphical interface will be in this section. The finished code listing will be in this section. 3. Implementation The code will be tested using component, system, and acceptance testing. If any errors are found 4. Testing they will be documented in this section. - 39 -
  40. 40. 4.1 FEATURES LISTINTRODUCTION TO FEATURES LISTSA features list is an abstract tool used to gather the most basic of requirements. Essentially it is “a list offeatures that the proposed system should possess” (Neville, Feature List, 2008).In the first section a feature list was made containing the basic functions. The requirements that featurein both lists are highlighted in bold.FEATURES LISTThe final program must:- 1. Enable the user to choose a file from a file browser 2. Check that the file is of the correct format (.txt) 4. Show a list of loaded files 3. Display the content of a file chosen by the user 5. Allow user to browse through loaded files 7. Display the number of the file (e.g. 1/3) from the list 6. Display the file name 8. Contain no errors 9. Enable user to remove files from the list 10. Allow user to close the program 11. Restrict the amount of files that the user can add to the listREFLECTIONThe features list has increased in size significantly in this second iteration of the program. The finalprogram must implement an appropriate user interface, so graphical components of Java need to beconsidered at this stage.For example, a file browser (see Figure 3) is implemented in Java using the JFileChooser class. TheJFileChooser class “displays a dialog that enables users to easily select files” (Deitel & Deitel, Java:How to Program, 2005). In the first iteration of the program, the pathname and name of the file that theuser wanted to display was directly written into the program by the user. This is susceptible to manyhuman errors. For example, they could spell the path name or file name incorrectly, they could forget toinclude the whole pathname or they could try and open a file that cannot be used in conjunction withthe FileReader/BufferedReader classes. Thus, using a JFileChooser class practicallyeliminates all human error.Requirement two implements another function of the JFileChooser class, specifically theaddChoosableFileFilter() method. The FileFilter class “can be set on a JFileChooser tokeep unwanted files from appearing in the directory listing” (Sun Microsystems, 2008). - 40 -
  41. 41. In this project a custom file filter will be created following an example found on a tutorial website(Demo Source and Support, 2008). This new FileFilter will just filter text (.txt) files from theJFileChooser.One of the main features in the next iteration of the system is its ability to load a sequence of files. Asequence implies that a collection must be used. The Java Collections Framework is “a group ofgeneric collections classes that grow as more elements are added to them”. This seems to be a morerobust method than using a simple array 12. This is because arrays are a fixed size and cannot bechanged when the program is run. In future iterations of the system it is likely that the user will want tobe able to change the maximum amount of objects (items) that can be stored.The Java Collections Framework provides three different collection interfaces; List, Set and Map. Setinterfaces contain no repetition of data and ordering is unimportant. Therefore, it is not suitable for usein this project, as ordering will be important. Map interfaces “process a collection consisting of pairs ofobjects” (Charatan & Kans, 2006), thus would be inefficient in this example as there is only the title ofthe file to store in the list. A List interface (specifically the ArrayList) will be used. It is designed for usewith an ordered list of objects. Ordering is important here as the number of the file will be shown(feature 7). FIGURE 312 Array: A container to store a collection of items of the same type (Charatan & Kans, 2006) - 41 -
  42. 42. 4.2 CONTEXT DIAGRAMINTRODUCTION TO CONTEXT DIAGRAMSContext diagrams show the environment that the system (artifact) will work in (Neville, ContextDiagrams, 2008)Key: An actor of the system A message that is passed Declares an interaction between system and actor Object / artifactCONTEXT DIAGRAM - 42 -
  43. 43. 4.3 USE CASE DIAGRAMINTRODUCTION TO USE CASE DIAGRAMSUse case diagrams “define the interaction between actors and the system”, and “encapsulate a set ofscenarios” 13 (Sommerville, 2007). They are a high level of abstraction and are used to determineinteractions primarily; therefore they are “not as effective for eliciting constraints and non-functionalrequirements” (Sommerville, 2007).Although there is no standard way to write a use case, a common style is to first choose the mainscenario and write a sequence of steps from the perspective of the user. The next stage is to defineother scenarios (extensions). From these scenarios, actors 14 and interactions can be established.The first use case diagram showed that the two actors were the user and the system.USE CASE TEXTGOAL : Display a fileMain success scenario: 1. User selects file to add to list 2. User selects file from list to display 3. User presses display file 4. System displays file content and nameExtensions: 1. List is full a. System displays message that list is full b. File is not added to list 1. User chooses a file that is already in the list a. System displays message that item is already in the list b. File is not added to list c. System prompts for another file13 Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004)14 Actor: The users of the system - 43 -
  44. 44. DIAGRAM:REFLECTION:More functionality has been added to the use case in order to achieve requirement 4 15. The diagramindicates that the list is the most important feature, and will need to be carefully planned. At this earlystage there is no concrete design plan, but it seems apparent that there will need to be at least twoclasses, one to contain the graphical user interface (GUI) and one to contain the ArrayList itself.Again this is the modularity 16 principle of software design. Error handling is much easier whenindividual components can be tested thoroughly. One suggestion for a design would be to have a‘FileHandler’ class which contains the list and all the functions needed to access and modify the list,and a graphical user interface class (‘FileHandlerInterface’) which contains a reference to theFileHandler class by creating an object of it. It will also contain the graphical functions, such as theJFileChooser and the text area to display the content of the file. A high quality GUI is needed toensure the efficiency of the system, and so rigorous testing will be undertaken.15 Requirement 4: Design an application that can read a sequence (set of files) and display them.16Modularity: Where large software systems are decomposed into smaller, more independent components. Seepage 13 - 44 -
  45. 45. 4.4 REQUIREMENTS SPECIFICATION DOCUMENTINTRODUCTIONThis document contains a formal list of specifications that must be adhered to, and will be used in theacceptance testing of the system. It is the “official statement of what the developers should implement”(Sommerville, 2007). Each specification will be given a number between 1 and 3 corresponding to itsimportance, i.e. level 1 requirements are essential and level 3 are optional.There are two main types of requirement; functional requirements and non-functional requirements.Functional requirements “are statements of services the system should provide”. Non-functionalrequirements are not “directly concerned with the specific functions”. Instead they may relate to thereliability, speed and appearance of the system.REQUIREMENTS SPECIFICATION The system must display the file name of the file in the display area FunctionalLevel Specification Type of requirement The system must display the file content of the file in the display area Functional1 The user must be given a choice of what file to load from a file Functional1 browser1 The system should provide error handling in case a file cannot be Non-functional loaded1 The user should be informed of any errors in the program Non-functional The system should respond quickly (within 1 second) to user Non-functional1 commands2 The user should be able to close the program Functional The user should be able to add a file to the list Functional1 The user should be able to remove a file from the list Functional1 The user should be able to clear the list Functional1 The user should be able to change the maximum size of the list Functional2 The system should ensure that the list size does not go below the Non-functional3 number of items currently in the list1 The system should ensure that the only files that can be loaded into Functional the program are text files1 The user should be able to open a file directly Functional The system should give the user help using tooltips Non-functional2 The system should contain an error log Non-functional32 - 45 -
  46. 46. 4.5 CLASS, RESPONSIBILITIES AND COLLABORATORSINTRODUCTIONCRC diagrams are used in the form of index cards, which are used as a “visual (textual) abstractionmethodology that follows a “divide and conquer” problem/solution methodology” (Neville, ClassResponsibilities and Collaborators, 2008). They aim to break down the problem into sub-problemswhich can be used to define the structure of the classes of the system. Responsibilities are the tasks that the class will undertake. Class Name Collaborators indicate which tasks are Responsibilities Collaborators undertaken by other classes.Two classes were identified in the first iteration of the program: The TextFile class and theTextFileProgram class. These classes will remain unchanged in this second iteration.DIAGRAMS TextFileRead a file line by line Responsibilities CollaboratorsCheck the file exists TextFileProgramSave the name of the file to a variableSave the content of the file to a variableHandle errors when file is read TextFileProgramDisplays the file name TextFile Responsibilities CollaboratorsDisplays the file content TextFileAsks the user to input a file path FileHandlerHold an ArrayList of TextFiles Responsibilities CollaboratorsChange the maximum size of the ArrayList FileHandlerInterfaceAllows access to specific TextFiles in the ArrayList when given anindex FileHandlerInterfaceAllows access to the entire ArrayList of filesAdds TextFiles to ArrayList FileHandlerInterfaceRemoves TextFiles from ArrayList FileHandlerInterfaceClears the ArrayList - 46 -
  47. 47. FileHandlerInterfaceHolds a FileHandler object (instance of class) FileHandler Responsibilities CollaboratorsShows a graphical user interface with add, remove and showbuttonsContains button to move to next and previous files in listAllows the user to close the programREFLECTIONThese CRC diagrams make it clear that the FileHandlerInterface class will be dependent on theFileHandler class. It will contain graphical features that will interface with the FileHandler class(i.e. calling methods of the FileHandler class when a button is pressed). - 47 -
  48. 48. 4.6 CLASS DIAGRAMSINTRODUCTIONClass diagrams are widely used in software development and “describes the types of objects in thesystem and the various kinds of static relationships that exist among them” (Fowler, 2004). Attributes Class Name MethodsAttributes are represented in the form of:Methods are represented in the form of: Visibility name : type multiplicity = default {property-string}The parameters in the parameter-list are represented as:Visibility name (parameter-list) : return-type {property-string}Arrows represent an association between classes, and the numbers on the arrow represents thedirection name : type = default valuemultiplicity17 * Student 1 Class 2.1 FigE.g. Fig 2.1 shows that a Class can have zero or more Students but a Student can only have one ClassThe classes that were found in the first iteration of the program have not changed and so will be re-usedin this iteration.17 Multiplicity: an indication of how many objects may fill the property (Fowler, 2004). - 48 -
  49. 49. DIAGRAM-name : StringTextFile-content : String TextFileProgram 1 1 -testTextFile : TextFile+TextFile(s:String) : null+getName() : String+getContent() : String *+readFile(f : File) : String * 1 FileHandler -arrayList : TextFile[] 1FileHandlerInterface -max : int-addButton : JButton-changeSize : JMenuItem +FileHandler() : null-clearButton : JButton 1 1-displayArea : JTextPane +getList() : ArrayList<TextFile>-displayButton : JButton +getTextFile(int) : TextFile-displayList : JList-filesLabel : JLabel +getMax() : int-menuAbout : JMenuItem +removeFromList(int) : boolean-menuBar : JMenuBar-menuClose : JMenuItem +addToList(File) : String-menuFile : JMenu-menuHelp : JMenu +clearList() : null-menuHelpTopics : JMenuItem +nextFile(int) : TextFile-menuOpen : JMenuItem-nextButton : JButton +prevFile(int) : TextFile-numLabel : JLabel +setMaxSize(int) : String-openButton : JButton-prevButton : JButton-remButton : JButton-remResult : JLabel-titleLabel : JLabel-mainPanel : JPanel-filehandler : FileHandler-listEntry : int = 0-model : DefaultListModel+FileHandlerInterface() : null+showList() : null+changeEnabled() : null+main(String) : null+showChangeDialog() : String+showMsg() : String - 49 -
  50. 50. REFLECTIONThe FileHandler class contains no graphical features and so will be able to be implemented andtested without the need of the FileHandlerInterface. This will make debugging easier.The TextFile class contains ‘arrayList’ and ‘max’ variables which are declared as private(represented by the – symbol). This means that they can only be accessed by the FileHandler class.The getList() and getMax() methods (commonly referred to as ‘getter’ methods) enable thevalues of those variables to be passed to the FileHandlerInterface class when needed, but notchanged directly. It also contains a getTextFile() method which returns a TextFile object in theArrayList. To summarise, the FileHandlerInterface class will only get a copy of the data, andnot the ‘real’ data.As previously mentioned, ArrayList’s are part of the Java Collections Framework. This provides aninterface class called an Iterator. Although this provides functions to move through the ArrayList(using the next() method), it will not be used in this system. This is because it is intended that theuser can choose any item in the ArrayList to display, and once it is displayed then they can movebetween files. Therefore an Iterator is not as useful as writing custom code to handle these events.Just as ‘getter’ methods are shown in this diagram, so are ‘setter’ methods, namely the setMaxSize()method. It is intended that the maximum size of the list is initially set to 3 (as that is the amount of filesthat will be entered into the program to test it), but can be altered as the user requires. It can be arguedthat the most effective way to do this is have an “edit size” in the menu bar of the program, whichdisplays a dialog box to the user prompting for a new maximum size.In addition to the methods in the FileHandlerInterface, there will be methods pertaining to theevent of most of the attributes, i.e. when the mouse is clicked on a button a method is called. - 50 -
  51. 51. 4.7 HIERARCHICAL TASK ANALYSISINTRODUCTIONHierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when theyare performed” (Stevens, 2008).The structure of a hierarchical task diagrams usually consists of “a goal at the top, followed by sub-goals, unit tasks and artifacts. Sub-goals may be further sub-divided as required” (ACM, 2005). Thesegoals are normally written from the perspective of the user.DIAGRAM - 51 -
  52. 52. 4.8 GRAPHICAL USER INTERFACE DESIGNSINTRODUCTIONThe requirements of the system have been gathered, and the discovery stage of the developmentprocess is now complete. The next stage of the process is the design stage. This usually begins with “aconceptual design of the system, which involves organising the information space of the proposeddesign” (Heim, 2008). Prototypes will be developed, which will then be analysed using a heuristicevaluation proposed by Nielson 18. These heuristics are: 1. Visibility of System Status 2. Match between System and the Real World 3. User Control and Freedom 4. Consistency and Standards 5. Error Prevention 6. Recognition Rather than Recall 7. Flexibility and Efficiency of Use 8. Aesthetic and Minimalist Design 9. Help Users to Recognise, Diagnose and Recover from Errors 10. Help and Documentation18 Nielson’s heuristics can be found at http://www.useit.com/papers/heuristic/heuristic_list.html - 52 -
  53. 53. DESIGN ONEEVALUATION OF DESIGN ONE Heuristic 1. This design does not give the user much feedback. After the user has chosen a file from the JFileChooser, it would be advisable to provide feedback to them. The most appropriate way is to change the mouse cursor from a pointer to an hourglass to indicate that the file is being loaded. Heuristic 2. The button design does not match the real world as much as it could. The ‘close’ button is ambiguous – does it close the program or close the file from being displayed? The ‘add file’ menu option could be interpreted as ‘add file to list’ or ‘add file to display’. More information should be provided. - 53 -
  54. 54. Heuristic 3. There is no ‘emergency exit’ in this design. In the next design it is important to prompt the user, “are you sure..” when they click on some buttons, e.g. ‘close’.Heuristic 4. The aforementioned ‘close’ button being ambiguous is an example of bad design practice. However, the menu items do follow platform conventions, e.g. the File menu being the leftmost menu item and the Help item being the rightmost.Heuristic 5. Errors can occur in the program when the list size is changed to a size that is smaller than the amount of files in the list. For example, if there are three items in the list and the user puts the size at two. Error handling will be dealt by a popup box telling the user that it is not allowed. This is standard practice and is considered a ‘good’ error message.Heuristic 6. The recognition rather than recall heuristic suggests that icons would be appropriate to use in the system. This makes it easier for the user to remember what they need to do to perform a certain task.Heuristic 7. This heuristic is not applicable in this system as the system is relatively simple to use and contains very little to remember.Heuristic 8. This design is very minimalist, although it may be better if it were more appealing.Heuristic 9. There are no error messages that are too confusing for the user in this design. All messages will be clear and precise so that the user knows exactly what to do if an error occurs.Heuristic 10. A help document should be provided for this system, if time allows. It will be found in the ‘help’ item in the menu list. - 54 -
  55. 55. DESIGN TWOWithout files:With files: - 55 -
  56. 56. EVALUATION OF DESIGN TWOHeuristic 1. This design changes the mouse cursor from a pointer to an hourglass to indicate that the file is being loaded.Heuristic 2. More information is provided in this design and the buttons are clearer, i.e. “Add file to list” is easier to understand. The layout suggests in what order buttons are designed to be pressed, i.e. the add file button is above the list which suggests that the user should put things in, and the remove button is below it, which suggests taking things out.Heuristic 3. When the user clicks on destructive buttons, such as close and delete, a message is prompted to the user to confirm that they want to perform the action.Heuristic 4. The menu items do follow platform conventions, e.g. the File menu being the leftmost menu item and the Help item being the rightmost.Heuristic 5. Errors can occur in the program when the list size is changed to a size that is smaller than the amount of files in the list. An example of this is if there are three items in the list and the user puts the size at two. Error handling will be dealt by a popup box telling the user that it is not allowed. This is standard practice and is considered a ‘good’ error message.Heuristic 6. The recognition rather than recall heuristic is adhered to in this design, as icons are used. This makes it easier for the user to remember what they need to do to perform a certain task.Heuristic 7. This heuristic is not applicable in this system as the system is relatively simple to use and contains very little to remember. - 56 -
  57. 57. Heuristic 8. This design is very minimalist, and is designed to be easy to use.Heuristic 9. There are no error messages that are too confusing for the user in this design. All messages will be clear and precise so that the user knows exactly what to do if an error occurs.Heuristic 10. A help document should be provided for this system, if time allows. It will be found in the ‘help’ item in the menu list. Tool tips will also be provided. - 57 -
  58. 58. 4.9 PSEUDOCODE – LEVEL ONEINTRODUCTIONPseudocode is used for describing algorithms. It “allows the designer to focus on the logic of thealgorithm without being distracted by details of language syntax” (Dalbey, 2003). The first level of thepseudocode is very basic as it is intended to give a better idea of program flow.PSEUDOCODE 1. Load GUI 2. Create new ArrayList to store the filesWHEN USER CLICKS ‘ADD FILE’ 1. Load file browser - USER CHOOSES TEXT FILE AND PRESSES OK 2. If ArrayList is full i. Display message that list is full 3. Else, if the file already exists in the ArrayList (check name to see if it matches existing file) i. Display message that it already exists ii. Jump back to start 4. If the file doesn’t exist in ArrayList and list is not full i. Create new TextFile object ii. Read character stream from file iii. Save stream to String variable iv. Save name to String variable v. Save TextFile object to ArrayList vi. Display ArrayListWHEN USER CLICKS ‘OPEN FILE’ 1. Load file browser - USER CHOOSES TEXT FILE AND PRESSES OK 2. If ArrayList is full - 58 -
  59. 59. i. Display message that list is full 3. Else, if the file already exists in the ArrayList (check name to see if it matches existing file) i. Display message that it already exists ii. Jump back to start 4. If the file doesn’t exist in ArrayList and list is not full i. Create new TextFile object ii. Read character stream from file iii. Save stream to String variable iv. Save name to String variable v. Save TextFile object to ArrayList vi. Display ArrayList vii. Get filename and print in on the screen viii. Get content and print on the screen ix. Get number of file in ArrayList and print it on the screenWHEN USER PRESSES ‘REMOVE FILE’ 1. Remove object from ArrayList 2. Display ArrayListWHEN USER PRESSES ‘CLEAR LIST’ 1. Remove all object from ArrayList 2. Display ArrayListWHEN USER PRESSES ‘DISPLAY FILE’ 1. Get the TextFile that user wants to display 2. Get filename and print in on the screen 3. Get content and print on the screen 4. Get number of file in ArrayList and print it on the screenWHEN USER PRESSES ‘NEXT FILE’ - 59 -
  60. 60. 3. Load next TextFile object in list 4. Get filename and print in GUI label 5. Get content and print in GUIWHEN USER PRESSES ‘PREVIOUS FILE’ 6. Load previous TextFile object in ArrayList 7. Get filename and print in GUI label 8. Get content and print in GUIWHEN USER PRESSES ‘EXIT’ OR ‘X’ ICON 9. Close applicationREFLECTIONThis pseudocode makes it easier to begin to think about the Java code for implementing this system. - 60 -
  61. 61. 4.10 PSEUDOCODE – LEVEL TWOINTRODUCTIONThe second level of the pseudocode aims to use the syntax of the Java language to describe systemprocesses and artefacts that are produced by the system.PSEUDOCODE 1. Load GUI 2. Create new FileHandler and instantiate ArrayList to hold TextFile objects 1. Load FileBrowser with TextFileFilter to only accept .txt files - USER CHOOSES FILE ANDWHEN USER CLICKS ‘ADD FILE’ PRESSES OK a. Error handling – IOException, FileNotFoundException b. Display message in GUI that error occurred c. Reload FileBrowser d. Else, if the file already exists in the ArrayList (use contains() method) i. Display message that it already exists ii. Jump back to start e. If the file doesn’t exist in ArrayList i. Create new TextFile object by sending in File object ii. Create FileReader object for that file and assign to variable iii. Create BufferedReader object for variable iv. Use readLine() method and save to a string v. Save string to content variable vi. Save name (getName() method) to String variable vii. Catch any errors and increment integer error variable viii. Save TextFile object to ArrayList ix. Display ArrayList in GUI x. Display the number of files in the list 1. Load FileBrowser with TextFileFilter to only accept .txt files - USER CHOOSES FILE ANDWHEN USER CLICKS ‘OPEN FILE’ PRESSES OK a. Error handling – IOException, FileNotFoundException b. Display message in GUI that error occurred - 61 -
  62. 62. c. Reload FileBrowser d. Else, if the file already exists in the ArrayList (use contains() method) i. Display message that it already exists ii. Jump back to start e. If the file doesn’t exist in ArrayList i. Create new TextFile object by sending in File object ii. Create FileReader object for that file and assign to variable iii. Create BufferedReader object for variable iv. Use readLine() method and save to a string v. Save string to content variable vi. Save name (getName() method) to String variable vii. Catch any errors and increment integer error variable viii. Save TextFile object to ArrayList ix. Display ArrayList in GUI x. Get filename (getName() method of TextFile) and print in on the screen xi. Get content (getContent() method of TextFile) and print on the screen xii. Get number of file in ArrayList and print it on the screen 1. Check the ArrayList contains() the TextFile that the user wants to removeWHEN USER PRESSES ‘REMOVE FILE’ 2. If found: a. Remove TextFile from ArrayList b. Display list 3. Get the TextFile that user wants to display using FileHandler getFile() methodWHEN USER PRESSES ‘DISPLAY FILE’ 4. Get filename (getName() method of TextFile) and print in on the screen 5. Get content (getContent() method of TextFile) and print on the screen 6. Load next TextFile object in list (using FileHandler getFile(current+1) method)WHEN USER PRESSES ‘NEXT FILE’ 7. Get filename (getName() method of TextFile) and print in on the screen 8. Get content (getContent() method of TextFile) and print on the screen 9. Load next TextFile object in list (using FileHandler getFile(current-1) method)WHEN USER PRESSES ‘PREVIOUS FILE’ 10. Get filename (getName() method of TextFile) and print in on the screen - 62 -
  63. 63. 11. Get content (getContent() method of TextFile) and print on the screen 12. Remove title from GUI labelWHEN USER PRESSES ‘CLOSE FILE’ 13. Remove content from GUI 14. Close applicationWHEN USER PRESSES ‘EXIT’ OR ‘X’ ICONREFLECTIONThis pseudocode provides a good foundation upon which entire lines of Java code can be written. - 63 -
  64. 64. 4.11 POSSIBLE PROBLEMS AND SOLUTIONSINTRODUCTIONIn this section possible problems will be declared. The solutions highlighted in bold will be thesolutions that will be implemented.PROBLEM LIST 1. The user may try to load files once they have reached the maximum size of the array, i.e. if array holds 3 file objects. a. Remove the button / menu item to ‘add a file’ once the limit has been reached. b. Disable the button / menu item to ‘add a file’ once the limit has been reached. c. Allow the user to change the amount of files that can be entered (but keep the d. Display a popup message on the screen to say that the limit has been reached. default as 3). 2. User may press a button to remove a file but the array list is empty. a. Do not show the button until a file has been loaded into the array list, e.g. “FileName1 X remove”. b. Display a message to the user saying that the action cannot be completed. c. Disable the button / menu item to ‘remove a file’ once the list is empty 3. The user tries to open a file other than a text file. File Browsers allow any type of file to be added, but it will be hard to display data by the readLine() method if the file was in different formats (i.e. image files). b. If user enters a non-text file, display message to the user (“Please re-select a file, .txt files a. Change file browser to only allow .txt files only”). Reload the file browser. - 64 -
  65. 65. 4.12 COMMENTED CODE LISTINGINTRODUCTIONThere will be three documents in this section. One document is the code for the FileHandler class,another is for the FileHandlerInterface class, and the final document is for theTextFileFilter. The code for the TextFile class has already been provided.CODE LISTING TEXTFILEFILTER CLASS//package declarationpackage filehandlerproject;//import statementsimport java.io.File;//main classpublic class TextFileFilter extends javax.swing.filechooser.FileFilter{ /*method returns true if the File is a directory or a text file this means that both will be shown*/ public boolean accept (File file) //returns true or false { if (file.isDirectory()) //shows directories { return true; } if (file.getName().toLowerCase().endsWith(".txt")) //shows .txt files { return true; } return false; } //gets the description to put in the JFileChooser box. public String getDescription() { return "Text File (*.txt)"; }} - 65 -

×