2010年9月25日星期六

The choice between Service Locator

The CIA program's original scope was to hide and interrogate the two dozen or so al Qaeda leaders believed to be directly responsible for the Sept. 11 attacks, or who posed an imminent threat, or had knowledge of the larger al Qaeda network. But as the volume of leads pouring into the CTC from abroad increased, and the capacity of its paramilitary group to seize suspects grew, the CIA began apprehending more people whose intelligence value and links to terrorism were less certain, according to four current and former officials.

The original standard for consigning suspects to the invisible universe was lowered or ignored, they said. "They've got many, many more who don't reach any threshold," one intelligence official said.

Several former and current intelligence officials, as well as several other U.S. government officials with knowledge of the program, express frustration that the White House and the leaders of the intelligence community have not made it a priority to decide whether the secret internment program should continue in its current form, or be replaced by some other approach.

Meanwhile, the debate over the wisdom of the program continues among CIA officers, some of whom also argue that the secrecy surrounding the program is not sustainable.

One year, Huffy had committed to supply Wal-Mart with an entry-level, thin-margin bike--as many as Wal-Mart needed. Sales of the low-end bike took off. "I woke up May 1"--the heart of the bike production cycle for the summer--"and I needed 900,000 bikes," he says. "My factories could only run 450,000." As it happened, that same year, Huffy's fancier, more-profitable bikes were doing well, too, at Wal-Mart and other places. Huffy found itself in a bind.

With other retailers, perhaps, Mariotti might have sat down, renegotiated, tried to talk his way out of the corner. Not with Wal-Mart. "I made the deal up front with them," he says. "I knew how high was up. I was duty-bound to supply my customer." So he did something extraordinary. To free up production in order to make Wal-Mart's cheap bikes, he gave the designs for four of his higher-end, higher-margin products to rival manufacturers. "I conceded business to my competitors, because I just ran out of capacity," he says. Huffy didn't just relinquish profits to keep Wal-Mart happy--it handed those profits to its competition. "Wal-Mart didn't tell me what to do," Mariotti says. "They didn't have to." The retailer, he adds, "is tough as nails. But they give you a chance to compete. If you can't compete, that's your problem."

The current rush of lightweight containers all have a common underlying pattern to how they do service assembly - the dependency injector pattern. Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.

If you use Dependency Injection there are a number of styles to choose between. I would suggest you follow constructor injection unless you run into one of the specific problems with that approach, in which case switch to setter injection. If you are choosing to build or obtain a container, look for one that supports both constructor and setter injection.

The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application.

Mariotti describes one episode from

Separating Configuration from Use
The important issue in all of this is to ensure that the configuration of services is separated from their use. Indeed this is a fundamental design principle that sits with the separation of interfaces from implementation. It's something we see within an object-oriented program when conditional logic decides which class to instantiate, and then future evaluations of that conditional are done through polymorphism rather than through duplicated conditional code.

What does the squeeze look like at Wal-Mart? It is usually thoroughly rational, sometimes devastatingly so.

John Mariotti is a veteran of the consumer-products world--he spent nine years as president of Huffy Bicycle Co., a division of Huffy Corp., and is now chairman of World Kitchen, the company that sells Oxo, Revere, Corning, and Ekco brand housewares.

He could not be clearer on his opinion about Wal-Mart: It's a great company, and a great company to do business with. "Wal-Mart has done more good for America by several thousand orders of magnitude than they've done bad," Mariotti says. "They have raised the bar, and raised the bar for everybody."

Mariotti describes one episode from Huffy's relationship with Wal-Mart. It's a tale he tells to illustrate an admiring point he makes about the retailer. "They demand you do what you say you are going to do." But it's also a classic example of the damned-if-you-do, damned-if-you-don't Wal-Mart squeeze. When Mariotti was at Huffy throughout the 1980s, the company sold a range of bikes to Wal-Mart, 20 or so models, in a spread of prices and profitability. It was a leading manufacturer of bikes in the United States, in places like Ponca City, Oklahoma; Celina, Ohio; and Farmington, Missouri.


If this separation is useful within a single code base, it's especially vital when you're using foreign elements such as components and services. The first question is whether you wish to defer the choice of implementation class to particular deployments. If so you need to use some implementation of plugin. Once you are using plugins then it's essential that the assembly of the plugins is done separately from the rest of the application so that you can substitute different configurations easily for different deployments. How you achieve this is secondary. This configuration mechanism can either configure a service locator, or use injection to configure objects directly.

In late 2002 or early 2003

Still without a long-term solution, the CIA began sending suspects it captured in the first month or so after Sept. 11 to its longtime partners, the intelligence services of Egypt and Jordan.

A month later, the CIA found itself with hundreds of prisoners who were captured on battlefields in Afghanistan. A short-term solution was improvised. The agency shoved its highest-value prisoners into metal shipping containers set up on a corner of the Bagram Air Base, which was surrounded with a triple perimeter of concertina-wire fencing. Most prisoners were left in the hands of the Northern Alliance, U.S.-supported opposition forces who were fighting the Taliban.

"I remember asking: What are we going to do with these people?" said a senior CIA officer. "I kept saying, where's the help? We've got to bring in some help. We can't be jailers -- our job is to find Osama."

Then came grisly reports, in the winter of 2001, that prisoners kept by allied Afghan generals in cargo containers had died of asphyxiation. The CIA asked Congress for, and was quickly granted, tens of millions of dollars to establish a larger, long-term system in Afghanistan, parts of which would be used for CIA prisoners.

The largest CIA prison in Afghanistan was code-named the Salt Pit. It was also the CIA's substation and was first housed in an old brick factory outside Kabul. In November 2002, an inexperienced CIA case officer allegedly ordered guards to strip naked an uncooperative young detainee, chain him to the concrete floor and leave him there overnight without blankets. He froze to death, according to four U.S. government officials. The CIA officer has not been charged in the death.

The Salt Pit was protected by surveillance cameras and tough Afghan guards, but the road leading to it was not safe to travel and the jail was eventually moved inside Bagram Air Base. It has since been relocated off the base.

By mid-2002, the CIA had worked out secret black-site deals with two countries, including Thailand and one Eastern European nation, current and former officials said. An estimated $100 million was tucked inside the classified annex of the first supplemental Afghanistan appropriation.

Then the CIA captured its first big detainee, in March 28, 2002. Pakistani forces took Abu Zubaida, al Qaeda's operations chief, into custody and the CIA whisked him to the new black site in Thailand, which included underground interrogation cells, said several former and current intelligence officials. Six months later, Sept. 11 planner Ramzi Binalshibh was also captured in Pakistan and flown to Thailand.

But after published reports revealed the existence of the site in June 2003, Thai officials insisted the CIA shut it down, and the two terrorists were moved elsewhere, according to former government officials involved in the matter. Work between the two countries on counterterrorism has been lukewarm ever since.

In late 2002 or early 2003, the CIA brokered deals with other countries to establish black-site prisons. One of these sites -- which sources said they believed to be the CIA's biggest facility now -- became particularly important when the agency realized it would have a growing number of prisoners and a shrinking number of prisons.

Thailand was closed, and sometime in 2004 the CIA decided it had to give up its small site at Guantanamo Bay. The CIA had planned to convert that into a state-of-the-art facility, operated independently of the military. The CIA pulled out when U.S. courts began to exercise greater control over the military detainees, and agency officials feared judges would soon extend the same type of supervision over their detainees.

In hindsight, say some former and current intelligence officials, the CIA's problems were exacerbated by another decision made within the Counterterrorist Center at Langley.

One thing we're seeing in the Java world

The agency set up prisons under its covert action authority. Under U.S. law, only the president can authorize a covert action, by signing a document called a presidential finding. Findings must not break U.S. law and are reviewed and approved by CIA, Justice Department and White House legal advisers.

Six days after the Sept. 11 attacks, President Bush signed a sweeping finding that gave the CIA broad authorization to disrupt terrorist activity, including permission to kill, capture and detain members of al Qaeda anywhere in the world.


It could not be determined whether Bush approved a separate finding for the black-sites program, but the consensus among current and former intelligence and other government officials interviewed for this article is that he did not have to.

Rather, they believe that the CIA general counsel's office acted within the parameters of the Sept. 17 finding. The black-site program was approved by a small circle of White House and Justice Department lawyers and officials, according to several former and current U.S. government and intelligence officials.

A separate but often conflated issue is whether to use configuration files or code on an API to wire up services. For most applications that are likely to be deployed in many places, a separate configuration file usually makes most sense. Almost all the time this will be an XML file, and this makes sense. However there are cases where it's easier to use program code to do the assembly. One case is where you have a simple application that's not got a lot of deployment variation. In this case a bit of code can be clearer than a separate XML file.

A contrasting case is where the assembly is quite complex, involving conditional steps. Once you start getting close to programming language then XML starts breaking down and it's better to use a real language that has all the syntax to write a clear program. You then write a builder class that does the assembly. If you have distinct builder scenarios you can provide several builder classes and use a simple configuration file to select between them.

I often think that people are over-eager to define configuration files. Often a programming language makes a straightforward and powerful configuration mechanism. Modern languages can easily compile small assemblers that can be used to assemble plugins for larger systems. If compilation is a pain, then there are scripting languages that can work well also.

It's often said that configuration files shouldn't use a programing language because they need to be edited by non-programmers. But how often is this the case? Do people really expect non-programmers to alter the transaction isolation levels of a complex server-side application? Non-language configuration files work well only to the extent they are simple. If they become complex then it's time to think about using a proper programming language.

One thing we're seeing in the Java world at the moment is a cacophony of configuration files, where every component has its own configuration files which are different to everyone else's. If you use a dozen of these components, you can easily end up with a dozen configuration files to keep in sync.

My advice here is to always provide a way to do all configuration easily with a programmatic interface, and then treat a separate configuration file as an optional feature. You can easily build configuration file handling to use the programmatic interface. If you are writing a component you then leave it up to your user whether to use the programmatic interface, your configuration file format, or to write their own custom configuration file format and tie it into the programmatic interface



Among the first steps was to figure out where the CIA could secretly hold the captives. One early idea was to keep them on ships in international waters, but that was discarded for security and logistics reasons.

CIA officers also searched for a setting like Alcatraz Island. They considered the virtually unvisited islands in Lake Kariba in Zambia, which were edged with craggy cliffs and covered in woods. But poor sanitary conditions could easily lead to fatal diseases, they decided, and besides, they wondered, could the Zambians be trusted with such a secret?

If you have multiple ways to construct a valid object

If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. This is when Factory Methods come into play, these can use a combination of private constructors and setters to implement their work. The problem with classic Factory Methods for components assembly is that they are usually seen as static methods, and you can't have those on interfaces. You can make a factory class, but then that just becomes another service instance. A factory service is often a good tactic, but you still have to instantiate the factory using one of the techniques here.

Constructors also suffer if you have simple parameters such as strings. With setter injection you can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position, which is harder to follow.

If you have multiple constructors and inheritance, then things can get particularly awkward. In order to initialize everything you have to provide constructors to forward to each superclass constructor, while also adding you own arguments. This can lead to an even bigger explosion of constructors.

Despite the disadvantages my preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I've outlined above start to become a problem.

This issue has led to a lot of debate between the various teams who provide dependency injectors as part of their frameworks. However it seems that most people who build these frameworks have realized that it's important to support both mechanisms, even if there's a preference for one of them.

No one wants to end up in what is known among Wal-Mart vendors as the "penalty box"--punished, or even excluded from the store shelves, for saying something that makes Wal-Mart unhappy. (The penalty box is normally reserved for vendors who don't meet performance benchmarks, not for those who talk to the press.)

"You won't hear anything negative from most people," says Paul Kelly, founder of Silvermine Consulting Group, a company that helps businesses work more effectively with retailers. "It would be committing suicide. If Wal-Mart takes something the wrong way, it's like Saddam Hussein. You just don't want to piss them off."

As a result, this story was reported in an unusual way: by speaking with dozens of people who have spent years selling to Wal-Mart, or consulting to companies that sell to Wal-Mart, but who no longer work for companies that do business with Wal-Mart. Unless otherwise noted, the companies involved in the events they described refused even to confirm or deny the basics of the events.

To a person, all those interviewed credit Wal-Mart with a fundamental integrity in its dealings that's unusual in the world of consumer goods, retailing, and groceries. Wal-Mart does not cheat suppliers, it keeps its word, it pays its bills briskly. "They are tough people but very honest; they treat you honestly," says Peter Campanella, who ran the business that sold Corning kitchenware products, both at Corning and then at World Kitchen. "It was a joke to do business with most of their competitors. A fiasco."

But Wal-Mart also clearly does not hesitate to use its power, magnifying the Darwinian forces already at work in modern global capitalism.

Morocco, Egypt and Jordan have said that they do not

Morocco, Egypt and Jordan have said that they do not torture detainees, although years of State Department human rights reports accuse all three of chronic prisoner abuse.

Another advantage with constructor initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is important - if something shouldn't change then the lack of a setter communicates this very well. If you use setters for initialization, then this can become a pain. (Indeed in these situations I prefer to avoid the usual setting convention, I'd prefer a method like initFoo, to stress that it's something you should only do at birth.)

But with any situation there are exceptions. If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. It's true that a long constructor is often a sign of an over-busy object that should be split, but there are cases when that's what you need.


The top 30 al Qaeda prisoners exist in complete isolation from the outside world. Kept in dark, sometimes underground cells, they have no recognized legal rights, and no one outside the CIA is allowed to talk with or even see them, or to otherwise verify their well-being, said current and former and U.S. and foreign government and intelligence officials.

Most of the facilities were built and are maintained with congressionally appropriated funds, but the White House has refused to allow the CIA to brief anyone except the House and Senate intelligence committees' chairmen and vice chairmen on the program's generalities.

The Eastern European countries that the CIA has persuaded to hide al Qaeda captives are democracies that have embraced the rule of law and individual rights after decades of Soviet domination. Each has been trying to cleanse its intelligence services of operatives who have worked on behalf of others -- mainly Russia and organized crime.


The idea of holding terrorists outside the U.S. legal system was not under consideration before Sept. 11, 2001, not even for Osama bin Laden, according to former government officials. The plan was to bring bin Laden and his top associates into the U.S. justice system for trial or to send them to foreign countries where they would be tried.

"The issue of detaining and interrogating people was never, ever discussed," said a former senior intelligence officer who worked in the CIA's Counterterrorist Center, or CTC, during that period. "It was against the culture and they believed information was best gleaned by other means."

On the day of the attacks, the CIA already had a list of what it called High-Value Targets from the al Qaeda structure, and as the World Trade Center and Pentagon attack plots were unraveled, more names were added to the list. The question of what to do with these people surfaced quickly.

The CTC's chief of operations argued for creating hit teams of case officers and CIA paramilitaries that would covertly infiltrate countries in the Middle East, Africa and even Europe to assassinate people on the list, one by one.

But many CIA officers believed that the al Qaeda leaders would be worth keeping alive to interrogate about their network and other plots. Some officers worried that the CIA would not be very adept at assassination.

Here, for example, is an executive at Dial

Of course the testing problem is exacerbated by component environments that are very intrusive, such as Java's EJB framework. My view is that these kinds of frameworks should minimize their impact upon application code, and particularly should not do things that slow down the edit-execute cycle. Using plugins to substitute heavyweight components does a lot to help this process, which is vital for practices such as Test Driven Development.

So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.

Constructor versus Setter Injection
For service combination, you always have to have some convention in order to wire things together. The advantage of injection is primarily that it requires very simple conventions - at least for the constructor and setter injections. You don't have to do anything odd in your component and it's fairly straightforward for an injector to get everything configured.

Interface injection is more invasive since you have to write a lot of interfaces to get things all sorted out. For a small set of interfaces required by the container, such as in Avalon's approach, this isn't too bad. But it's a lot of work for assembling components and dependencies, which is why the current crop of lightweight containers go with setter and constructor injection.

The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented programming - should you fill fields in a constructor or with setters.

My long running default with objects is as much as possible, to create valid objects at construction time. This advice goes back to Kent Beck's Smalltalk Best Practice Patterns: Constructor Method and Constructor Parameter Method. Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there's more than one way to do it, create multiple constructors that show the different combinations.

Our clients cannot grow without finding a way to be successful with Wal-Mart."

Many companies and their executives frankly admit that supplying Wal-Mart is like getting into the company version of basic training with an implacable Army drill sergeant. The process may be unpleasant. But there can be some positive results.

"Everyone from the forklift driver on up to me, the CEO, knew we had to deliver [to Wal-Mart] on time. Not 10 minutes late. And not 45 minutes early, either," says Robin Prever, who was CEO of Saratoga Beverage Group from 1992 to 2000, and made private-label water sold at Wal-Mart. "The message came through clearly: You have this 30-second delivery window. Either you're there, or you're out. With a customer like that, it changes your organization. For the better. It wakes everybody up. And all our customers benefited. We changed our whole approach to doing business."

But you won't hear evenhanded stories like that from Wal-Mart, or from its current suppliers. Despite being a publicly traded company, Wal-Mart is intensely private. It declined to talk in detail about its relationships with its suppliers for this story. More strikingly, dozens of companies contacted declined to talk about even the basics of their business with Wal-Mart.

Here, for example, is an executive at Dial: "We are one of Wal-Mart's biggest suppliers, and they are our biggest customer by far. We have a great relationship. That's all I can say. Are we done now?" Goaded a bit, the executive responds with an almost hysterical edge: "Are you meshuga? Why in the world would we talk about Wal-Mart? Ask me about anything else, we'll talk. But not Wal-Mart."