Tuesday, September 11, 2012

Java program to read a .pst file and save in a excel file

Below is the java program to create and write a excel file.

 ShibExcel.java
package mail2tickets;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class ShibExcel {

    public static  WritableCellFormat timesBoldUnderline;
    public static  WritableCellFormat times;
    private  String inputFile;

public void setOutputFile(String inputFile) {
    this.inputFile = inputFile;
    }

    public  void createLabel(WritableSheet sheet)
            throws WriteException {
        // Lets create a times font
        WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
        // Define the cell format
        times = new WritableCellFormat(times10pt);
        // Lets automatically wrap the cells
        times.setWrap(true);

        // Create create a bold font with unterlines
        WritableFont times10ptBoldUnderline = new WritableFont(
                WritableFont.TIMES, 10, WritableFont.BOLD, false,
                UnderlineStyle.SINGLE);
        timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
        // Lets automatically wrap the cells
        timesBoldUnderline.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(times);
        cv.setFormat(timesBoldUnderline);
        cv.setAutosize(true);

        // Write a few headers
     
        addCaption(sheet, 0, 0, "Sender_name");
                addCaption(sheet, 1, 0, "Sender_email");
                addCaption(sheet, 2, 0, "Subject");
        addCaption(sheet, 3, 0, "Email_to");
                addCaption(sheet, 4, 0, "Email_cc");
        addCaption(sheet, 5, 0, "Email_bcc");
                addCaption(sheet, 6, 0, "create_time");
        addCaption(sheet, 7, 0, "submit_time");
                addCaption(sheet, 8, 0, "isRead");
        addCaption(sheet, 9, 0, "hasAttachment");
                addCaption(sheet, 10, 0, "hasForwarded");
        addCaption(sheet, 11, 0, "hasReplied");
                addCaption(sheet, 12, 0, "Importance");
     


    }

    public void addCaption(WritableSheet sheet, int column, int row, String s)
            throws RowsExceededException, WriteException {
        Label label;
        label = new Label(column, row, s, timesBoldUnderline);
        sheet.addCell(label);
    }

    public void addNumber(WritableSheet sheet, int column, int row,
            Integer integer) throws WriteException, RowsExceededException {
        Number number;
        number = new Number(column, row, integer, times);
        sheet.addCell(number);
    }

    public  void addLabel(WritableSheet sheet, int column, int row, String s)
            throws WriteException, RowsExceededException {
        Label label;
        label = new Label(column, row, s, times);
        sheet.addCell(label);
    }

}

The below program reads a .pst file and save the data in excel file

InboxMail.java  
package mail2tickets;


import java.io.*;
import Shibsentmail.com.pff.*;
import java.util.*;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class InboxMail {

    WritableCellFormat timesBoldUnderline;
    WritableCellFormat times;


    public static void main(String[] args) {
        new InboxMail("D:/Data/Outlook Emails/Personal Folders.pst","D:/");
    
    }

    private InboxMail(String string) {
        //throw new UnsupportedOperationException("Not yet implemented");
    }


    public void Smail(String file,String location)
    {
       new InboxMail(file.replace("\\", "/"),location.replace("\\", "/"));


    }

    public InboxMail(String filename,String location) {
        try {
            PSTFile pstFile = new PSTFile(filename);
            System.out.println(pstFile.getMessageStore().getDisplayName());
            ShibExcel WE = new ShibExcel();
            String inputFile1 = location+"/ShibInbox.xls";
            System.out.println(inputFile1);
            WE.setOutputFile(inputFile1);
            File file = new File(inputFile1);
            WorkbookSettings wbSettings = new WorkbookSettings();

            wbSettings.setLocale(new Locale("en", "EN"));

            WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
            workbook.createSheet("Report", 0);
            WritableSheet excelsheet1 = workbook.getSheet(0);
            WE.createLabel(excelsheet1);
            processFolder(pstFile.getRootFolder(), excelsheet1,location);
            workbook.write();
            workbook.close();
        } catch (Exception err) {
            err.printStackTrace();
        }
    }
    int depth = -1;
    int inc = 1;

    public void processFolder(PSTFolder folder, WritableSheet excelsheet,String location)
            throws PSTException, java.io.IOException, WriteException, RowsExceededException {

        try {





            File f = new File(location+"/InboxMail_Log.log");
            Boolean b = f.createNewFile();
            System.out.println(b);
            BufferedWriter outt = new BufferedWriter(new FileWriter(f, true));


            depth++;
            // the root folder doesn't have a display name
            if (depth > 0) {

                if (folder.getDisplayName().equalsIgnoreCase("Inbox")) {
                    //printDepth();

                    // System.out.println(folder.getDisplayName());
                    outt.write(folder.getDisplayName() + " \\n");
                }

            }

            // go through the folders...
            if (folder.hasSubfolders()) {
                Vector<PSTFolder> childFolders = folder.getSubFolders();
                for (PSTFolder childFolder : childFolders) {
                    processFolder(childFolder, excelsheet,location);
                }
            }


            // and now the emails for this folder
            if ((folder.getContentCount() > 0) && (folder.getDisplayName().equalsIgnoreCase("Inbox"))) {
                depth++;
                PSTMessage email = (PSTMessage) folder.getNextChild();

                while (email != null) {
                    // WritableSheet sheet1 = null;
                    try {

                        outt.write("|- Sender Name : " + email.getSenderName() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 0, inc, email.getSenderName().toString());
                        outt.write("|- Sender Email : " + email.getSenderEmailAddress() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 1, inc, email.getSenderEmailAddress());
                        outt.write("|- Email Subject : " + email.getSubject() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 2, inc, email.getSubject());
                        outt.write("|- Display to : " + email.getDisplayTo().replace("'", "") + " \\n");
                        new ShibExcel().addLabel(excelsheet, 3, inc, email.getDisplayTo().replace("'", ""));
                        outt.write("|- CC : " + email.getDisplayCC().replace("'", "") + " \\n");
                        new ShibExcel().addLabel(excelsheet, 4, inc, email.getDisplayCC().replace("'", ""));
                        outt.write("|- BCC : " + email.getDisplayBCC().replace("'", "") + " \\n");
                        new ShibExcel().addLabel(excelsheet, 5, inc, email.getDisplayBCC().replace("'", ""));
                        outt.write("|- Creation Time : " + email.getCreationTime() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 6, inc, email.getCreationTime().toLocaleString());
                        outt.write("|- Submit Time : " + email.getClientSubmitTime() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 7, inc, email.getClientSubmitTime().toString());
                        outt.write("|- Read : " + email.isRead() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 8, inc, email.isRead() + "");
                        outt.write("|- Attachments : " + email.hasAttachments() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 9, inc, email.hasAttachments() + "");
                        outt.write("|- Forwarded : " + email.hasForwarded() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 10, inc, email.hasForwarded() + "");
                        outt.write("|- Replied : " + email.hasReplied() + " \\n");
                        new ShibExcel().addLabel(excelsheet, 11, inc, email.hasReplied() + "");
                        outt.write("|- Importance : " + email.getImportance() + " \\n \\n");
                        new ShibExcel().addLabel(excelsheet, 12, inc, email.getImportance() + "");
                        System.out.println(inc);

                    } catch (Exception sqle1) {
                        System.out.println(sqle1);
                    }


                    email = (PSTMessage) folder.getNextChild();
                    inc++;
                }
                depth--;
            }
            depth--;
            outt.close();


        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    public void printDepth() {
        for (int x = 0; x < depth - 1; x++) {
            System.out.print(" | ");
        }
        System.out.print(" |- ");
    }
}

Connect to MySQL with JDBC driver

import java.sql.*;

public class MySqlConnect{
  public static void main(String[] args) {
       try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Polaroid?user=root&password=");
                Statement st = con.createStatement();
                ResultSet rs = st.executeQuery("select * from cases");

                while(rs.next()) {
                    System.out.println( rs.getString("id"));
                }
                st.close();
                rs.close();
                con.close();
        } catch (Exception ex) {
                ex.printStackTrace();
        }


  }
}

Monday, September 3, 2012

JDBC Questions & Answer

1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2. What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it’s own stored procedure language,
3. What is JDBC Driver ?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.
4. What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.
5. What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.
6. What is a ResultSet ?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
7. What is Connection?
Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
8. What does Class.forName return?
A class as loaded by the classloader.
9. What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.
10. What are the different JDB drivers available?
There are mainly four type of JDBC drivers available. They are:
Type 1 : JDBC-ODBC Bridge Driver – A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
Type 4: JDBC Net pure Java Driver – A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
11. What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
12. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
13. What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’ ) is a backup taken of each tablespace while the database is running and is being accessed by the users
14. What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
15. How do you handle your own transaction ?
Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

Monday, July 2, 2012

Log4j - Logging Framework

Logging basics

Logging can be defined as a process of storing information about events that occurred during program execution. There are different options to show/store log messages:

- show on console
- store in a file
- send to a remove monitor

Choosing the right option depends on the requirements and type of application.

Normally every java coder does logging even if he is not uing any logging framework. For instance, System.out.println statement is used to print informative message on the console. These messages can also contain the timestamp and other useful information which will make these messages interesting for the viewer and can help in error tracking and performance monitoring. But if you use a logging framework, then there is a big plus. The logging framework adds contextual information like line number, timestamp etc which prevents the developers from writing extra code. Result is better logging and less cost.

Importance of logging applications

Logging helps in debugging as well. Although debuggers are available but frankly it takes time to debug an application using a debugger. An application can be debugged more easily with few well-placed logging messages. So we can safely say that logging is a very good debugging tool. If logging is done sensibly and wisely, it can provide detailed context for application failures.

In distributed applications (e.g. web/remote applications), the logging is very important. The administrator can read logs to learn about the problems that occurred during some interval.

Java's built-in APIs provide logging options but they are not that flexible. Another option is to use Apache’s open source logging framework called log4j.

Drawbacks of logging applications

There are some drawbacks of use logging in your application. For example: logging will

- pollute the code
- increase the size of the code
- reduce the speed

These are important points because, we ultimately want efficient applications. Log4J has the solution to this. You may turn on or turn off the logging at runtime by changing the configuration file. This means no change in the Java source code (binary).

Log4j

log4j is an open source project created by Apache and is part of Apache Logging Services Project. Currently Apache has 3 logging frameworks:

- log4j for Java
- log4cxx for C++
- log4net for the Microsoft .NET framework

Apache also provides a tool called Chainsaw, which can be used for log analysis. If you are interested to learn about Chainsaw, visit the following link:
Apache Chainsaw -
API docs available at:
Logger (Apache Log4j 1.2.15 API)

The log4j package can be downloaded from
Apache Logging Services Project - Apache log4j

Standard API vs log4j

A common question asked by Java developers is:

Why we should use log4j logging framework when Java provides an API for logging (java.util.logging)?

Log4j has following advantages over standard logging API:
- log4j provides robust logging
- log4j has more features available than standard logging API
- configuring and using log4j is easier
- log4j also has a much more robust formatting system
- many add-on programs and handlers are available for log4j

Configuring log4j

Configuring log4j is very simple. You have to download the log4j-xxx.jar (xxx is the version no) file from the Apache logging services web site which is:
Apache Logging Services Project - Apache log4j

Currently there are 3 different versions available which are log4j 1.2, log4j 1.3 and log4j 2.0.

Once you have the jar file, you have to include that in your CLASSPATH. In Eclipse, you can simply import that jar file in your project.

Categories of log messages

Before using log4j framework, one should be aware of different categories of log messages. Following are 5 categories:

DEBUG
The DEBUG Level is used to indicate events that are useful to debug an application. Handling method for DEBUG level is: debug().

INFO
INFO level is used to highlight the progress of the application. Handling method for INFO level is: info().

WARN
The WARN level is used to indicate potentially harmful situations. Handling method for WARN level is: warn().

ERROR
The ERROR level shows errors messages that might not be serious enough and allow the application to continue. Handling method for ERROR level is: error().

FATAL
The Fatal level is used to indicate severe events that will may cause abortion of the application. Handling method for FATAL level is: fatal().

If you declare log level as debug in the configuration file, then all the other log messages will also be recorded.
If you declare log level as info in the configuration file, then info, warn, error and fatal log messages will be recorded.
If you declare log level as warn in the configuration file, then warn, error and fatal log messages will be recorded.
If you declare log level as error in the configuration file, then error and fatal log messages will be recorded.
If you declare log level as fatal in the configuration file, then only fatal log messages will be recorded.

Main Components

There are 3 main components that are used to log messages based upon type and level. These components also control the formatting and report place at runtime. These components are:

- loggers
- appenders
- layouts


log4j.properties file

log4j.properties file is a configuration file (not in XML format). If you have a stand alone application, then log4j.properties should be in the directory where you issued the java command. In case of web application (JSP/Servlet), place log4j.properties at /WEB-INF/classes/.

A sample properties file is given below:

log4j.appender.stdout=org.apache.log4j.ConsoleAppe nder
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.Patt ernLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=C:\\Log4J\\src\\tmp\\logs \\log.txt
log4j.appender.FILE.layout=org.apache.log4j.Patter nLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.rootLogger=debug, FILE,stdout

We have used only two appenders (ConsoleAppender and FileAppender)in the example above. All the possible appender options are:

AppenderSkeleton, AsyncAppender, ConsoleAppender, DailyRollingFileAppender, ExternallyRolledFileAppender, FileAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender, NullAppender, RollingFileAppender, SMTPAppender, SocketAppender, SocketHubAppender, SyslogAppender, TelnetAppender, WriterAppender

We have used PatternLayout with both the appenders. All the possible options are:

DateLayout, HTMLLayout, PatternLayout, SimpleLayout, XMLLayout

So interesting thing is, you can generate log in HTML and in XML format as well.

If you use HTMLLayout or XMLayout, then you should not mention ConversionPattern.

Example

Time for an example. I have written a class named LogTest. Its purpose is to create a Vector and populate it. After populating, I tried to add the element at its 10th index to an integer value. I want to create log for this application. My concerns are to track the vector size as well. Vector, if created using default constructor has initial capacity of 10. When capacity is reached, Vector’s capacity will be doubled which is a costly activity. That’s why I want to log the size and capacity of vector and want to know when capacity is increased. It can help me in application tuning. Also I am interested in knowing how much time it took to populate the Vector with 50 elements. Although logging activity also takes time (for printing on console, for rating to the log file), but let’s ignore this for the time being.

log4j.properties file for the application described above is as follows:

log4j.appender.stdout=org.apache.log4j.ConsoleAppe nder
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.Patt ernLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=C:\\Log4J\\src\\tmp\\logs \\log.txt
log4j.appender.FILE.layout=org.apache.log4j.Patter nLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
log4j.rootLogger=debug, FILE,stdout

We have used two options for logging. On console and on file. We can use other options as well. The list line
log4j.rootLogger=debug, FILE,stdout

is very important. It is used to control logging at runtime without altering the Java code. It declares that output log should be generated on console and on to file. File path is mentioned above in the file. It also declares the logging level. Logging level is DEBUG, which means that all the log messages (debug, info, warn, error, fatal) will be recorded.

LogTest.java
Java Code:






















































public class LogTest {
private static org.apache.log4j.Logger log = Logger.getLogger(LogTest.class);

public static void main(String[] args) {

Vector<String> vector = new Vector<String>();
log.info("Vector created with size: " + vector.capacity());

boolean limitReached = false;

Long start = System.currentTimeMillis();
for(int i=0;i<50; i++)
{
vector.addElement("Element" + i);

if(limitReached)
{
limitReached = false;
log.debug("Current index: " + i);
log.info("Vector limit increased. Now the capacity is: " +  vector.capacity());
}

if(vector.capacity()-vector.size() == 1)
{
log.debug("Current index: " + i);
log.info("Current vector capacity is: " + vector.capacity());
log.info("Current vector size is: " + vector.size());
log.warn("Vector size is about to increase.");
}
if(vector.capacity()-vector.size() == 0)
{
limitReached = true;
log.debug("Current index: " + i);
log.info("Current vector capacity is: " + vector.capacity());
log.info("Current vector size is: " + vector.size());
log.warn("Vector limit reached.");
}

}

Long stop = System.currentTimeMillis();

log.info("Time for populating (in millisec): " + (stop - start));

try{
int sum = (Integer.parseInt(vector.elementAt(10)) + 10);
}
catch(java.lang.NumberFormatException e)
{
log.error(vector.elementAt(10) + " cannot be converted into integer.");
}

log.shutdown();
}
}
It is a good programming practice to shut down the logging subsystem when you finish logging.

I have used debug, info, warn and error log messages according to the logic. Of course, one can argue and can use debug in case of info or any other option. As I said, it depends on your domain and logic.

Output: log.txt
Java Code:

































[Dez 13 11:51:39] INFO  (LogTest.java:12) - Vector created with size: 10
[Dez 13 11:51:39] DEBUG (LogTest.java:30) - Current index: 8
[Dez 13 11:51:39] INFO  (LogTest.java:31) - Current vector capacity is: 10
[Dez 13 11:51:39] INFO  (LogTest.java:32) - Current vector size is: 9
[Dez 13 11:51:39] WARN  (LogTest.java:33) - Vector size is about to increase.
[Dez 13 11:51:39] DEBUG (LogTest.java:38) - Current index: 9
[Dez 13 11:51:39] INFO  (LogTest.java:39) - Current vector capacity is: 10
[Dez 13 11:51:39] INFO  (LogTest.java:40) - Current vector size is: 10
[Dez 13 11:51:39] WARN  (LogTest.java:41) - Vector limit reached.
[Dez 13 11:51:39] DEBUG (LogTest.java:24) - Current index: 10
[Dez 13 11:51:39] INFO  (LogTest.java:25) - Vector limit increased. Now the capacity is: 20
[Dez 13 11:51:39] DEBUG (LogTest.java:30) - Current index: 18
[Dez 13 11:51:39] INFO  (LogTest.java:31) - Current vector capacity is: 20
[Dez 13 11:51:39] INFO  (LogTest.java:32) - Current vector size is: 19
[Dez 13 11:51:39] WARN  (LogTest.java:33) - Vector size is about to increase.
[Dez 13 11:51:39] DEBUG (LogTest.java:38) - Current index: 19
[Dez 13 11:51:39] INFO  (LogTest.java:39) - Current vector capacity is: 20
[Dez 13 11:51:39] INFO  (LogTest.java:40) - Current vector size is: 20
[Dez 13 11:51:39] WARN  (LogTest.java:41) - Vector limit reached.
[Dez 13 11:51:39] DEBUG (LogTest.java:24) - Current index: 20
[Dez 13 11:51:39] INFO  (LogTest.java:25) - Vector limit increased. Now the capacity is: 40
[Dez 13 11:51:39] DEBUG (LogTest.java:30) - Current index: 38
[Dez 13 11:51:39] INFO  (LogTest.java:31) - Current vector capacity is: 40
[Dez 13 11:51:39] INFO  (LogTest.java:32) - Current vector size is: 39
[Dez 13 11:51:39] WARN  (LogTest.java:33) - Vector size is about to increase.
[Dez 13 11:51:39] DEBUG (LogTest.java:38) - Current index: 39
[Dez 13 11:51:39] INFO  (LogTest.java:39) - Current vector capacity is: 40
[Dez 13 11:51:39] INFO  (LogTest.java:40) - Current vector size is: 40
[Dez 13 11:51:39] WARN  (LogTest.java:41) - Vector limit reached.
[Dez 13 11:51:39] DEBUG (LogTest.java:24) - Current index: 40
[Dez 13 11:51:39] INFO  (LogTest.java:25) - Vector limit increased. Now the capacity is: 80
[Dez 13 11:51:39] INFO  (LogTest.java:48) - Time for populating (in millisec): 94
[Dez 13 11:51:39] ERROR (LogTest.java:55) - Element10 cannot be converted into integer.
Ok, we have the log file. It shows the log messages with date/time stamp.

Log messages are appended to the file so you don’t need to worry about lose of information in the log files.

Using XMLLayout

If you are interested in getting XML file with log messages, then you don’t need to change anything in the Java code. That’s the beauty of log4j framework. You simple have to add the following line in the configuration file:

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=C:\\Log4J\\src\\tmp\\logs \\log.xml
log4j.appender.FILE.layout=org.apache.log4j.xml.XM LLayout
log4j.rootLogger=debug, FILE

Screenshot of output:
Log4j (Logging Framework)-xmloutput.jpg

Using HTMLLayout

Lets generate HTML log files. Put the following in the configuration file:

log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.file=C:\\Log4J\\src\\tmp\\logs \\log.html
log4j.appender.FILE.layout=org.apache.log4j.HTMLLa yout
log4j.rootLogger=debug, FILE

Screenshot of output:
Log4j (Logging Framework)-htmloutput.jpg

Conclusion

Log4J is very flexible, easy to learn and configure. It is ideal for distributed applications but it can also be used as good debugging tool for standalone applications. Logs can be generated on the console or on a text file in simple format, in XML format or in HTML format. A must use framework.

Java logical programs

Fibonacci Series

This Program generates Fibonnaci Series for a given number of times.
Output: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
public class FibonnaciSeries {
/*
* Generates the Fibonnaci Series
*/
public void generateSeries(int num) {
int f1, f2 = 0, f3 = 1;
System.out.println(“fib(0) = ” + f2);
for (int i = 1; i <= num; i++) {
System.out.println("fib(" + i + ") = " + f3);
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
public static void main(String[] args) {
System.out.println("*****Fibonnaci Series*****");
FibonnaciSeries fb = new FibonnaciSeries();
fb.generateSeries(10);
}
}

Highest Prime Number

Given a number this program generates the highest prime number.
Output: If the input is 25, the highest prime number close to 25 is 23. It prints 23.

public class PrimeNumber {
/*
* Given a number, finds the highest prime number.
*/
public static int highestPrime(int n) {
int value = 1;
for (int i = 2; i <= n; i++) {
// System.out.println("n: " + n + " i: " + i + " mod: " + n%i);
if (i == n) {
value = n;
break;
}
if (n % i == 0) {
n--;
}
}
return value;
}
public static void main(String[] args) {
int value = highestPrime(25);
System.out.println("Prime:" + value);
}
}

Triangle Printing

Given a number, this program prints the numbers in the right angle manner.
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14

public class TrianglePrinting {
/*
* Prints the numbers in the right angle manner.
*/
public static void trianglePrinting(int n) {
int counter = 0, i = 1;
while (i <= n) {
counter++;
for (int j = 0; j < counter; j++) {
if (i > n)
break;
System.out.print(i + ” “);
i++;
}
System.out.println();
}
}
public static void main(String[] args) {
trianglePrinting(14);
}
}
Print Reverse number example 123 as 321

public class ReverseTest
{

public static void main(String[] args)
{
int n = 345897;
int sum = 0, rev = 0;
while(n!=0)
{
rev= n%10;
sum = (sum*10)+rev;
n = n/10;
}
System.out.println("Reverse number is "+sum);
}

}

Prime Number program

public class PrimeTest
{


public static boolean isPrime(int num)
{
boolean prime = true;
int limit = (int)Math.sqrt(num);
for(int i=2; i<=limit;i++)
{
if(num%i==0)
{
prime = false;
break;
}

}
return prime;
}
public static void main(String[] args)
{
for(int i=2;i<1000;i++)
{
if(isPrime(i))
{
System.out.print(" "+i);
}
}
}
}

Fibonacci Series

public class FibTest
{
public static void main(String[] args)
{
int f1=0,f2=0, f3 =1;
for (int i=1;i<20;i++)
{
f1 = f2;
f2= f3;
f3 = f1+f2;
System.out.print(" "+f3);
}

}

}


SumTest


public class SumTest
{
public static void main(String args[])
{
int n = 4566;
int sum =0;
while(n!=0)
{
sum = sum + (n%10);
n = n/10;
}
System.out.println("Sum is "+sum);
}
}

// Recursion

public class StringReverseTest
{
public static void main(String[] args)
{
String str = "Gangadhararao Bommasani";
str = reverse(str, str.length());
System.out.println(str);
}
public static String reverse(String input, int index)
{
if(index==0) return "";
return input.charAt(index-1)+ reverse(input, index-1);
}

}

Write a java Program to display Pyramid.
public class Pyramid {
    public static void main(String...strings){
        int i,j,k;
        for(i=1;i<=5;i++){
            for(j=5;j>=i;j--){
                System.out.print(" ");
            }
            for(k=1;k<=i;k++){
                System.out.print(" @");
            }
            System.out.println("");
        }
    }
}
Output :
           @
        @ @
      @ @ @
    @ @ @ @
  @ @ @ @ @

Check wheather String is palindrome or not?

import java.util.Scanner;
public class Practical1 {
public static void main(String argv[]){
System.out.print("Enter String ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringBuffer sb = new StringBuffer(input);
String revStr = sb.reverse().toString();
if(revStr.equals(input)){
System.out.println("String is Palindrome");
}
else {
System.out.println("String is Not Palindrome");
}
}
}
/*Write a program to Find Factorial of Given no. */
class Factorial{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);                 //take argument as command line
          int result = 1;
          while(num>0){
                result = result * num;
                num--;
          }
          System.out.println("Factorial of Given no. is : "+result);
   }
}
/* Write a program to find sum of all integers greater than 100 and
   less than 200 that are divisible by 7 */
class SumOfDigit{
      public static void main(String args[]){
      int result=0;
      for(int i=100;i<=200;i++){
           if(i%7==0)
              result+=i;
      }
      System.out.println("Output of Program is : "+result);
   }
}
/* Write a program to Swap the values */
class Swap{
      public static void main(String args[]){
      int num1 = Integer.parseInt(args[0]);
      int num2 = Integer.parseInt(args[1]);
      System.out.println("\n***Before Swapping***");
      System.out.println("Number 1 : "+num1);
      System.out.println("Number 2 : "+num2);
      //Swap logic
      num1 = num1 + num2;
      num2 = num1 - num2;
      num1 = num1 - num2;
      System.out.println("\n***After Swapping***");
      System.out.println("Number 1 : "+num1);
      System.out.println("Number 2 : "+num2);
      }
}
/*Write a program to find whether given no. is Armstrong or not.
  Example :
           Input - 153
           Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */
class Armstrong{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      int n = num; //use to check at last time
      int check=0,remainder;
      while(num > 0){
           remainder = num % 10;
           check = check + (int)Math.pow(remainder,3);
           num = num / 10;
      }
      if(check == n)
            System.out.println(n+" is an Armstrong Number");
      else
            System.out.println(n+" is not a Armstrong Number");
   }
}
/* Write a program to Find whether number is Prime or Not. */
class PrimeNo{
      public static void main(String args[]){
          int num = Integer.parseInt(args[0]);
         int flag=0;
         for(int i=2;i<num;i++){
             if(num%i==0)
              {
                 System.out.println(num+" is not a Prime Number");
                 flag = 1;
                 break;
              }
         }
         if(flag==0)
             System.out.println(num+" is a Prime Number");
    }
}
/* Write a program to generate Harmonic Series.
   Example :
           Input - 5
           Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */
class HarmonicSeries{
      public static void main(String args[]){
      int num = Integer.parseInt(args[0]);
      double result = 0.0;
      while(num > 0){
            result = result + (double) 1 / num;
            num--;
      }
      System.out.println("Output of Harmonic Series is "+result);
  }
}
/* Display Triangle as follow
    0
    1 0
    1 0 1
    0 1 0 1 */
class Output2{
      public static void main(String args[]){
           for(int i=1;i<=4;i++){
              for(int j=1;j<=i;j++){
                            System.out.print(((i+j)%2)+" ");
                    }
                    System.out.print("\n");
                 }
     }
}       

Friday, June 29, 2012

Design Patterns Explained - Review Questions and Answers


Table of Contents

  • Chapter 1: The Object-Oriented Paradigm
  • Chapter 2: The UML - The Unified Modeling Language
  • Chapter 3: A Problem That Cries Out for Flexible Code
  • Chapter 4: A Standard Object-Oriented Solution
  • Chapter 5: An Introduction to Design Patterns
  • Chapter 6: The Façade Pattern
  • Chapter 7: The Adapter Pattern
  • Chapter 8: Expanding Our Horizons
  • Chapter 9: The Strategy Pattern
  • Chapter 10: The Bridge Pattern
  • Chapter 11: The Abstract Factory Pattern
  • Chapter 12: How Do Experts Design?
  • Chapter 13: Solving The CAD/CAM Problem with Patterns
  • Chapter 14: The Principles and Strategies of Design Patterns
  • Chapter 15: Commonality and Variability Analysis (CVA)
  • Chapter 16: The Analysis Matrix
  • Chapter 17: The Decorator Pattern
  • Chapter 18: The Observer Pattern
  • Chapter 19: The Template Method Pattern
  • Chapter 20: Lessons from Design Patterns: Factories
  • Chapter 21: The Singleton Pattern and the Double-Checked Locking Pattern
  • Chapter 22: The Object Pool Pattern
  • Chapter 23: The Factory Method Pattern
  • Chapter 24: Summary of Factories (no review questions)
  • Chapter 25: Design Patterns Reviewed: A Summation and a Beginning

Chapter 1: The Object-Oriented Paradigm

Observations

1. Describe the basic approach used in functional decomposition.
Functional decomposition is the approach to analysis that breaks down (decomposes) a problem into its functional parts without too much concern for global requirements and future modifications.
2. What are three reasons that cause requirements to change?
The user's understanding of what they need and what is possible grows and changes as they discuss the problem with analysts. The developer's understanding of what is possible and what is needed evolves as they become familiar with the domain and with the software. The technical environment evolves, forcing changes in how to implement.
3. I advocate thinking about responsibilities rather than functions. What is meant by this? Give an example.
Rather than thinking first about how something is done (functions), the analyst should focus on what the routine is responsible for doing - how it does it does not matter. The control program is much simpler in this case.
4. Define "coupling" and "cohesion". What is "tight" coupling?
Cohesion is how strongly the internal operations of a routine are related to each other. Coupling is how strongly a routine is dependent upon other routines.
5. What is the purpose of an "interface" to an object?
It provides the methods whereby other objects can tell the object what to do.
6. Define instance of a class.
A specific, unique occurrence of a more abstract object. An object is an instance of a class.
7. A class is a complete definition of the behavior of an object. What three aspects of an object does it describe?
The three elements of a class are: the data elements, the methods, the interfaces (ways that data and methods can be accessed).
8. What does an abstract class do?
At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a name or label to a set of classes. At the specification level, an abstract class is a class that does not get instantiated.
9. What are the three main types of accessibility that objects can have?
Public, Protected, Private
10. Define encapsulation. Give one example of encapsulation of behavior.
Any kind of hiding. Both data and behavior may be encapsulated.
11. Define polymorphism. Give one example of polymorphism.
The ability to refer to different derivations of a class in the same way.
12. What are the three perspectives for looking at objects?
Conceptual: the high-level concepts in a system (concepts, not software). At the conceptual level, an object is a set of responsibilities.
Specification: the interfaces between things in the software (software, not code). At the specification level, an object is a set of methods.
Implementation: how an individual routine works (code). At the implementation level, an object is code and data.

Interpretations

13. Sometimes, programmers use "modules" to isolate portions of code. Is this an effective way to deal with changes in requirements? Why or why not?
Changes to one function or routine can have impacts on other routines. Usually, routines are not independent .
14. It is too limited to define an abstract class as a class that does not get instantiated. Why is this definition too limited? What is a better (or at least alternative) way to think about abstract classes?
It is too limited because it only talks in terms of its implementation: what the abstract class does and how it is treated as software. It does not describe why I would want to use an abstract class: the motivation for it and how to think about it. It ignores the "conceptual perspective" of objects that analysts need to keep in mind as they work with users to understand problems. At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a name or label to a set of classes so that I can interact with them as a whole without getting trapped by the details.
15. How does encapsulation of behavior help to limit the impact of changes in requirements? How does it save programmers from unintended side effects?
It makes the control program much less complicated since it does not have to be responsible for as much. It limits the impact that changes to the internals of an object can have on the rest of the application.
16. How do interfaces help to protect objects from changes that are made to other objects?
Interfaces define the only ways that those external objects can communicate with the object. It protects me from side effects because I know what is coming into the system.
17. A classroom is used to describe objects in a system. Describe this classroom from the conceptual perspective.
The classroom contains students who are responsible for their own behaviors: how to move from here to there, how to go from class to class. It contains a teacher who tells students where to go.

Opinions and Applications

1. Changing requirements is one of the greatest challenges faced by systems developers. Give one example from your own experience where this has been true.
2. There is a fundamental weakness in functional decomposition when it comes to changes in requirements. Do you agree? Why or why not?
3. What do you think is the best way to deal with changing requirements?


Chapter 2: The UML - The Unified Modeling Language

Observations

1. What is the difference between an "is-a" relationship and a "has-a" relationship? What are the two types of "association" relationships?
"is-a" indicates that one object is a "kind of" a class; for example, a "sail boat" is a kind of "boat" which is a kind of "type of transportation".
"has-a" indicates that one class "contains" another class; for example, a car has wheels.
There are two types of "associations": containment (has-a) and "uses"
2. In the Class diagram, a class is shown as a box, which can have up to three parts. Describe these three parts.
The  box is the name (label) of the class. This is required.
The middle box, if it is shown, shows the data members of the class.
The bottom box, if it is shown, shows the methods (functions) of the class.
3. Define cardinality.
Cardinality indicates the number of things that another object can have
4. What is the purpose of a Sequence diagram?
The Sequence diagram is one type of Interaction Diagram in the UML. It shows how objects interact with other objects.

Interpretations

1. Give an example of an "is-a" relationship and the two "association" relationships. Using these examples,
Draw them in a Class diagram
Show cardinality on this Class diagram
Is-a example: "Sailboat" is-a "boat"
Has-a example: Sailboat has-a sail (one to many)
Uses example: A marina contains one or more Sailboats
2. Figure 2-8 shows a Sequence diagram. How many steps are shown in the figure? How many objects are shown and what are they?
There are 13 steps in the diagram
There are 6 objects shown: Main, ShapeDB, Collection, shape1:Square, shape2:Circle, and Display.
3. When objects communicate with each other, why is it more appropriate to talk about "sending a message" than "invoking an operation"?
When objects "talk" to each other, it is called "sending a message." You are sending a request to another object to do something rather than telling the other object what to do. You allow the other object to be responsible enough to figure out what to do. Transferring responsibility is a fundamental principle of object-oriented programming. It is quite different from procedural programming where you retain control of what to do next, and thus might "calling a method" or "invoke an operation" in another object.

Opinions and Applications

1. How many steps should be shown on a Sequence diagram?
As many as it takes to communicate clearly, and no more


Chapter 3: A Problem That Cries Out for Flexible Code

Observations

1. What five features in sheet metal will this system have to address?
The features are Slot, Hole, Cutout, Special, and Irregular
2. What is the difference between the V1 system and the V2 system?
The V1 system has a collection of subroutine libraries that interacts with the CAD/CAM model. To get information about the CAD/CAM model, you have to make a series of calls
The V2 system is an object-oriented system. The geometry is stored in objects, each of which represents a feature. To get information about a feature, you interrogate the object for that feature.

Interpretations

1. What is the essential challenge of the CAD/CAM problem?
We have different types of CAD/CAM systems. A third system (the "expert system") has to extract information from whichever CAD/CAM system in order to work with the geometry. The two CAD/CAM systems are implemented in completely different ways and require completely different ways of interacting with them, even though they contain essentially the same information
2. Why is polymorphism needed at the geometry-extractor level but not at the feature level?
Polymorphism is required at the geometry extractor level because the "expert system" needs to know what type of features it is dealing with: slot, hole, etc. It is insufficient for the expert system simply to work on generic "features." Polymorphism does not buy me anything at the feature level. The expert system does not need to care about the particular method that is used to extract that feature. While we could hard-code the extraction method into the expert system, that would be bad if we ended up getting a new CAD/CAM system that uses yet another method of working with geometry. Polymorphism frees us from having to worry about the particular extraction method: the expert system can simply use a generic "geometry extractor" that worries about extractions.

Opinions and Applications

1. I spend time defining terms related to the CAD/CAM problem.
Why did I do this?
Did you find this useful or a distraction?
Is it important to understand the user's terminology?
What is the most effective method you have found for recording user terminology?


Chapter 4: A Standard Object-Oriented Solution

Observations

1. Identify each of the elements of the UML diagram in Figure 4-3.
Abstract class
Cardinality
Derivation
Composition
Public methods
Abstract class: Feature (in italics)
Cardinality: A Model can have no Features, 1 Feature, or many Features.
Derivation: SlotFeature, a HoleFeature, a CutoutFeature, an IrregularFeature, or a SpecialFeature all derive from Feature. They are all "kinds of" Features.
Composition: A Model is composed of Features
Public method: Geerations is a public method of the CutoutFeature.
2. What is the essential ability required by the CAD/CAM application?
They need the ability to plug-and-play different CAD/CAM systems without changing the expert system (p. 63)
3. The first solution exhibits four problems. What are they?
There is redundancy amongst the methods It is messy
It has tight coupling: features are related to each other
It has low cohesion: core functions are scattered amongst many classes.

Interpretations

1. Describe the first approach to solving the CAD/CAM problem. Was it a reasonable first approach?
The first object-oriented approach to a solution is to specialize a feature for each case: a Slot class for V1 and a Slot class for V2. Each V1 type case communicates with the V1 libraries and V2 type case communicates with V2 libraries. It is a reasonable approach to begin with (p. 59). It gives insights into the problem. But it should not be implemented!

Opinions and Applications

1. "Delay as long as possible before committing to the details." Do you agree? Why or why not?
2. One solution was rejected because "intuition told me it was not a good solution." Is it appropriate for analysts / programmers to be guided by their instincts?


Chapter 5: An Introduction to Design Patterns

Observations

1. Who is credited with the idea for design patterns?
The architect, Chrisher Alexander developed design patterns in the late 1970s. The "Gang of Four" took this idea in the 1990s and applied them to software design. I point out that one school of anthropology used patterns to study cultures in the 1940s. Also, the ESPRIT consortium used patterns for understanding human thought patterns in ways that could be implemented in computer programs in the 1980s
2. Alexander discovered that by looking at structures that solve similar problems, he could discern what? Designs / solutions that are high quality. And that this was objectively measurable
3. Define pattern. A pattern is a solution to a problem that occurs in a given context.
4. What are the key elements in the description of a design pattern?
To be complete, a pattern description must have the following eight elements:
  • Name: a label that identifies it
  • Intent: a description of the purpose of the pattern
  • Problem: a description of the problem being solved
  • Solution: what the solution is in the given context
  • Participants / Collaborators: the entities involved in the solution
  • Consequences: what happens as a result of using the pattern. What forces are at work.
  • Implementation: how to implement the pattern in one or more concrete ways.
  • GoF Reference: where to look in the Gang of Four book for more information.
5. What are three reasons for studying design patterns?
Patterns make it possible to reuse solutions
Patterns help with communication between analysts, giving a shorthand terminology.
Patterns give you perspective on the problem, freeing you from committing to a solution too early.
6. The Gang of Four suggests a few strategies for creating good object-oriented designs. What are they?
Design to interfaces
Favor aggregation over inheritance Find what varies and encapsulate it  

Interpretations

1. "Familiarity sometimes keeps us from seeing the obvious." In what ways can patterns help avoid this? We can gain insights from previous solutions, have our attention drawn to features of the problem that I might not otherwise think of (until too late)
2. The Gang of Four cataloged 23 patterns. Where did these patterns come from? It came from their insights into solutions that had already been developed within the software community.
3. What is the relationship between "consequence" and "forces" in a pattern? Consequences are the cause-and-effect of using the pattern Forces are the factors at play in a particular problem that constrain and shape the possible solutions.
4. What do you think "find what varies and encapsulate it" means? Look for what is changing and make a more generic version of it so that you can see what is truly going on in your system and not get caught up in the details.
5. Why is it desirable to avoid large inheritance hierarchies? They are very complex to understand and to maintain.

Opinions and Applications

1. Think of a building or structure that felt particularly "dead". What does it not have in common with similar structures that seem to be more "alive"?
2. "The real power of patterns is the ability to raise your level of thinking." Have you had an experience in which this was true? Give an example.


Chapter 6: The Façade Pattern

Observations

1. Define Façade.
A Façade is "The face of a building, especially the principal face" - dictionary.com. It is the front that separates the street from the inside.
2. What is the intent of the Façade pattern?
Provide a unified interface to a set of interfaces in a sub-system
3. What are the consequences of the Façade pattern? Give an example.
The Façade simplifies the use of the required subsystem. However, since the Façade is not complete, certain functionality may be unavailable to the client. Example is a reporting application that needs a routine way to access on certain portions of a database system: The Façade would provide an interface to those portions and not the entire API of the database.
4. In the Façade pattern, how do clients work with subsystems?
Clients work with sub-systems through the Façade's interfaces. They do not interact with the underlying methods directly
5. Does the Façade pattern usually give you access to the entire system?
Not usually. In general, Façade give access to a portion of the system, one that is customized to our needs.

Interpretations

1. The Gang of Four says that the intent of the Façade pattern is to "provide a unified interface to a set of interfaces in a sub-system. Façade defines a higher-level interface that makes the subsystem easier to use." What does this mean? Give an example.
The Façade gives a simpler way to access an existing system by giving an interface that is customized to the needs you have.
Example is a class that insulates a client program from a database system
2. Here is an example of a Facade that comes from outside of software. Pumps at gasoline stations in the US can be very complex. There are many options on them: how to pay, the type of gas to use, watch an advertisement. One way to get a unified interface to the gas pump is to use a human gas attendant. Some states even require this.
  • What is another example from real life that illustrates a Facade?
  • Another example could be a stockbroker who serves as the interface to a complex system of stock trades.

Opinions and Applications

1. If you need to add functionality beyond what the system provides, can you still use the Façade pattern?
2. What is a reason for encapsulating an entire system using the Façade pattern?
3. Is there a case for writing a new system rather than encapsulating the old system with Façade? What is it?
4. Why do you think the Gang of Four call this pattern "Façade"? Is it an appropriate name for what it is doing? Why or why not?


Chapter 7: The Adapter Pattern

Observations

1. Define Adapter.
"Adapter" is something that allows one thing to modify itself to conform to the needs of another thing.
2. What is the intent of the Adapter pattern?
The intent of the Adapter is to match an existing object that is beyond your control to a particular interface.
3. What are the consequences of the Adapter pattern? Give an example.
A consequence is that the pattern allows for preexisting objects to fit into new class structures without being limited by their interfaces (p. 102). The example in the book is the drawing program that wants to use an existing Circle object but the existing object doesn't provide exactly the same methods as the rest of the system. The Adapter provides a translation to these methods.
4. Which object-oriented concept is being used to define the relationship between Shape and Points, Lines, and Squares?
Polymorphism
5. What is the most common use for the Adapter pattern?
To allow for continued use of polymorphism. It is often used in conjunction with other design patterns.
6. What does the Adapter pattern free you from worrying about?
Adapter frees me from worrying about the interfaces of existing classes when doing a design. If the class doesn't do what I need, I can create an Adapter to give it the correct interface.
7. What are the two variations of the Adapter pattern?
Object Adapter: relies on one object to contain the other object.
Class Adapter: uses multiple inheritance to provide the interface

Interpretations

1. The Gang of Four says that the intent of the Adapter pattern is to "convert the interface of a class into another interface that the clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces."
  • What does this mean?
  • Give an example.
It means that I have a class that needs to interact with another class through a certain set of method calls. If the interface of that other class does not provide these method calls, the Adapter sets up a new interface to do the translation. An example would be a reporting application that needs pulls data from two different database systems. My application wants to use a "GetDate" method to pull information from the database, but the database systems don't provide that through their API. I write an Adapter that provides the GetDate method in its interface and is responsible for pulling the data appropriately.
2. "The Circle object wraps the XXCircle object." What does this mean?
Circle completely insulates XXCircle from the system. Circle manifests the entire behavior of XXCircle to the system, although with a different interface / way of accessing XXCircle.  
3. The Façade pattern and the Adapter pattern may seem similar. What is the essential difference between the two?
In both cases, there is a preexisting class or classes that have functionality I need. In both cases, I create an intermediary object with interfaces that my system wants to use and that has responsibility for mapping that to the preexisting class. Both Façade and Adapter are wrappers.
The Adapter is used when the client already has predefined interfaces that it expects to use and when I need to use polymorphism.
The Façade is used when I need a simpler interface to the existing object.
4. Here is an example of an Adapter that comes from outside of software. A translator at the UN lets diplomats from different countries reason about and argue for the positions of their own countries in their own languages. The translator makes "dynamically equivalent" representations from one language to the other so that the concepts are communicated in the way that the recipient expects and needs to hear it.
What is another example from real life that illustrates an Adapter?
Another example could be a travel agent, seen as the common interface between a passenger making arrangements and an airline with its own systems. Each has competing systems, speaking different languages

Opinions and Applications

1. When is it more appropriate to use the Façade pattern rather than the Adapter pattern? How about the Adapter pattern instead of Façade pattern?
2. Why do you think the Gang of Four call this pattern Adapter? Is it an appropriate name for what it is doing? Why or why not?


Chapter 8: Expanding Our Horizons

Observations

1. What do I say is the right way to think about encapsulation?
Encapsulation is best thought of as "any kind of hiding." This can mean hiding data, or behavior, or implementations, or derived classes, or any other thing.
2. What are the three perspectives for looking at a problem? (You may need to review Chapter 1, "The Object-Oriented Paradigm").
The three perspectives are the Conceptual perspective, the Specification perspective, and the Implementation perspective.

Interpretations

1. There are two mention different ways to understand objects: "data with methods" and "things with responsibilities."
  • In what ways is the second approach superior to the first?
  • What additional insights does it provide?
The second approach takes looks at what an object is supposed to do, what its essential concepts are, without worrying about how to do them. It fights against the tendency of programmers to want to jump to coding too soon.
By focusing on what an object is supposed to do rather than how it does it, I can be more flexible in design. It helps to think about the public interfaces that will be required and what those interfaces need to do.
2. Can an object contain another object? Is this different than one object containing a data member?
In object-oriented systems, everything is an object. An object can contain another object, data, or anything. In fact, data types are also objects, so there is no difference.
3. What is meant by the phrase find what varies and encapsulate it? Give an example
Variation represents special cases that complicate understanding. At the conceptual level, find a common label to a set of these variations. Variation can be in data, in behavior
4. Explain the relationship between commonality/variability analysis and the three perspectives of looking at a problem.
By looking at what objects must do (the Conceptual perspective), we determine how to call them (the Specification perspective). Commonality / Variability analysis reveals the interfaces I need to handle all of the cases of the concept.
Specifications become abstract classes at the implementation level . Given a specification, the Implementation perspective shows how each of its variations must handled. 
5. An abstract class maps to the "central binding concept." What does this mean?
The core concept is what defines what is common across a set of things that vary. An abstract class represents this core concept. The name you give to that core concept Is the name for the abstract class.
6. "Variability analysis reveals how family members vary. Variability only makes sense within a given commonality."
  • What does this mean?
  • What types of objects are used to represent the common concepts?
  • What types of objects are used to represent the variations?
Variability analysis looks for all of the variants of a concept: all of the concrete instances of an abstract class. The "commonality" labels the essential concept that ties the variations together. The goal is to find the best unifying name for the set of variations so that you can have a handle to work with them as a set: to work with the forest instead of the trees.
Abstract classes are used to represent the common concept. Concrete instances are used to represent the variations.

Opinions and Applications

1. Why is it better to start out focusing on motivations rather than on implementation? Give an example where this has helped you.
2. Preconceived notions limit one's ability to understand concepts. This was shown to be the case with encapsulation. Can you think of a situation in which your preconceived notions got in the way of understanding requirements? What happened and how did you overcome it?
3. The term inheritance is used both when a class derives from an nonabstract class to make a specialized version of it and when an abstract class is used as a starting point for different implementations. Would it be better if we had two different terms for these concepts instead of using the same term?
4. How might you use commonality/variability analysis to help you think about ways to modify a system?
5. It is important to explore for variations early and often.
  • Do you believe this? Why or why not?
  • How does it help to avoid pitfalls?
6. Commonality/variability analysis is an important primary tool for identifying objects, better than "looking for the nouns." Do you agree? Why or why not?
7. This chapter tried to present a new perspective on objects? Did it succeed? Why or why not?


Chapter 9: The Strategy Pattern

Observations

1. What are some alternatives for handling new requirements?
Cut and paste
Switches or ifs on a variable specifying the case we have Using function pointers or delegates (a different one representing each case) Inheritance (make a derived class that does it the new way) Design patterns
2. What are the three fundamental principles proposed by the Gang of Four that guide how to anticipate change?
"Program to an interface, not an implementation." 1
"Favor object aggregation over class inheritance." 2 "Consider what should be variable in your design.
3. What is the intent of the Strategy pattern?
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it
4. What are the consequences of the Strategy pattern?
The Strategy pattern defines a family of algorithms.
Switches and/or conditionals can be eliminated. You must invoke all algorithms in the same way (they must all have the same interface).

Interpretations

1. The Gang of Four suggests "considering what should be variable in your design." How is this different from focusing on the cause of redesign?
The focus is on seeing where change might occur and then encapsulating it so that your system will not be affected by change when it occurs. It assumes you will not be able to anticipate what will change.
2. What is wrong with copy-and-paste?
duplications of code result in higher maintenance costs
3. What is "switch creep"?
The flow of the switches themselves becomes confusing. Hard to read. Hard to decipher. When a new case comes in, the programmer must find every place it can be involved (often finding all but one of them). I like to call this "switch creep".
4. What are the advantages of the design patterns approach to handing variation?
Improves cohesion
Aids flexibility Makes it easier to shift responsibility Aids understandability
5. Why is the object-aggregation approach to inheritance superior to direct class inheritance for handling variation?
But this simplifies the bigger, more complicated program. Second, by doing this, I have made inheritance better. When I need to use inheritance, there is now only one piece of functionality changing within any one class. The bottomline is, the approach espoused by patterns will scale while the original use of inheritance will not.

Opinions and Applications

1. Have you ever been in a situation where you did not feel you could afford to anticipate change? What drove you that way? What was the result?
2. Should you ever use switch statements? Why or why not?


Chapter 10: The Bridge Pattern

Observations

1. Define decouple and abstraction.
Decouple means to separate or detach one thing from another. In our context, it means to have one thing behave independently from another (or at least to state explicitly what that relationship is)
Abstraction means to generalize or conceptualize: to step back from the more concrete to the more conceptual or abstract.
2. How is implementation defined in the context of the Bridge pattern?
Implementation refers to the objects that the abstract class and its derivations use to put themselves into operation or into service.
3. What are the basic elements of a sequence diagram?
The basic elements are:
  • Boxes. These are shown at the  and represent the objects that are interacting.
  • Name in the form objectname:classname. The object name is optional.
  • Dashed vertical lines, also known as swim lanes, one for each object, to indicate time.
  • Arrows, may be horizontal or vertical, showing the interaction between objects. Each arrow is labeled to describe the interaction
  • Notes. This is optional.
4. What is Alexander's view of how to use patterns? Does he advocate starting with the solution first or the problem to be solved first?
Alexander says that a pattern describes a problem which occurs over and over again in the environment and then describes the core of the solution to that problem. This means that it is most important to understand the problem first and then tackle the solution. It is a mistake to try finding the solution first.
5. What does commonality analysis seek to identify? What does variability analysis seek to identify?
Commonality analysis focuses on finding structures that will not change over time while variability analysis looks for structures that are likely to change.
6. What is the basic problem being solved by the Bridge pattern?
The derivations of an abstract class must use multiple implementations without causing an explosion in the number of classes
7. Define the "one rule, one place" strategy.
"one rule, one place" says you should implement a rule in only one place. (p. 144). Note that this results in a greater number of smaller methods.
8. What are the consequences of the Bridge pattern?
Decoupling of the implementations from the objects that use them increases extensibility. Client objects are freed from being aware of implementation issues.  

Interpretations

1. The Gang of Four says that the intent of the Bridge pattern is to "decouple an abstraction from its implementation so that the two can vary independently." What does this mean? Give an example.
What it means is that you can have an abstraction that is independent of its implementations. (p. 150) An example is a shape object that is responsible for knowing shapes and a Drawing class that is responsible implementing drawing routines. Individual shapes don't have to know how to do drawings
2. Why can tight coupling lead to an explosion in the number of classes?
Tight coupling means that as you get more variations in implementation, each class has to be responsible for its own implementation.

Opinions and Applications

1. "Look at objects in terms of their responsibilities rather than their behaviors." How does this affect your view of the use of inheritance in an object-oriented system?
2. Why do you think the Gang of Four call this pattern "Bridge"? Is it an appropriate name for what it is doing? Why or why not?


Chapter 11: The Abstract Factory Pattern

Observations

1. While using "switches" can be a reasonable solution to a problem that requires choosing among alternatives, it caused problems for the driver problem discussed in this chapter. What were these problems? What might a switch indicate the need for? The rules for determining which driver to use are intermixed with the actual use of the drivers. This creates both tight coupling and strong cohesion.
Switches may indicate a need for abstraction
2. Why is this pattern called "Abstract Factory"?
At first glance, you might be tempted to conclude it is because the factory is implemented as an abstract class with a derivation for each case. But that is not the case. This pattern is called the "Abstract Factory" because the things it is intended to build are themselves defined by abstractions. How you choose to implement the factory variations is not specific to the pattern.
3. What are the three key strategies in the Abstract Factory?
Find what varies and encapsulate it
Favor aggregation over inheritance
Design to interfaces, not to implementations
4. In this pattern, there are two kinds of factories. What does the "Abstract Factory" class do? What do the "concrete factory" classes do?
The "Abstract Factory" class specifies which objects can be instantiated by defining a method for each type of object.
The "concrete factory" classes specify which objects are to be instantiated.
5. What are the consequences of the Abstract Factory pattern?
The Abstract Factory isolates the rules about which objects to use from the logic about how to use these objects.

Interpretations

1. The Gang of Four says that the intent of the Abstract Factory pattern is to "provide an interface for creating families of related or dependent objects without specifying their concrete classes." What does this mean? Give an example.
It means that I need to coordinate the instantiation of several objects, a family of objects. However, I want to insulate my system from having to know specifics of the particular concrete object being instantiated. That is, the selection of which particular concrete instance to use might depend upon another factor. An example would be a system that wants to manage records in a database but be insulated from the specifics of which DBMS is being used.

Opinions and Applications

1. Why do you think the Gang of Four call this pattern "Abstract Factory"? Is it an appropriate name for what it is doing? Why or why not?
2. How do you know when to use the Abstract Factory pattern?

Chapter 12: How Do Experts Design?

Observations

1. Alexander uses the term, "alive" to characterize good designs. What terms do I suggest using when it comes to software?
"When you read ‘alive', think ‘robust' and ‘flexible' systems
2. Good design requires keeping what in mind?
Keeping the big picture in mind. Being able to consider the forest first and then the trees. (p. 189)
3. Alexander suggests that the best approach to design involves"complexification." What does this mean?
Complexification is the approach to design to starts by looking at the problem in its simplest terms and then adds additional features (distinctions), making the deisgn more complex as we go because we are adding information
4. To Alexander, what relationships does a pattern define?
A pattern defines relationships between the entities in his problem domain (p. 191, 192) This is why define a pattern as a solution to a problem in a context. The entities describe the context in which the pattern exists.
5. What are Alexander's five steps to design?
Identify patterns that are present in your problem.
Start with context patterns (those that create context for other patterns)
Work inward from the context
Refine the design
Implement

Interpretations

1. I quote Alexander, "But it is impossible to form anything which has the character of nature by adding preformed parts." What does Alexander mean by this?
Alexander believes that designs that have the "character of nature" are those that humans would judge has being superior in design. They are "alive" and feel right. He believes that buildings (or in our case, software) that is built simply by assembling stock parts will not feel "alive". They will have all the charm of 60s style block houses: functional but dead. In software terms, it works the same way: cobbling together objects does not create solutions that are easily maintained: robust and flexible.

Opinions and Applications

1. Sometimes, the case that is made for object-oriented programming is that it gives you small, reusable components that you can assemble to create a program. Does this align with Alexander or contradict him? Or is Alexander speaking at a different level? Why?
2. Have you ever seen a courtyard or entryway in a house or building that has felt particularly "dead" or uninviting? As you look at Alexander's description of the Courtyard pattern, what entities did your courtyard fail to resolve or involve?
3. Think of one software project in which you think Alexander's approach would apply or an approach in which it would not apply. What are the issues? Keep this case in mind as you read the rest of the book.


Chapter 13: Solving The CAD/CAM Problem with Patterns

Observations

1. What are the three steps to software design with patterns that I use?
Find the patterns in the problem domain
For the set of patterns to be analyzed, pick the pattern that provides the most context and apply it to the conceptual design. Identify additional patterns that are now suggested. Repeat.
Add detail to the conceptual design. Expand the method and class definitions.
2. Define "context."
One definition is "the interrelated conditions in which something exists or occurs. An environment or a setting." (p. 201)
3. What do I mean by "seniormost" pattern?
The seniormost pattern is the pattern that creates the context for the other patterns. When it comes to applying patterns to a design, we want start with the "seniormost" patterns first and then work down (p. 203)
4. When comparing two patterns, I suggest two rules for discerning which pattern might be seniormost. What are these rules? Does one pattern define how the other pattern behaves?
Are the two patterns interrelated? Mutually dependent?
5. Define "canonical form" of a pattern. When is it used?
The canonical form of a pattern is it standardized, simplified representation. This is generally what is shown in the Gang of Four book and is shown in each of the pattern descriptions in Design Patterns Explained. I suggest starting with the canonical form and then mapping classes and elements of the problem into it.

Interpretations

1. Do I believe that your entire problem can always be defined in terms of patterns? If not, what else is needed?
The answer is "not always." Generally, patterns give you a way to get started with understanding the problem. However, analysis remains a human activity! (which is good because we still have jobs!). it is usually the case that the analyst ends up having to identify relationships amongst concepts in the problem domain. One good approach to this is Commonality / Variability analysis, which has been discussed before.
2. In the CAD/CAM problem, I reject the Abstract Factory as the "seniormost" pattern. What reasons do they give?
The Abstract Factory requires knowing what classes will be defined. These are defined by other patterns. Therefore, Abstract Factory depends upon other patterns; they create the context for the Abstract Factory. Therefore, it is not seniormost
3. In the CAD/CAM problem, what reason(s) do I give for labeling Bridge as senior to Adapter?
Clearly, there is a relationship between Bridge and Adapter. But Adapter's interfaces cannot be determined without Bridge. Without the Bridge, Adapter's interfaces simply don't exist. Since Adapter depends upon Bridge and not vice-versa, Bridge is more senior (p. 204)

Opinions and Applications

1. Once all of the patterns are applied, there are still likely to be more details. I assert that Alexander's general rules (design by starting with the context) still apply. Does this ever s? Is there ever a time when you should go ahead and dive into the details? Isn't that what "rapid prototyping" suggests? How can you avoid this temptation that all programmers have? Should you?

Chapter 14: The Principles and Strategies of Design Patterns

Observations

1. When it comes to choosing how to implement a design, what question do I suggest asking?
Rather than ask, "Which implementation is better?" ask, for each alternative, "Under what circumstances would this alternative be better than the other alternative" and then "Which of these circumstances to I have in my problem domain?"
2. What are the five errors of using design patterns?
Superficiality, Bias, Selection, Misdiagnosis, Fit

Interpretations

1. The "open-closed" principle says, "modules, methods, and classes should be open for extension while closed for modification." What does this mean?
Bertrand Meyer puts this forward as a way to minimize risk when changing systems. Basically, it means that we want to be able to extend the capabilities of our systems without substantially changing it. Design in such a way that the software can absorb new variations without having to introduce new fundamental structure (p. 218).
2. In what way does the Bridge pattern illustrate the open-closed principle?
Bridge allows us to add new implementations without changing any existing classes

Opinions and Applications

1. I suggest that even though a design pattern might give you insights into what could happen, you do not have to build your code to handle those possibilities. How do you decide which possibilities to handle now and which to be ready for in the future?
2. Give a concrete example of the danger of misapplying a design pattern, based upon your current work.

Chapter 15: Commonality and Variability Analysis (CVA)

Observations

1. I suggest two approaches to identifying commonalities and variabilities. What are they?
Pick any two items in the problem domain and ask, "is one of these a variation of the other" and "are both of these a variation of something else".
Look at the problem and identify the major concepts.

Interpretations

1. CVA says you should have only one issue per commonality. Why is this important?
Having two issues per commonality leads to confusion in the relationship amongst the concepts.
When the connection is clear, then there is clear and thus strong cohesion amongst concepts.
2. How do CVA and design patterns complement each other?
CVA helps to identify what the essential concepts are. Design patterns do not necessarily lead to that.
Design patterns tell you what to do with those concepts, how to relate them based upon good designs from the past. CVA does not speak about best-practices, leaving that to the designer's imagination.

Opinions and Applications

1. I state that experienced developers - even more than inexperienced ones - often focus on entity relationships too early, before they are clear what the right entities are. Is that your experience? Give an example to confirm or refute this statement.
2. Relate the approach to design - starting with CVA - with Alexander's approach.

Chapter 16: The Analysis Matrix

Observations

1. What goes in the far left column of the Analysis Matrix?
The essential concept represented by a function.
2. What do the rows of the Analysis matrix represent?
Each row represents specific, concrete implementations of the generalized concept described in the row.
3. What do the columns of the Analysis matrix represent?
Each column represents the specific implementations for each case
4. Which patterns described in this book might be present in an Analysis Matrix?
In general, any pattern that uses polymorphism could be present in an Analysis Matrix. In this book, that involves Bridge, Decorator, Template, and Observer.

Interpretations

1. At what level of perspective does the Analysis Matrix operate?
The Analysis Matrix is focused on variations in concepts. It is used at the Conceptual Level
2. In what way is the Analysis Matrix similar to Commonality/Variability Analysis?
The Analysis Matrix is focused on variations in concepts. It starts by understanding the concept that a function represents and putting a label onto it. The Analysis Matrix works with these labels as abstractions for the function. CVA also works by abstracting variations and labeling them.

Opinions and Applications

1. Can patterns help handle variation more efficiently?
2. Do you agree with I' observations about users (p. 296)? Can you give examples from your own experience?
3. Do you believe that the Analysis Matrix is generally useful in most problem domains?

Chapter 17: The Decorator Pattern

Observations

1. What does each Decorator object wrap?
Decorators wrap their trailing objects. Each Decorator object wraps its new function around its trailing object.
2. What are two classic examples of decorators?
Heading and footers
Stream I/O

Interpretations

1. How does the Decorator pattern help to decompose the problem?
The Decorator pattern helps to decompose the problem into two parts: How to implement the objects that give the new functionality; and how to organize the objects for each special case
2. In discussing the essence of the Decorator, I say that "the structure is not the pattern." What does this mean? Why is this important?
The Decorator pattern comes into play when there are a variety of optional functions that can precede or follow another function that is always executed.
Implementing the pattern by rote can lead to bad design. Instead, you need to think about the forces at work in the pattern and then think about ways to implement the intent of the pattern. Patterns are not recipes.

Opinions and Applications

1. Why do you think the Gang of Four call this pattern "Decorator"? Is it an appropriate name for what it is doing? Why or why not?
2. Sometimes, people think of patterns as recipes. What is wrong with this?

Chapter 18: The Observer Pattern

Observations

1. According to the Gang of Four, what are structural patterns responsible for?
Structural patterns are used for tying together existing functionality.
2. What are the three classifications of patterns, according to the Gang of Four? What is the fourth classification that I suggest?
The GoF specified three types: Structural, Behavioral, and Creational. I suggest "decoupling" as a fourth type.
3. What is the one true thing about requirements?
Requirements always change! Plan for it.
4. What is the intent of the Observer pattern?
The Gang of Four says that the intent of the Observer pattern is to "define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Interpretations

1. Why are the Bridge and Decorator patterns more correctly classified as structural rather than behavioral patterns?
They both are tying together functionality, which is what structural patterns do. In the Bridge pattern, we typically start with abstractions and implementations and then bind them together with the bridge. In the Decorator pattern, we have an original functional class, and want to decorate it with additional functions.
2. One example of the Observer pattern from outside of software is a radio station: It broadcasts its signal; anyone who is interested can tune in and listen when they want to. What is another example from "real-life"?
Newspaper publishing could be another example
3. Under what conditions should an Observer pattern not be used? When the dependencies are fixed (or virtually so), adding an Observer pattern probably just adds complexity.

Opinions and Applications

1. I put forward the idea of a "fourth category" of patterns, that somewhat includes patterns from other categories. Is this a good idea? Why or why not?

Chapter 19: The Template Method Pattern

Observations

1. The Template Method pattern makes the method call in a special way. What is that?
The method itself is general. It makes the method call via a reference pointing to one of the derived classes to handle the special details.

Interpretations

1. According to the Gang of Four, the intent of the Template Method pattern is to "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine the steps in an algorithm without changing the algorithm's structure" What does this mean?
It helps us to generalize a common process - at an abstract level - from a set of different procedures. It helps to identify the common ground between the set of different procedures while encapsulating the differences in derived classes
2. The Gang of Four calls this a "Template Method". Why do they do this?
Because it provides a boilerplate (or a "template") that specifies the generic actions and derived class implements the specific steps required for the actions to take
3. What is the difference between the Strategy pattern (chapter 9) and the Template Method pattern?
The Template Method pattern is applicable when there are different, but conceptually similar processes.
The Strategy pattern controls a family of algorithms. They do not have to be conceptually similar. You choose the algorithm to employ just in time.

Chapter 20: Lessons from Design Patterns: Factories

Observations

1. How do I define a factory?
A factory is a method, an object, or anything else that is used to instantiate other objects.
2. Name one factory pattern that was shown in a previous chapter. Name the factory patterns mentioned in this chapter
The Abstract Factory was shown in chapter 11. In this chapter, the factories mentioned are Builder, Factory Method, Prototype, and Singleton
3. When it comes to managing object creation, what is a good, universal rule to use?
An object should either make and/or manage other objects, or it should use other objects but it should never do both

Interpretations

1. I state that developers who are new to object-oriented programming often lump the management of object creation in with object instantiation. What is wrong with this?
It can lead to decreased cohesion because an object depends on or more other objects to ensure work is done before it can successfully continue.
2. I suggest that factories increase cohesion. What is their rationale for saying so?
Factories help to keep together both the functionality and the rules that determine which objects should be built and/or managed under different circumstances.
3. I suggest that factories also help in testing. In what ways is this true?
The "using objects" should behave in exactly the same way with any set of derivatives present. I should not need to test every possible combination, because I can test each piece individually. No matter how I combine them, the system will work in the same manner.

Opinions and Applications

1. I suggest that factories are useful for more than simply deciding which object to create or use. They also help with encapsulating design by solving a problem created by patterns? Evaluate this argument.

Chapter 21: The Singleton Pattern and the Double-Checked Locking Pattern

Observations

1. What type of pattern is the Singleton? What general category of pattern does it belong to?
It is a type of Factory pattern
2. What is the intent of the Singleton pattern?
Ensure a class only has one instance, and provide a global point of access to it
3. How many objects is the Singleton responsible for creating?
one
4. The Singleton uses a special method to instantiate objects. What is special about this method?
When this method is called, it checks to see if the object has already been instantiated. If it has, the method simply returns a reference to the object. If not, the method instantiates it and returns a reference to the new instance.
To ensure that this is the only way to instantiate an object of this type, I define the constructor of this class to be protected or private.
5. What do I say is the difference in when to use the Singleton and Double-Checked Locking patterns?
The distinction between the patterns is that the Singleton pattern is used in single-threaded applications while the Double-Checked Locking pattern is used in multithreaded applications. Double-Checked must focus on synchronization in creations in case two objects try to create an object at exactly the same moment. This avoids unnecessary locking. It does this by wrapping the call to new with another conditional test. Singleton does not have to worry about this.

Interpretations

1. I state that they would rather have the objects be responsible for handling their own single instantiation than to do it globally for the objects. Why is this better?
It is encapsulation of behavior: it helps objects be less dependent on some other object to do something that will directly impact what that object can do.
It also frees other objects from worrying whether the object already exists. They can assume it does (or will) and that there is only one of that object to reference. They don't have to worry about getting the right one. As systems grow in size and complexity, trying to manage all of this quickly can get out of hand. But you have to be careful not to create global variables.

Opinions and Applications

2. Why do you think the Gang of Four call this pattern "Singleton"? Is it an appropriate name for what it is doing? Why or why not?
3. The authors state, "When it was discovered that the Double Checked Locking pattern as initially described did not work in Java, many people saw it as evidence that patterns were over-hyped. I drew exactly the opposite conclusion." Do you agree with their logic? Why or why not?

Chapter 22: The Object Pool Pattern

Observations

1. What three general strategies do I suggest you follow?
Look for ways to insulate yourself from the impacts of changes to your system.
Focus on the hard things first
Trust your instincts.
2. What two patterns does the Object Pool pattern incorporate?
The Singleton pattern ensures that only one
The Factory pattern manages the creation and logic
3. What is the intent of the Object Pool pattern? Manages the reuse of objects when a type of object is expensive to create or only a limited number of objects can be created

Interpretations

1. What do the XP community mean by YAGNI?
You Aint Gonna Need It
It reflects the idea that you should build what you need now while ignoring the rest. You should work on the most important things early, when solving them can make the greatest impact. It also means you avoid working on things are at a minimum distracting, and typically never used (and therefore building is a waste of resources).

Opinions and Applications

1. Reading widely is an important discipline. You never know when you will find something you can use. One example is the example they found from Steve Maguire's book, Writing Solid Code. Give at least one example from your own experienced where this has been true for you.

Chapter 23: The Factory Method Pattern Observations

1. What are factories responsible for?
Factories are responsible for creating objects and ensuring objects are available to be used.
2. What is the essential reason to use a Factory Method?
You want to defer the decision for instantiating a derivation of another class to a derived class
3. The Factory Method pattern has been implemented in all of the major object-oriented languages. How has it been used in Java, C#, and C++?
In Java, the iterator method on collections is a Factory Method.
In C#, the GetEnumerator is a Factory method on the differen C# collections where it is present. In C++, the methods used include begin() and end().

Interpretations

1. Why is this pattern called a "factory method?"
It uses a method to handle the factory
2. How does the Factory Method pattern fit in with other factories?
The Factory Method allows these other patterns to defer instantiation to subclasses. One uses the Factory Method to defer responsibility to subclass objects. The Abstract Factory can use a family of Factory Methods, one for each different family of objects involved. The Template Method can use a method to handle the instantiation; giving responsibility to that method is the factory.
3. The Gang of Four says that the intent of the Factory Method is to "define an interface for creating an object, but let subclasses decide which class to instantiate." Why is this important?
It is not always desirable for a class to have to know how to instantiate derived classes

Opinions and Applications

4. How should you go about deciding whether a method should be public, private, or protected?
5. This is a small chapter but this is not a small pattern. Think of one example where this pattern could be used.

Chapter 24: Summary of Factories

No Review Questions in this summary chapter. 

Chapter 25: Design Patterns Reviewed From Our New Perspective of Object-Oriented Principles

Observations

1. Several of the patterns have the characteristic of shielding implementations from what? What is this called? Give examples.
They shield implementation details from the Client object. This is one type of encapsulation. Bridge is one such pattern: It hides from the Client how the Abstraction is implemented.
2. What is one example of a pattern helping to think about decomposing responsibilities?
The Decorator pattern gives a way of decomposing responsibilities into the main set that are always used (ConcreteComponent) and variations that are options (decorators).
3. As you learn patterns, what five forces and concepts do I urge you to look for?
The five forces to look for are:
What implementations does this pattern hide?
What commonalities are present in this pattern?
What are the responsibilities of the objects in this pattern?
What are the relationships between these objects?
How may the pattern itself be a microcosmic example of designing by context?

Interpretations

1. What is the value of hiding implementations?
The patterns allow for adding new implementations by hiding details of current implementations. This reflects the open-closed principle, making systems easier to endure over time

Advance Java Blogging

Java New Articles

Javas Latest News

Java Web Services and XML

Ajax Latest News

Mac OS Java Features

Advance Spotlights

Patterns Features