Sie sind auf Seite 1von 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, youll 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 Bs 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. Its quite possible that the developer enhancing class B has no knowledge of class A, (why would he/she?) Class Bs developer ought to feel that any enhancements that dont break the classs 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, theres a chance that the other class will break. Lets 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; } }

All large OO applications are a mix of many classes and interfaces working together. Ideally, all interactions between objects in an OO system should use the APIs, in other words, the contracts, of the objects respective classes. Theoretically, if all of the classes in an application have well-designed APIs, then it should be possible for all interclass interactions to use those APIs exclusively. If you make changes to the way one class behaves, in a loosely coupled environment, you shouldn't be getting surprise errors in other classes. As we discussed earlier in this chapter, an aspect of good class and API design is that classes should be well encapsulated. The point here is that coupling is a somewhat subjective concept. Because of this, the SCJP exam will test you on really obvious examples of tight coupling only. So don't worry much about having to make design decisions about code. Cohesion While coupling has to do with how classes interact with each other, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Keep in mind that cohesion too is a subjective concept. The more focused a class is, the higher its cohesiveness. 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. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes. Lets 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, Hey you know that accounting application were working on? The clients just decided that theyre also going to want to generate a revenue projection report, oh and they want to do some inventory reporting also. They do like our reporting features however, so make sure that all of these reports will let them choose a database, choose a printer, and save generated reports to data files... Rather than putting all the printing code into one report class, 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. Instead of one class that does everything, weve broken the system into four main classes, each with a very specific, or cohesive, role.

Because weve built these specialized, reusable classes, itll be much easier to write a new report, since weve already got the database connection class, the printing class, and the file saver class, and that means they can be reused by other classes that might want to print a report. Again, as in Coupling, 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, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Keep in mind that cohesion is a subjective concept. The more focused a class is, the higher its cohesivenessa good thing. 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. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes. 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, "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, oh and they want to do some inventory reporting also. They do like our reporting features however, so make sure that all of these reports will let them choose a database, choose a printer, and save generated reports to data files..." Ouch! Rather than putting all the printing code into one report class, 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. Instead of one class that does everything, we've broken the system into four main classes, each with a very specific, or cohesive, role. Because we've built these specialized, reusable classes, it'll be much easier to write a new report, since we've already got the database connection class, the printing class, and the file saver class, and that means they can be reused by other classes that might want to print a report.

A high cohesion and low coupling is always desired. Cohesion is closely related the various functions of a class. Coupling is how closely this class is integrated with implementations of other classes, that a change in any other class will result in change in this class. Hence its always better to program to interface. Cohesion means that the whole of a class sticks together (well, roughly). A class should be responsible for itself, should do one thing and as far as possible do everything for that one thing. For example: A Car class should remember its make, colour, speed. It is responsible for changing speed; the speedUp() and slowDown() methods should be in the Car class; no other class should make your Car go faster or slower. Cohesion is (to quote sellers and Yeatman) A Good Thing.

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

Das könnte Ihnen auch gefallen