Monday, March 24, 2008

Working With Design Patterns: Facade

Source

By Jeff Langr

Go to page: 1 2 Next

Introduction

A software system is never a perfect thing. Developers almost always must balance system quality with demand. The software must be shipped; therefore, developers must proceed with what they think is the most appropriate design.

Developers also know much more about the actual use of the software once it ships. This effect is highly evident when they build a system that requires publicly exposed programmatic interfaces, or APIs (application programming interfaces). The primary goal of an API is to allow multiple parties to re-use the software product.

If only one party intends on ever using software modules, developers don't talk about a "public API" so much, and they don't spend a lot of time ensuring that it's as well-defined and forward thinking as possible. Things are still within their control, and thus easy to change. But, once an API is out of the bag—once other developers have begun to consume it—developers lose a lot of the ability to control it.

Case in point: the unfortunate design of the Java date and calendar classes. The getter methods (getMonth, getYear, and so forth) on the java.util.Date class, introduced in Java 1.0, have been marked as deprecated since version 1.1. I recall some mumbling from Sun about an internationalized date solution, and how the Date class wasn't it.

Sun couldn't change the Date class without breaking many applications, as it was already in heavy use. So, it introduced the heavyweight Calendar class to help resolve the problem, adding support for international applications. The resulting design is difficult at best. I've encountered countless shops that created a simpler solution by building a wrapper classes around Java's date-related library classes.

The wrapper classes these teams built are facades (also typed as façades, but the former is easier to type on a US keyboard). A facade, in software design terms, is an interface intended to simplify a more complex API. Introducing a facade simplifies conceptual understanding within a system, and thus helps keep maintenance costs low. It also allows increased flexibility by encapsulating the specific APIs that hide behind the facade.

The ProcessBuilder API, introduced in Java 2 SE 1.5, is another Sun solution that often promotes the introduction of a facade. (The ProcessBuilder class provides capabilities similar to the Runtime class that's always been a part of the Java class libraries.) Obtaining output from a command line application that writes to the console requires creating a separate thread, and two threads to obtain stderr output in addition to stdout.

As a programmer who simply wants to execute a command and grab its output, I find the API for ProcessBuilder too involved. Still, the design choice for ProcessBuilder is appropriate, because it supports ultimate flexibility. For example, I might want to do something special with the stdout thread for a command that produces voluminous output. But, most of the time, I want to bury all of that thread complexity behind a facade.

The Command class (see Listing 1) is a facade that simplifies interaction with a ProcessBuilder object and the Process objects it creates.

Listing 1: Command.

import java.io.*;

public class Command {
private String[] command;
private Process process;
private StringBuilder output = new StringBuilder();
private StringBuilder errorOutput = new StringBuilder();

public Command(String... command) {
this.command = command;
}

public void execute() throws Exception {
ProcessBuilder processBuilder =
new ProcessBuilder(command);
process = processBuilder.start();
collectOutput();
collectErrorOutput();
process.waitFor();
}

private void collectErrorOutput() {
Runnable runnable = new Runnable() {
public void run() {
try {
collectOutput(process.getErrorStream(),
errorOutput);
}
catch (IOException e) {
errorOutput.append(e.getMessage());
}
}
};
new Thread(runnable).start();
}

private void collectOutput() {
Runnable runnable = new Runnable() {
public void run() {
try {
collectOutput(process.getInputStream(), output);
}
catch (IOException e) {
output.append(e.getMessage());
}
}
};
new Thread(runnable).start();
}

private void collectOutput(InputStream inputStream,
StringBuilder collector) throws IOException {
BufferedReader reader = null;
try {
reader =
new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
collector.append(line);
}
finally {
reader.close();
}
}

public String getOutput() throws IOException {
return output.toString();
}

public String getErrorOutput() throws IOException {
return errorOutput.toString();
}
}

The ProcessBuilder-related code in the Command class isn't terribly complex. Still, to execute a single command and capture output, it's a bit more effort than I want to deal with. Using the Command class is much simpler:

   Command command = new Command("dir", "/");
command.execute();
System.out.println(command.getOutput());
System.out.println(command.getErrorOutput());
Note: The constructor for Command takes each command-line parameter as a separate string in a string array.)

Facades go to the core of the notion of information hiding in OO design. The ProcessBuilder and Process classes represent implementation details. The Command class interface reduces these details to a small set of abstractions: execute a command and get its output.

Testing and Facades

A test-driven approach will likely result in the creation of facades. Test-driven development (TDD) involves designing a system by writing tests to demonstrate exercising a class through its public interface. A developer looking to succinctly express a concept or policy in a unit test may find that it needs translation—a facade—to map to an underlying API.

The tests for the Command class appear in Listing 2. An interesting aspect of the CommandTest class is that it uses itself as the command-line application to test. This "self shunt" eliminates dependency on an external application or OS.

Listing 2: CommandTest.

import static org.junit.Assert.*;

import org.junit.*;

public class CommandTest {
enum TestName {
testSingleLine("a short line of text"),
testMultipleLines("line 1\\nline2\\n"),
testLotsOfLines("") {
String outputText() {
final int lots = 1024;
StringBuilder lotsBuffer = new StringBuilder();
for (int i = 0; i < lots; i++)
lotsBuffer.append("" + i);
return lotsBuffer.toString();
}
};

private String outputText;

TestName(String outputText) {
this.outputText = outputText;
}

String outputText() {
return outputText;
}
}

private Command command;

public static void main(String[] args) {
TestName testName = TestName.valueOf(args[0]);
System.out.println(output(testName));
System.err.println(syserrOutput(testName));
}

private static String syserrOutput(TestName testName) {
return testName.outputText.toUpperCase();
}

private static String output(TestName testName) {
return testName.outputText();
}

@Test
public void successfullyExecutesSingleLine()
throws Exception {
executeCommand(TestName.testSingleLine);
verifyOutput(TestName.testSingleLine);
}

@Test
public void successfullyExecutesMultipleLines()
throws Exception {
executeCommand(TestName.testMultipleLines);
verifyOutput(TestName.testMultipleLines);
}

@Test
public void successfullyExecutesLotsOfLines()
throws Exception {
executeCommand(TestName.testLotsOfLines);
verifyOutput(TestName.testLotsOfLines);
}

private void executeCommand(TestName testName)
throws Exception {
command = new Command(commandString(testName));
command.execute();
}

private void verifyOutput(TestName testName)
throws Exception {
assertEquals(output(testName), command.getOutput());
assertEquals(syserrOutput(testName),
command.getErrorOutput());
}

private String[] commandString(TestName testName) {
return new String[] { "java", "-classpath",
"\"" + System.getProperty("java.class.path")
+ "\"", "CommandTest",
testName.toString() };
}
}

Figure 1: Facade

About the Author

Jeff Langr is a veteran software developer with over a quarter century of professional software development experience. He's written two books, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. Jeff is contributing a chapter to Uncle Bob Martin's upcoming book, Clean Code. Jeff has written over 75 articles on software development, with over thirty appearing at Developer.com. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft dot com.

1 comments:

Jack said...

Thanks for the code.Nowadays, i am facing a problem of this kind.I will certainly use this code and hope it works absolutely fine with me.
PDF signature