667481 members! Sign up to stay informed.

Sponsored Links


Resources

Enterprise Java
Research Library

Get Java white papers, product information, case studies and webcasts

J2EE patterns J2EE patterns J2EE patterns Messages: 7 Messages: 7 Messages: 7 Printer friendly Printer friendly Printer friendly Post reply Post reply Post reply XML XML XML

Refactoring: Introduce Adapter

Posted by: Archimedes Trajano on March 05, 2005 DIGG
Available at http://www.livejournal.com/users/trajano/24452.html

This is a refactoring I generally do, but I can't seem to find it in www.refactoring.com, it might be an anti-pattern for what I know, what do you think? Also the refactoring link at the note below does not exist yet from what I know since I have to write it still.

objectB.setA(getA(objectA));
objectB.setB(getB(objectA));

|
v

ObjectAdapter adapter = new ObjectAdapter(objectA);
objectB.setA(adapter.getA());
objectB.setB(adapter.getB());
Motivation
Objects that are as simple as Strings or as complex as HttpServletRequest have data that we need to retrieve. However, we need to get specific pieces of data either by using the String.substring() or HttpServletRequest.getAttribute() methods. The direct approach forces an understanding on the how the data is stored in the objects.

The Adapter design pattern is used to wrap an existing object with another object that provides methods that would be named closer to what the client would need and limits the possible inputs to the actual object to what clients would normally need so developers do not have to know which part to get from the data.

Mechanics
Determine the object to be wrapped.
Create a new adapter class that has a constructor with one parameter, the object that needs to be wrapped.
Add a private final field to the adapter class with the type of object that needs to be wrapped.
In the adapter class constructor assign the field with the value from the parameter.
In the client code place the code to create the adapter in. Then test to ensure it is working properly.
Determine a data extraction method used in the client code.
Create a new method that performs the data extraction method into the adapter class.
Replace the client code that used to perform the extraction with the method from the adapter class.
Test.
Add more methods to the adapter for any calculation instance.

Example
Before refactoring.

public class ClassA {
  public void someMethod(String data) {
    Persister.saveData(getId(data), getName(data));
  }
  private String getId(String data) {
    return data.substring(0,4);
  }
  private String getName(String data) {
    return data.substring(5,10);
  }
}

after refactoring

public class ClassA {
  public void someMethod(String data) {
    DataAdapter adapter = new DataAdapter(data);
    Persister.saveData(adapter.getId(), adapter.getName());
  }
}

public class DataAdapter {
  private final String data;
  public DataAdapter(String data) {
    this.data = data;
  }
  private String getId() {
    return data.substring(0,4);
  }
  private String getName() {
    return data.substring(5,10);
  }
}Notes
In some cases all the data is needed by clients so it might be useful to move the code for the getters to be performed during construction rather than on demand. Please see "Move getter logic to constructor" refactoring.

Threaded replies

·  Refactoring: Introduce Adapter by Archimedes Trajano on Sat Mar 05 15:31:23 EST 2005
  ·  Fits Proxy pattern by Michael Mahemoff on Wed Mar 23 09:52:15 EST 2005
    ·  Facade or Decorator could do also (but not Proxy) by Guillaume Bertrand on Tue Mar 29 06:29:20 EST 2005
  ·  Facade or Decorator could do also (but not Proxy) by SAnjay Sankolli on Sat Apr 02 09:56:54 EST 2005
  ·  Refactoring: Introduce Adapter by han theman on Sat Apr 02 10:12:48 EST 2005
    ·  Refactoring: Introduce Adapter by Anonymous Coward on Sun May 01 21:08:25 EDT 2005
      ·  Not So Complex Example by Archimedes Trajano on Wed Aug 31 17:57:51 EDT 2005
  ·  complexity added by Olivier Lalonde on Fri Mar 03 20:45:40 EST 2006
  Message #162957 Post reply Post reply Post reply Go to top Go to top Go to top

Fits Proxy pattern

Posted by: Michael Mahemoff on March 23, 2005 in response to Message #160006
I would probably call it a Proxy rather than an Adaptor. A Proxy typically wraps around an object to constrain access and/or alter its behaviour. An Adaptor usually involves legacy (difficult-to-change) classes on either side, which isn't the issue here.

I don't remember seeing it in Fowler's Refactorings, but it's certainly a useful refactoring to make.

  Message #163637 Post reply Post reply Post reply Go to top Go to top Go to top

Facade or Decorator could do also (but not Proxy)

Posted by: Guillaume Bertrand on March 29, 2005 in response to Message #162957
A Proxy would preferably implement the same interface as the object it gives access to, so that the user won't know it's a proxy. Proxy will not necessarily wrap around an object, but mostly control communication with it.

The example shown by Archimedes Trajano is quite what Adapter should do, but I think this precise use is really between Adapter (adapting an exsting interface to a new system), Facade (providing simple meaningful access to an object hierarchy) and Decorator (adding functionnality to the object).

What do you think?

  Message #164474 Post reply Post reply Post reply Go to top Go to top Go to top

Facade or Decorator could do also (but not Proxy)

Posted by: SAnjay Sankolli on April 02, 2005 in response to Message #160006
I agree with Guillaume Bertrand.

  Message #164477 Post reply Post reply Post reply Go to top Go to top Go to top

Refactoring: Introduce Adapter

Posted by: han theman on April 02, 2005 in response to Message #160006
While such "patterns" can be useful, this particular one increases complexity (an added class per appliance) which should have been mentioned as a liability.

  Message #168709 Post reply Post reply Post reply Go to top Go to top Go to top

Refactoring: Introduce Adapter

Posted by: Anonymous Coward on May 01, 2005 in response to Message #164477
agreed, this should be used when slightly more complex extraction logic is required. more code = harder to maintain

  Message #183182 Post reply Post reply Post reply Go to top Go to top Go to top

Not So Complex Example

Posted by: Archimedes Trajano on August 31, 2005 in response to Message #168709
One of the things I think this can be used is for the HttpServletRequest object in which there are several places to get the data: session, attributes, parameters.

Rather than having every class know where to get the data from a map and cast it to the appropriate type, it can be performed on a single place: the adapter.

  Message #202920 Post reply Post reply Post reply Go to top Go to top Go to top

complexity added

Posted by: Olivier Lalonde on March 03, 2006 in response to Message #160006
Maybe there is be more code to maintain, but with good packaging this refactoring can be quite useful, either for complex objects or not.

New content on TheServerSide.comNew content on TheServerSide.comNew content on TheServerSide.com

Dependency Injection in Java EE 6 - Part 1

Reza Rahman explores the features of the proposed JSR 299, Contexts and Dependency Injection for Java EE (CDI). When approved, it promises to be a key feature of Java EE 6. (November 2, Article)

SAML: It's Not just for Web services

SAML is an XML-based standard for exchanging authentication and authorization data between security domains. The single most important problem that SAML was created to solve is the Web browser Single Sign-On problem. Many organizations are debating whether to stay with version 1.1 or move to 2.0. This article makes observations about both options. (September 28, Article)

Programming is Also Teaching Your Team

Joe Ottinger takes a look at how people learn, and applies it to the practice of programming. He notes that understanding how people learn is an essential part of working in a programming team. (September 22, Article)

Can Java EE Deliver The Asynchronous Web?

Stephen Maryka gave us an article about the Asynchronous Web and posed a number of questions that get examined like an approach to delivering Asynchronous Web capabilities through extensions to existing Java EE technologies. (July 14, Article)

JSF Flex

JavaServer Faces Flex goal is to provide users capability in creating standard Flex components, part of flexSDK which is open sourced through MPL license, as normal JSF components. This article by Ji Hoon Kim will provide an overview of creating a simple multilingual JSF page consisting of JSF Flex tags. (June 29, Article)

The Rules of SOA - A Road to a Successful SOA Implementation

In this session Jeff explores the key characteristics of successful SOA projects. He covers some of the patterns, and anti-patterns, tool sets, and strategies that he himself learned the hard way. Last, he provides a strategy and blueprint for achieving a high likelihood of success in your SOA project. (June 23, Tech Talk)

Ari Zilka Talks About Terracotta 3.1

Ari Zilka, CTO of Terracotta, Inc., talks about the new features in Terracotta 3.1, announced during JavaOne and available now. (June 15, Tech Talk)

Enterprise Application Integration, and Spring

In this Tech Talk, Josh Long explores an integration challenge using Spring Integration and walks through the implementation, employing and expanding on the basic patterns of Enterprise Application Integration to tie together components into a function integration solution, and then demonstrates how Spring Integration helps address the integration requirements. (June 15, Tech Talk)

Google Web Toolkit: An Introduction

In this Tech Talk, David Geary teaches you: The basics of Google Web Toolkit; How to implement Ajax-enabled applications in Java; Internationalization; Hooking into the browser history mechanism; Remote procedure calls. (June 4, Tech Talk)

Just Enough Early Architecture to Guide Development

Jon Kern discusses the best architecture/technical solutions and ensure that they are repeated by all developers. By tackling the architecture up-front in a serial manner, subsequent parallel development will be much more manageable and predictable. (May 28, Tech Talk)

Productive Programmer: On the Lam from the Furniture Police

This keynote describes the frustrations of modern knowledge workers in their quest to actually get some work done, and solutions for how to guard yourself against all those distractions. Neal Ford talks about environments, coding, acceleration, automation, and avoiding repetition as ways to defeat the misguided attempts to sap your ability to produce good work. (May 26, Tech Talk)

Auto-Scaling Your Existing Web Application

Gil demonstrates how new, aggressive uses of already abundant compute capacity by common applications offer competitive value for application designers. (May 21, Tech Talk)

Automating Hibernate Mapping and Queries For Java Web Development

Chris Keene introduces WaveMaker as a new way to automate the ability to generate Hibernate classes in order to more quickly bring OR mapping into an application. (May 19, Article)

Auto-Scaling Your Existing Web Application

In this session Nati Shalom demonstrates how to take a standard Java EE web application and scale it out or down dynamically without changes to the application code. Seeing as most web applications are over-provisioned to meet infrequent peak loads, this is a dramatic change because it enables growing your application as needed, when needed, without paying for unutilized resources. (May 19, Tech Talk)

Free Book: Jakarta-Struts Live

Download the entire book of Jakarta-Struts Live and learn about Struts MVC, Tiles, the Validator, DynaActionForms, plug-ins, internationalization, and more.
(Book PDF Download)

Application Server Matrix

The Application Server Matrix is a detailed listing of J2EE vendors and their application server products, with information on latest version numbers, J2EE spec support and licensing, pricing, platform support, and links to product downloads and reviews.
(Application Server Comparison Matrix)

News | Blogs | Discussions | Tech talks | Patterns | Reviews | White Papers | Downloads | Articles | Media kit | About
Java Solutions
All Content Copyright ©2007 TheServerSide Privacy Policy
Site Map