New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Chapter 6

by: AnnMarie

Chapter 6 CSC 120


GPA 3.028

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

I have created this set of notes to cover the reading material assigned. These notes cover the important sections of the material which are in the learning objectives.
Debra Blackman
Class Notes
25 ?





Popular in ComputerScienence

This 9 page Class Notes was uploaded by AnnMarie on Thursday February 25, 2016. The Class Notes belongs to CSC 120 at Louisiana Tech University taught by Debra Blackman in Winter 2015. Since its upload, it has received 24 views. For similar materials see INTRODUCTION TO COMPUTER PROGRAM in ComputerScienence at Louisiana Tech University.


Reviews for Chapter 6


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 02/25/16
Chapter 6: Designing Classes 6.3 Introduction to coupling and cohesion The term coupling refers to the interconnectedness of classes. Our aim is to design our applications as a set of cooperating classes that communicate via well-defined interfaces. The degree of coupling indicates how tightly these classes are connected. We strive for a low degree of coupling, or loose coupling. The degree of coupling determines how hard it is to make changes in an application. In a tightly coupled system, a change to one class may require additional changes to other classes else the application may not work as designed or not at all. In a loosely coupled system, a change to one class does not require any changes to the other classes, and the application will still work. The term cohesion relates to the number and diversity of tasks for which a single unit of an application is responsible. Cohesion is relevant for units of a single class and an individual method. Ideally, one unit of code should be responsible for one cohesive task (that is, one task that can be seen as a logical unit). Amethod should implement one logical operation, and a class should represent one type of entity. The main reason behind the principle of cohesion is reuse: if a method or a class is responsible for only one well-defined thing, then it more likely to be used again for a different context.An complementary advantage of following this principle is that, when change is required to some aspect of an application, we are likely to find all relevant pieces located in the same unit. 6.4 Code Duplication The problem with code duplication is that any change to one version must also be made to another if we are to avoid inconsistency. This increases the amount of work a maintenance programmer has to do, and it introduced the danger of bugs. It is also usually a symptom of bad cohesion. If you look at the printWelcome and goRoom methods you will notice that they both contain the following lines of code: System.out.println(“You are “ + currentRoom.getDescription()); System.out.print(“Exits: “); if(currentRoom.northExit != null){ System.out.print(“north “); } if(currentRoom.eastExit != null){ System.out.print(“east “); } if(currentRoom.southExit != null){ System.out.print(“south “); } if(currentRoom.westExit != null){ System.out.print(“west “); } System.out.println(); If we were to create a method that contained the block of code above and then changed both the printWelcome and goRoom methods to make calls on the new method, we would be able to improve the design of the class. 6.6 Coupling Zuul-bad is a tight coupled application (system) that making improvements to the design due to its poor design we have to decouple the classes before we can introduce any changes like the HashMap that would cleanup the multiple places where all the exits are enumerated. 6.6.1 Using encapsulation to reduce coupling The encapsulation guideline (hiding implementation information from view) suggests that only information about what a class can do should be visible to the outside, not about how it does it. This has a great advantage: if no other class knows how our information is stored, then we can easily change how it is stored without breaking other classes. We can enforce this separation of what and how by making the fields private and using an accessor method to access them. 6.7 Responsibility-driven Design Responsibility-driven design expresses the idea that each class should be responsible for handling its own data. How well responsibility-driven designed is used influences the degree of coupling and, therefore, again, the ease with which an application can be modified or extended. 6.8 Localizing Change Another aspect of the decoupling and responsibility principles is that of localizing change. Localizing change is the concept of that when making changes to one class it should have minimal effects on other classes. Ideally, only a single class needs to be changed to make a modification. Sometimes several classes need change, but we then aim at this being as few classes as possible. In addition, the changes needed in other classes should be obvious, easy to detect, and easy to carry out. To a large extent, we can achieve this by following good design rules such as using responsibility- driven design and aiming for loose coupling and high cohesion. We should have modification and extension in mind when we create our application. It is important to anticipate that an aspect of our program might change, in order to make this change easy. 6.9 Implicit Coupling Implicit coupling is a situation where one class depends on the internal information of another, but this dependence is not immediately obvious. The tight coupling in the case of the public fields was not good, but at least it was obvious. If we change the public fields in one class and forget the other, the application will not compile anymore and the compiler will point our the problem. In cases of implicit coupling, omitting a necessary change can go undetected. An example of implicit coupling is when you made a change to the Zuul-bad application to include the look command. We were able to add it to the array of known words in the validCommands array , create a method for the look command, and then added the look command to the processCommand. But when the help command is called the option for look was not listed. If you look at the class diagram you will notice arrows point at other classes. The arrows in the diagram are a good first indication of how tightly coupled a program is – the more arrows, the more coupling. As an approximation of good class design, we can aim at creating diagrams with few arrows. 6.11 Cohesion 6.11.1 Cohesion of Methods Method cohesion expresses the ideal that any one method should be responsible for one, and only one, well defined task. We can see an example of a cohesive method in the Game class. This class has a private method named printWelcome to show the opening text, and this method is called when the games starts in the play method. 6.11.3 Cohesion for readability There are several ways in which high cohesion benefits a design. The two most important ones are readability and reuse. The example discussed in Section 6.11.1, cohesion of the printWelcome methods, is clearly an example in which increasing cohesion makes a class more readable and thus easier to understand and maintain. The class-cohesion example in Section 6.11.2 also has an element of readability. If a separate Item class exists, a maintenance programmer will easily recognize where to start reading code if a change to the characteristics of an item is needed. Cohesion of classes also increases readability of a program. 6.11.4 Cohesion for reuse The second greater advantage of cohesion is a higher potential for reuse. Consider a method in the Room class with the following signature: public Room leaveRoom(String direction) This method could return the room in the given direction and also print out the description of the new room we just entered. However, we can separate this task into two methods. One for returning the next room and another to produce the room's description. public Room getExit(String direction) public String getLongDescription() The advantage to this design is that the separate tasks can be reused more easily. 6.12 Refactoring Refactoring is the activity of restructuring existing classes and methods to adapt them to change functionality and requirements. Often in the lifetime of an application, functionality is gradually added. Once common effect is that, as a side-effect of this, methods and classes slowly grow in length. 6.12.1 Refactoring and testing When something is changes, there is a likelihood that errors will be introduced. Therefore, it is important to proceed cautiously; and, prior to refactoring, we should establish a set of tests exists for the current version of the program. If tests do not exist, then we should first decide how we can reasonably test the functionality of the program and record those tests (for instance, by writing them down) so we can repeat the same tests later. Once a set of tests have been established, the refactoring can start. Ideally, the refactoring should then follow in two steps:  The first step is to refactor in order to improve internal structure of code, but without making any changes to the functionality of the application. Once completed, the previously established tests should be repeated to ensure that we have not introduced unintended errors.  The second step is taken only once we have reestablished the baseline functionality in the refactored version. Then we are in a safe position to enhance the program. Once that has been done, testing will need to be conducted on the new version. Making several changes at the same time (refactoring and adding new features) makes it harder to locate the source of problems when they occur. So, it is suggested to make one change at a time. 6.12.2 Example of refactoring Doing good refactoring is as much about thinking in a certain mindset as it is about technical skills. While we make changes and extensions to applications, we should regularly question whether an original class design still represents the best solution.As the functionality changes, arguments for or against certain design changes. What was a good design for a simple application might not be good any more when some extensions are added. Recognizing these changes and actually making the refactoring modifications to the source code usually saves a lot of time and effort in the end. The earlier we clean up our design, the more work we usually save. 6.13 Refactoring for language independence An enumerated type definition consists of an outer wrapper that uses the word enum rather than class and a body that is simply a list of variable names denoting the set of values that belong to this type. By convention, these variable names are fully capitalized. We never create objects of an enumerated type. The following block of code is an example of how to implement the enumerated type: public enum CommandWord { GO, QUIT, HELP, UNKNOWN; } We would refer to these instances as CommandWord.GO, CommandWord.QUIT, etc. The switch statement takes the variable in the parentheses following the switch keyword and compares it to each of the values listed after the case key words. When a case matches, the code following it is executed. The break statement causes the switch statement to abort at that point, and execution continues after the switch statement. The following code segment shows how to implement a switch statement: switch(commandWord){ case UNKNOWN: System.out.println(“I do not know what you mean...”); break; case HELP: printHelp(); break; case GO: goRoom(command); break; case QUIT: wantToQuit = quit(command); break; } 6.14 Design Guidelines “Don't put too much into a single method.” Amethod is too long is it does more than one logical task. “Don't put everything in one class.” Aclass is too complex if it represents more than one logical entry. These guidelines are not cast-in-stone but keeping these in mind will significantly improve your class design and enable you to master more complex problems and write better and more interesting programs. 6.15 Executing without BlueJ 6.15.1 Class methods What distinguishes class methods from instance methods is that class methods can be invoked without an instance – having the class is enough. Aclass method is defined by adding the keyword static in front of the type name in the method's signature: public static int getNumberOfDays() { ... } Such a method can be called by specifying the name of the class in which it is defined, before the dot in the usual dot notation. If, for instance, the above method is defined in a class called Calendar, the following call invokes it: int days = Calendar.getNumberOfDays(); Note that the name of the class is used before the dot – no object has been created. 6.15.2 The main method If we want to start a Java application without BlueJ, we need to use a class method. Classes are the only things we have initially, so the first method that can be invoked must be a class method. Java definition for starting applications is quite simple: the user specifies the class that should be started, and the Java system will then invoke a method called main in that class. This method must a specific signature. Public static void main(String[] args) If such a method does not exist in that class, an error is reported.Appendix E describes the details of this method and the commands needed to start the Java system without BlueJ. You can also see the additional attachment called “How to Execute a Java Class From the Command Line”. 6.15.3 Limitations of class methods Because class methods are associated with a class rather an instance, they have two important limitations. The first is that a class method may not access any instance fields defined in the class. The second is that a class method may not call an instance method from the class. 6.16 Summary Good class design can make a huge difference when an application needs to be corrected, modified, or extended. It also allows us to reuse parts of the application in other contexts and thus creates benefits later. There are two key concepts under which class design can be evaluated: coupling and cohesion. Coupling refers to the interconnectedness of classes, cohesion to modularization into appropriate units. Good design exhibits loose coupling and high cohesion. One way to achieve a good structure is to follow a process of responsibility-driven design. Whenever we add a function to the application, we try to identify which class should be responsible for which part of the task. When extending a program, we use regular refactoring to adapt the design to changing requirements and to ensure that classes and methods remain cohesive and loosely coupled. Keywords Coupling describes the interconnectedness of classes. Cohesion describes how well a unit of code maps to a logical task or entity. Responsibility-driven design is the process of designing classes by assigning well-defined responsibilities to each class. Refactoring is the activity of restructuring an existing design to maintain a good class design when the application is modified or extended. Encapsulation is the process of hiding implementation information from view. Change localizing is ensuring that changes to one class should have minimal effects on other classes. Implicit coupling is the situation where one class depends on the internal information of another, but this dependence is not immediately obvious. Explicit coupling is the situation where one class is independent and communicates with other classes via a small, well-defined interface. Method cohesion is the concept that a method is responsible for one, and only one, well-defined task. Modularity, in Java, refers to a multi-class unit. Class cohesion is the concept that a class is responsible for one well-defined entity. In Java, class level methods, are methods that are called on a class rather than an instance. How to create and compile Java Programs with Text Editor and Command Line Prompt. 1. Open Command Line Prompt or Terminal 2. Use dr or ls to list files and folders 3. Use cd folderName to access another folder or location 4. Use mkdir folderName to create a new folder 5. Access the folderName you just created 6. Open the Text Editor or Note Pad 7. The first line of text should be public class ClassName{} 8. The second line of text should be public static void main(String[] args){} 9. Between the {} you will type your program. In our example we typed System.out.println(“Hello World”); 10. Choose File > Save as > and select the folder that you created earlier to save the file in and name the file the same name as the folder with .java at the end. 11. Go back to the Terminal or Command Prompt and type javac fileName 12. It should give you the command prompt if compiled correctly. 13. You then need to invoke the Java machine with java fileName and then it should give you a response. In our example it gives Hello World. 14. If you make any changes to the code you will have to recompile with javac before you can run the application again else it will run the previous version.


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.