You are on page 1of 4

Chapter 14: Coupling and Cohesion

You would have heard or learnt a lot about coupling and cohesion when you learnt object oriented concepts or while learning other programming languages like c++. Let me tell you up front that, this chapter is going to be from the SCJP exam perspective and is going to cover concepts related to these two topics only from the exam point of you and not the overall dig deep into the topics. Frankly speaking, you’ll have very few questions about coupling and cohesion on the real exam. Lets get started. These two topics, coupling and cohesion, have to do with the quality of an OO design. In general, good OO design calls for loose coupling and shuns tight coupling, and good OO design calls for high cohesion, and shuns low cohesion. As with most OO design discussions, the goals for an application are • Ease of creation • Ease of maintenance • Ease of enhancement Coupling Coupling is the degree to which one class knows about another class. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. If, on the other hand, class A relies on parts of class B that are not part of class B’s interface, then the coupling between the classes is tighter. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled. Using this second scenario, imagine what happens when class B is enhanced. It’s quite possible that the developer enhancing class B has no knowledge of class A, (why would he/she?) Class B’s developer ought to feel that any enhancements that don’t break the class’s interface should be safe, so she might change some noninterface parts of the class, which then causes class A to break. At the far end of the coupling spectrum is the horrible situation in which class A knows non-API stuff about class B, and class B knows non-API stuff about class A. (This is REALLY BAD CODING). If either class is ever changed, there’s a chance that the other class will break. Let’s look at an obvious example of tight coupling, which has been enabled by poor encapsulation: class CalculateTaxes { float rate; float doIndia() { TaxRatesInIndia str = new TaxRatesInIndia(); rate = str.salesRate; // ouch // this should be a method call: // rate = str.getSalesTaxRates("CO"); // do stuff with rate } } class TaxRatesInIndia { public float salesRate; // should be private public float adjustedSalesRate; // should be private public float getSalesTaxRates(String region) { salesRate = new CalculateTaxes().doIndia(); // ouch again! // do country-based calculations return adjustedSalesRate; } }

1

choose a printer.. so make sure that all of these reports will let them choose a database. Let’s take a look at a pseudocode example: class SalesReport { void connectToDb(){ } void generateSalesReport() { } void saveAsFile() { } void print() { } } Now imagine your manager comes along and says. Keep in mind that cohesion too is a subjective concept. well-focused purpose. 2 . role.” Rather than putting all the printing code into one report class. The more focused a class is. the higher its cohesiveness. The term cohesion is used to indicate the degree to which a class has a single. you shouldn't be getting surprise errors in other classes. Cohesion While coupling has to do with how classes interact with each other. we probably would have been better off with the following design right from the start: class SalesReport { Options getReportingOptions() { } void generateSalesReport(Options o) { } } class ConnectToDb { DBconnection getDb() { } } class PrintStuff { PrintOptions getPrintOptions() { } } class FileSaver { SaveOptions getFileSaveOptions() { } } This design is much more cohesive. or cohesive. The key benefit of high cohesion is that such classes are typically much easier to maintain (and less frequently changed) than classes with low cohesion. Because of this. if all of the classes in an application have well-designed APIs. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes. Ideally. the SCJP exam will test you on really obvious examples of tight coupling only. all interactions between objects in an OO system should use the APIs.. we’ve broken the system into four main classes. the contracts. each with a very specific.All large OO applications are a mix of many classes and interfaces working together. oh and they want to do some inventory reporting also. If you make changes to the way one class behaves. Instead of one class that does everything. and save generated reports to data files. “Hey you know that accounting application we’re working on? The clients just decided that they’re also going to want to generate a revenue projection report. in a loosely coupled environment. then it should be possible for all interclass interactions to use those APIs exclusively. As we discussed earlier in this chapter. cohesion is all about how a single class is designed. They do like our reporting features however. Theoretically. an aspect of good class and API design is that classes should be well encapsulated. in other words. So don't worry much about having to make design decisions about code. The point here is that coupling is a somewhat subjective concept. of the objects’ respective classes.

and the file saver class. since we've already got the database connection class. it’ll be much easier to write a new report. A class should be responsible for itself. Let's take a look at a pseudo-code example: class BudgetReport { void connectToRDBMS(){ } void generateBudgetReport() { } void saveToFile() { } void print() { } } Now imagine your manager comes along and says. the printing class. role. since we’ve already got the database connection class. "Hey you know that accounting application we're working on? The clients just decided that they're also going to want to generate a revenue projection report. we probably would have been better off with the following design right from the start: class BudgetReport { Options getReportingOptions() { } void generateBudgetReport(Options o) { } } class ConnectToRDBMS { DBconnection getRDBMS() { } } class PrintStuff { PrintOptions getPrintOptions() { } } class FileSaver { SaveOptions getFileSaveOptions() { } } This design is much more cohesive. Hence its always better to program to interface.. A high cohesion and low coupling is always desired. each with a very specific. and the file saver class. reusable classes. Instead of one class that does everything. Cohesion means that the whole of a class sticks together (well. Cohesion is closely related the various functions of a class. and save generated reports to data files. or cohesive. and that means they can be reused by other classes that might want to print a report. For example: A Car class should remember its make.. Because we've built these specialized. well-focused purpose. speed. so make sure that all of these reports will let them choose a database. Cohesion is (to quote sellers and Yeatman) A Good Thing. and that means they can be reused by other classes that might want to print a report. that a change in any other class will result in change in this class. The more focused a class is. the higher its cohesiveness—a good thing. 3 . reusable classes. The term cohesion is used to indicate the degree to which a class has a single. The key benefit of high cohesion is that such classes are typically much easier to maintain (and less frequently changed) than classes with low cohesion. Coupling is how closely this class is integrated with implementations of other classes. colour. no other class should make your Car go faster or slower. you may not get too many questions about cohesion but if you are (un)lucky you may get one or two… Cohesion While coupling has to do with how classes interact with each other. the speedUp() and slowDown() methods should be in the Car class.Because we’ve built these specialized. choose a printer. Again. It is responsible for changing speed. Keep in mind that cohesion is a subjective concept. roughly). the printing class. They do like our reporting features however. should do one thing and as far as possible do everything for that one thing. as in Coupling. oh and they want to do some inventory reporting also. cohesion is all about how a single class is designed." Ouch! Rather than putting all the printing code into one report class. it'll be much easier to write a new report. we've broken the system into four main classes. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes.

This means other classes gain access to the implementation of the Car class. } . . To avoid tight coupling * All classes should have as small a public interface as possible..speed += speed.. 4 . * All non-constant fields should have private access.. For example: Driver campbell = new Driver(). This is "tight coupling" and tight coupling is A Bad Thing. public class Driver { Car myCar.. Car ford = new Car("Ford". * Any alterations to the values of fields should be via method calls.. public void goFaster(int speed) { myCar.. . because any changes to one class can mean that other classes would have to be altered too. } The Car class has allowed access to its speed field and the Driver class changes its value directly. any changes to that implementation will "break" the Driver class.Coupling means that one class gets at the implementation of another class. "red").