CSCI 111 LAB 5
previously CSCI 15a

Lab Times: See course home page

TA: See course home page

Worth:20 points


*** Documentation and Style ***

All source code needs to be documented. As you probably have already seen it can be difficult to understand what is happening in a piece of code just by looking at it. Comments and good programming style can make it easier to understand the structure and purpose of the code we write. There are three parts to creating a readable and understandable design along with its associated code. The three parts are the object model, programming style and the comments, each contributes to creating a program that others can modify and use.


First is the object model which is done prior to concrete coding to manifest the design and get ideas down on paper. To make this model, program designers have agreed on a standard form of representation called the Unified Modeling Language (UML). The object model provides a visual reference to the relationships of the classes to each other and a shorthand view of the classes. During this design phase of building the object model, you should be playing with the ideas and relationships of the classes and not be set on the first design that pops into your head. A good design at the start, created by "playing with" the object model, will save coding time and reduce bugs. A good design also makes the overall program ideas and relationships more understandable by others. Often the initial object model is not adequate to fully solve the problem and is changed during the code writing phase of the project. This is part of the normal process of creating a program and as you make changes to the code being written, you should reflect those changes in the object model. There are four principle things that will appear in an object model, these are classes, inheritance relationships, associations and aggregations.


*** Classes ***

Classes are the main tool we use to organize the code and provide the structure to our programs. As such they form a principle and central role in object models and are represented by a square, that is divided into three parts. The first part is the name of the class, the second is the variables and the third is the methods of the class. In the process of design, you must make decisions as to what classes should be in your programs and hence in the object model. A simple way to think about this is to make big concepts or nouns into classes and smaller related things into variables of the related classes. Instance variables should represent some state of an object or its present situation. Methods are the verbs or actions that effect our classes ( nouns) and the instance variables of the associated class. Verbalize what something is and what actions are to be preformed on it and that should help in seeing what should be a class, an instance variable of a class and what actions or verbs will become methods of the class. There is no clear cut way to determine exactly what should be an instance variable and what should be a class, generally if it is a complex problem with lots of detail - the tendency will be to create classes to handle the details. For example, I could model the gas tank in a car class as simply a double and when the car is moved around the gas is subtracted from the tank. When the value of the gas tank equals zero I am out of gas. But take the situation in which I am modeling a rear-end crash of a car, suddenly the complexity level jumps and a separate car and a separate gas tank class may be required to correctly model the behavior of a crash.


public class A
{
	public int x;
	private double y;
	
	public void myMethod( int z )
	{
	}

	private int myOtherMethod( )
	{
		return 0;
	}
}


*** Inheritance ***

Inheritance is one of the techniques we use to allow us to reuse code others have written and/or modify something that is very close to fit what we need. This must be used with caution since inheritance should only be used to express an IS-A relationship, that an object is also something else. Generally this means moving from a general concept to one that is more specific to what is in our problem domain. Take for example the class motor vehicles (general concept) being extended to make a Mercedes ( a less general motor vehicle ) class. The Mercedes is still a motor vehicle, so by using inheritance we gain the general features of a motor vehicle and then modify only the parts that are specific to our motor vehicle. We have already been doing this in our programs by inheriting Applet into our programs, which we then make a specific kind of Applet that is our program. Generally you will not have a lot of inheritance in the programs we write in this course.

 

public class A
{
	public int x,y;
	private double z;

	public void display( )
	{
	}
	
	private double add(int a1, int a2 )
	{
		return 0;
	}
}

public class B extends A
{
	public int x1;	
	private double z1;

	public void display( )
	{
	}
}


If you did not write the class that your class is inheriting from, you do not need to show the variables and methods that you did not write. For example, with
Applet. You do need to always show the variables and methods of your own code though. Note that showing the inherited class also shows the user what was necessary to import.

*** Association ***

Associations are the most common connections generally in our object models. An association is A-USE relationship between two or more classes. In some way two classes are related to each other within our program, normally an association is labeled with a short meaningful description ( 1 or 2 words ) of what the relationship is. Often this label will be something like "model/view" , "prints", "mouse controller". Frequently the best way to figure out what labels should be on the association is to look at the verbs, actions or methods that interact between the two classes. Associations are thought of as being fairly loose connections between classes. Because of this they are frequently changed during the code development phase of projects and are the most updated part of most object diagrams.


public class A
{
	public B myb;
	
	public void paint( )
	{
		myb =new B( );
		myb.display( );
	}
}

public class B
{
	public int x, y;
	public void display( )
	{
	}

}


*** Interfaces ***

Whether a class uses an explicit instantiation of a Listener or if it implements it internally, the reader should be clear that an Interface/Listener has been implemented. Since class A says that it implements the Interface ActionListener, and the Interface specifies the method of actionPerformed(ActionEvent e), then this method must be implemented in the class. Note however, that even though the code is inside of class A, for the Object Model diagram the method is specified in the Interface box since that is where it is specified in the API.
Notice also that Class A has a Button as an instance variable. Since this user did not write the code for the Button, but rather it was available from the Java API, the class only shows its name but not its variables or methods.


public class A implements ActionListener
{
	public Button myButton;

	public void paint()
	{ 
		g.drawString("Hello", 50, 50);
	}

	public void actionPerformed(ActionEvent e)
	{
		System.out.println("Button was pushed");
	}
}

*** Aggregation ***

Aggregation is a special kind of association. Aggregation is the composition of a class from other classes and is a PART-OF relationship between classes. Meaning that one class contains another as part of its definition, the aggregate classes are part of a bigger item but is not the item itself or the same kind of item. An example of this is a car which is made up of a number of items grouped together like the engine, tires, seats, but each of those items alone is not the car but when put together as a group make up a car. This is a much stronger relationship than that of an association because the use of the classes is in relation to its containment within another class. If you are unsure about whether something is an aggregate or just an association, make it an association. The code between an association and an aggregation may look very similar, this has more to do conceptually with the way we think about how the classes are used. For more, see this page


public class A
{	
	public int x,y;
	private double z;
	private C myClass;
	
	public void display( )
	{
	}
	private double add(int a1, int a2 )
	{
		myClass=new C();
		myClass.x1=a1+a2;
		return 0;
	}
}

public class C
{
	public int x1;
	private double z1;
	
	public void display( )
	{
	}
}

*** Programming Style ***

Programming style is about putting your code in a format that is readable as well as applying conventions on how certain features of the language are used. Often it is possible to get a program to compile and run but that does not mean all is "done". Most programs must also be modified at some point. This is called maintenance. Maintenance is a major issue since most programs must be changed to meet the evolving needs of the users or the systems that they use. Languages often give us programmers many different ways to achieve the same task and programming styles provide a way to simplify the ways in which things are done. Companies working on large products will often have a documented style that all programmers working on a project will adhere too, this keeps the code in a uniform manner and makes it easier for a new programmer to examine the work of previous programmers. Ideally the code from two different programmers following the same coding style and guidelines should look extremely similar.

The Free Software Foundation ( GNU ) has one of the best programming style guides and you should take some time and review these guidelines. The guidelines they provide are for C programs but much of what they say is also useful when developing in other languages like java.

http://www.fsf.org/prep/standards_toc.html

Some simple programming style guidelines for this course...

  1. Comment, Comment, Comment

  2. Indent one tab space every time there is a meaningful block change in the code. Generally this means every time there is an open curly bracket, all code until the close curly bracket will be indented. Choose a curly bracket style and stick to it throughout your code.
    style 1 "Classic C style "
    
    public class A {
    
    	int x;
    
    }
    
    style 2 "Pascal style"
    
    public class A
    
    {
    
    	int x;
    
    }
    
    

  3. Use meaningful variable names for the problem being solved, avoid using single character variable. For instance in problem 3 we had area and perimeter as things in our problem space and hence it would make sense to use those names as variables in our program.

  4. Always state the member visibility of all variables and methods. State whether the variable or method is public, private or protected. (If the code has nothing stated, it is the default or "package" access - these are visible by other classes in the same package (or directory).)
    Also state whether they are instance or class variables/methods. This is done with the word static to designate a class variable/method.

  5. Any block of code that is longer than 1 printed page should be broken down into separate methods.

  6. Any process or code that is used repeatedly in more than one place should be a method.

  7. Avoid using ++ and -- except on a line by themselves. Same applies to += , -= , /= and *= .

    Examples..

    Don't do something like this.

    x++ = y + x++ + 4 - y-- ;

    Use it pretty much only like this.

    x++;

    y--;

  8. Never ever make an assignment inside of or as part of a boolean expression.

  9. Use the simplest possible solution. Follow the KISS principle of "Keep it simple, stupid", complicated solutions are rarely worth the effort and frequently are hard to maintain and modify . Keep in mind that you and other programmers must be able to understand the design and inner workings of what you write.

*** Comments ***

Comments provide a way to communicate directly though the source code what your intentions, feelings and reasoning are for a certain solution. At a later date and time you, or another programmer, may need to return to the program you wrote. Most likely you won't remember these details at a later date and/or a new programmer will have no reference to what the code does. Well-written comments will clarify and enlighten the source code and no comments are way better than ones that are wrong or misleading. Good comments are a kindness that other programmers will greatly appreciate when they encounter your code. Poor or misleading comments will earn the hate and scorn of your fellow programmers.

  1. EVERY FILE must have a group of comments at the beginning of the file that has your name, the program and its purpose, the classes used in the file, the date it was created and the date it was last modified. You should include a copyright notice there as well to protect your intellectual property.

  2. EVERY CLASS must be commented at the beginning with its purpose and intended use. If the class was written by someone other than the person at the top of the file their name should be here as well. If the class inherits from another class, the purpose of the inheritance should be stated along with the package name of the inherited class. Any restrictions on the use of the class and any pre or post conditions on its use must also be listed.

  3. EVERY METHOD must be commented at the beginning with its purpose and intended use. Any restrictions on how the method can be used and all pre-conditions that must be met prior to its use. All post-conditions of the method must be stated along with possible side effects from its use.

  4. EVERY VARIABLE should be commented if the name of the variable and its use are not clearly apparent. It is best to use variable names that enhance the program and are meaningful with-in the problem space being addressed by the program.

  5. DO COMMENT every section of code that is doing a specific task. Any part of the code that is strange or difficult to understand should be commented. A good rule of thumb is that every 10 to 20 lines of code should have a comment and some even say that every 5 lines should be commented. The more complicated a section of code is or its obscure nature the more comments.

  6. DO NOT comment every line of code. Too many comments can make a program difficult to read and obscure the code. Only in rare cases where the code is very strange or complicated should you ever need to comment every line and instead you should try to group comments together whenever possible. A good short comment is better than a long one that doesn't get to the point of the problem.

  7. DO INCLUDE comments on the references to where information can be found on how you solved a problem. Make references to the sources that gave you the ideas for solving the problem like for instance other programs, books, web sites or even people that helped.

  8. DO INCLUDE comments that break the file up into separate parts....like for instance using two lines of stars to separate classes from each other.

  9. LEARN TO USE JAVADOC. The javadoc utility can help produce an API for your application which can be useful for others to read and use in understanding your program and its classes and methods. Plus it produces really professional looking output and puts it into a format just like what SUN did with the API.

  10. REMEMBER SOMEONE BESIDES YOURSELF WILL USE YOUR CODE......and someday you will have to use somebody else's code.....be kind and comment.. it will either haunt you like 3 day old B.O. or make your life smell like roses.

*** Assignment ***

  1. Create an object model of the following code samples from the Sun JDK. You should post the models you create on your web page as JPG, GIF or PNG files. (These can be built with Word, Paint or your favorite drawing tool or gliffy.com (you are doing UML - Unified Modeling Language) or dia ( Screenshots) or other IDE's to make these in electronic form.) Provide a short description ( 1 or 2 sentences ) of the purpose and use of each class and interface used in the example programs.

    program 1 to model

    program 2 to model

    The html for adding the actual image to a web page looks like so,

    <img src="filename"><br>

    or you can put a link to each of your lab's images
    <a href="filename.gif"> OM.gif </a >
    to the .gif file (in the same directory)

  2. Write an applet that draws a four by four grid on the applet. Your applet should define at least three methods and 2 instance variables. Each square must be filled with one of the 13 standard colors, you must use all the standard colors from the Color class. Each square should be at least 25 pixels. Example (Hint: The methods init() and paint(Graphics g) are called by the Applet class when it is instantiated by the browser. Other methods in the Applet are not automatically called. Make sure to remember to invoke the methods that you write (other than init() and paint(Graphics g)). See methods notes for a reminder on using and invoking multiple methods...(and a very similar class on using and instance variable. )

    Create an object model of the applet and post it with the documented and commented source code. Everything should be in a directory called lab5 under your csci directory (in the public_html directory).

    You must create the applet, a web page to display applet, a link to the source code, the javadoc and an object model to get full credit.
    Submission:

    Web Page Submission Required Contents:
    In the URL you submit, you should have a web page with

    1. links to the three (3) Object Models of number 1 and 2,
    2. the applet of number 2
    3. provide link to source code (with class defined as specified - at least three methods and 2 instance variables),
    4. a link to the javadoc created page
    Poorly documented source code will also lose points.

  3. We will be modifying this applet in assignment 7 to create a guessing game. You will need to understand mouse event handling and if statements to complete lab 7. Make sure you read the book and lecture notes on these topics.