6.005 8. Decoupling and interfaces
MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Decoupling and Interfaces Rob Miller Fall 2008 © Robert Miller 2008 Quote Generation Problem problem ¾obtain stock quotes for some ticker symbols ¾produce both RTF and HTML output ¾put the ask price in bold if the change since open is ≥ ± 1% Today’s Topics principles and concepts of system design ¾modularity ¾decoupling¾information hidinginformation hidinga new notation ¾module dependency diagram case study: designing a stock quoter ¾using interfaces to decouple modules © Robert Miller 2007 Design Tasks tasks, for each ticker symbol: ¾download quote information from web site¾parse to extract stock quotes¾write to file in RTF or HTML formatwrite formatparsing ¾minimize parsing by choosing a site with a simple format ¾Yahoo offers stock quotes in comma-separated-values (CSV) format example ¾http://quote.yahoo.com/d/quotes.csv?s=aapl&f=noa¾rreturns the string “APPLE INC”,130.75,125.20eturns INC” 130 75 125 20 © Robert Miller 2007 © Robert Miller 2007 1 Downloading & Parsing public class Quoter {private URL url;private String open, ask;private int change;why are the fields of Quoter private? publiic Quoter (Striing symbol) throws MalformedURLExceptiion {url = new URL("http://quote.yahoo.com/d/quotes.csv?s=“+symbol+"&f=noa");}public String getOpen () {return open;}public String getAsk () {return ask;}public int getChange () {return change;}public void obtainQuote () throws IOException {BufferedReader in = new BufferedReader(new BufferedReader is also a state machine. Draw it. What design pattern does it use? InputStreamReader(url.open..)); Sti i dLi () Quoter is a state machine. Draw it. What design pattern does it use? String csv = in.readLine(); in.close();String[] fields = csv.split(“,”);open = fields[1];ask = fields[2];change = (int)(100 *(Float.valueOf(ask)-Float.valueOf(open))/Float.valueOf(open));} © Robert Miller 2007}Design Option #1 just build two formatters that use Quoter public class HTMLFormatter {private final Set symbols = new HashSet ();...public voidvoid generateOutput uthrows IOException IOExceptin { generateOtput () throws oPrintStream out = new PrintStream(new FileOutputStream (...)); out.println(""); for (String symbol: symbols) { Quoter q = new Quoter (symbol);q.obtainQuote();out.println(symbol + ": "+ "opened at " + q.getOpen () + " and is currently trading at "); boolean bigChange = Math abs q >= 1;Math.(q.getChange()) > if (bigChange) out.println("");out.println(q.getAsk ());if (bigChange) out.println("");out.println("
");}out.close();}} © Robert Miller 2007How would the RTF version differ? What’s undesirable about this choice? Modularity and Decoupling modularity is essential for managing complexity ¾system is divided into parts (modules) that can be handled separately and recombined in other combinations coupling ¾degree of dependence between parts of the system¾an important measurement of modularitydecoupling achieved so far ¾the website (Yahoo) and its format (CSV) have been decoupled from the rest of the system next step ¾design the part of the system that generates the report¾report can be either HTML or RTF© Robert Miller 2007 Design Option #2 build one formatter that takes a flag (RTF or HTML) ¾tests flag to determine flow of control p ublic class Formatter { public enum Format { HTML, RTF }; private final Format format; .. public void generateOutput () throws IOException { PrintStream out = new PrintStream(new FileOutputStream (...)); out.println(format == HTML ? "“ : "{\\rtf1\\mac“); for (String symbol: symbols) { ... boolean bigChange = Math.abs (q.getChange()) >= 1; Is this a wise way to test the format flag? g g q g g ()) ; if (bigChange) out.println(format == HTML ? "“ : "\\f\\b“); out.println(q.getAsk ()); if (bigChange) out.println(format == HTML ? "“ : "\\f\\b0“); out.println("
"); } ... } } © Robert Miller 2007 What’s undesirable about this choice? 2 why are the fields of Quoterprivate? BufferedReaderis also a state machine. Draw it. What design pattern does it use? How would the RTF version differ? What’s undesirable about this choice? What’s undesirable about this choice?A Better Solution A Principle factor out responsibilities for report generation localize each design decision in exactly one place ¾generator: knows how to put in bold, italics, etc. ¾more crudely:“don’t repeat yourself” ¾formatter: knows what to put in bold, italics, etc. designing the generator why? ¾ready for change: if decision needs to change, there’s only one place ¾make it a state machine! ¾two versions, one RTF and one HTML ¾but same interface ¾ease of understanding: don’t have to think about the details of that decision when working on the rest of the system ¾safety from bugs: fewer places to change means less chance of omission variations on the same ideavariations idea ¾Information hiding: localizing design decision and protecting the rest of the system from it ¾Encapsulation: wrapping code up into a module that hides information © Robert Miller 2007 ¾Separation of concerns: responsibility for a feature is given to one module, not spread across system © Robert Miller 2007 A Generator public class RTFGenerator implements Generator {private boolean italic;private boolean bold;private final String filename;private PrintStream stream; public RTFGenerator (String filename) { this.filename = filename; } public void open() throws FileNotFoundException { FileOutputStream fos = new FileOutputStream (filename); stream = new PrintStream(fos); stream.println ("{\\rtf1\\mac"); } public void close() { stream.println ("}"); stream.close(); }public void newLine () { stream.println ("\\"); }public void toggleBold() { stream.println (bold ? "\\f\\b0" : "\\f\\b");bold = !bold; }...© Robert Miller 2007 } 3 Generator Machinekey design ideadevelop generic interface for text formattingOPENBOLDITALICPLAINROMANCLOSEDtoggleBoldtoggleBoldtoggleItalictoggleItalicwrite,newlineclose© Robert Miller 2007BOLDITALICCLOSEDThe Big Question how to make formatter independent of generator? ¾we want them decoupled¾so we can plug in different generators¾formatter’s code without changing the formatter s solution ¾formatter doesn’t refer to a particular generator class¾it refers to an interface instead© Robert Miller 2007 Interfaces, in Pictures what we want ¾two ways to configure formatter how does formatter refer to generators? ¾with an interface © Robert Miller 2007 Generator Interface /** * Interface for generator with basic text formatting.* Typically a stream is passed to the constructor.*/public interface Generator { public void open () throws Exception;public void close ();public void newLine ();public void toggleBold ();public void toggleItalic ();public void write (String s);} public class RTFGenerator implements Generator { public void open() throws FileNotFoundException { ... } ...} public class HTMLGenerator implements Generator {public void open() throws FileNotFoundException { ... } ...} © Robert Miller 2007 Using the Generator Interface public class QuoteFormatter {private final Set symbols = new HashSet ();private final Generator generator;public QuoteFormatter(Generator generator) { thiis.generator = generator ;}public void addSymbol (String symbol) {symbols.add (symbol);}public void generateOutput () throws Exception {generator.open (); for (String symbol: symbols) {Quoter q = new Quoter (symbol);q.obtainQuote();generator.write (symbol + ": ");generator.toggleItalic ();generator.write ("opened at ");generator.toggleItalic ();...generator.close();}© Robert Miller 2007 } 4 an object implementing Generator is plugged into p gg the formatter no mention of HTMLGenerator or RTFGeneratoranywhere!erator Putting Everything Together public class QuoteApp { public static void main(String[] args) throws Exception {Generator rtfg = new RTFGenerator ("myQuotes.rtf");QuoteFormatter formatter = new QuoteFormatter(rtfg);formatter.addSymbol ("AAPL");formatter.addSymbol ("INTC");formatter.addSymbol ("JAVA");formatter.addSymbol ("MSFT");formatter.generateOutput ();plugin is selected here Generator htmlg = new HTMLGenerator ("myQuotes.html");formatter = new QuoteFormatter(htmlg);formatter.addSymbol ("AAPL");formatter.addSymbol ("INTC");formatter.addSymbol ("JAVA");formatter.addSymbol ("MSFT");formatter.generateOutput ();}}© Robert Miller 2007 Exercise which modules would you need to modify to... ¾handle new RTF syntax for italics?¾put the ask price in bold if the stock went down since open?¾use Google Finance instead of Yahoo?¾add year-to-date change to the report?What We’ve Achieved dependency diagram ¾arc means “depends on” invokes QuoteFormatter with tickers & selects output format Gen obtains and outputs quotes Quoter HTMLGenerator RTFGenerator obtains quotes formats text in HTML formats text in RTF QuoteApp QuoteFormatter © Robert Miller 2007 An Interface is a Specification a general strategy ¾client should only know about the specification of the service it uses ¾so decouple the client from the service by interposing the specification in Java: ¾the specification is declared by an interface ¾the service is plugged in by passing an object implementing that interface specification is a contract ¾we’ll see more about this idea in later lectures © Robert Miller 2007 © Robert Miller 2007 5 plugin is selected here obtains and outputs quotes invokes QuoteFormatterwith tickers & selects output format QuoteApp QuoteFormatter Generator Quoter HTMLGenerator RTFGenerator obtains quotes formats text in HTML formats text in RTFOther Uses of Interfaces decoupling from choice of representation ¾very common and importantList recording = new ArrayList();recording add( );recording.add(...); List recording = new LinkedList (); recording.add(...); “marker” interfaces ¾declare no methods¾used to expose specification properties (e.g. java.util.RandomAccess)¾or as a hack to add functionality (e.g. java.io.Serializable)© Robert Miller 2007 Summary system design principles ¾modularity¾decoupling using interfacesdependency diagrams ¾show essence of code design¾missing dependences are the interesting ones!© Robert Miller 2007 6
Description
After completing this lesson, you should be able to do the Modularity, decoupling, information hiding, module dependence diagrams and using interfaces for decoupling.Modularity is an essential for managing complexity . System is divided into parts (modules) that can be handled separately and recombined in other combinations coupling,degree of dependence between parts of the system, an important measurement of modularity.
Instructors: Prof. Daniel Jackson, Prof. Robert Miller MIT Course Number: 6.005 Level: Undergraduate, 6.005 8. Decoupling and interfaces, Elements of Software Construction, Electrical Engineering and Computer Science, Engineering, Massachusetts Institute of Technology: MIT Open Course Ware, http://ocw.mit.edu (01-11-2011). License: Creative Commons BY-NC-SA: http://ocw.mit.edu/terms/#cc.
Presentation Transcript
Your Facebook Friends on WizIQ