Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Java IoT, Eclipse

Java IoT: Article

Eclipse Special: Bill Dudney Looks at the Change Method Signature Refactoring

Eclipse Special: Bill Dudney Looks at the Change Method Signature Refactoring

This column contains an excerpt from one of the refactoring chapters in my book Eclipse 3 Live. The book will eventually contain similar sections for all the refactorings available in Eclipse.

Change Method Signature

This refactoring allows you to change the signature of an existing method by changing any of the aspects of the method that make its signature. You can change the access rights (public, private, etc.), you can change the name as well as add or remove parameters, and you can add or remove exceptions that are thrown from the method.

The most typical use of this refactoring is to add or remove parameters from a method. Over time, you might discover that a method would be better designed or easier to understand or implement if it took an additional parameter. Another reason to use this refactoring is that during the process of refining/refactoring your code, you might discover that you no longer need one of the parameters that is being passed in. In addition to adding and removing parameters, this refactoring is also helpful in changing the access privileges on methods. I most commonly change access rights to be more restrictive (i.e., public to protected or private). Sometimes for retrofitting unit tests onto existing code, however, I change privileges to be less restrictive. This refactoring will change all the subclass implementations of the method to match the new access privilege.

Change Method Signature - AntiPattern Example

During some recent development on the MyFaces project, I implemented a method and then realized that I needed an additional parameter in order to make the method work properly. Specifically, I added some code to handle some of the factory lookup functionality. At first, I was only interested in getting the algorithm correct and not on how to make sure the actual configuration was set properly. The initial method is shown in Listing 1 below.

Listing 7.2 Initial performMetaInfFactoryConfig


protected FactoryConfig performMetaInfFactoryConfig(
      ExternalContext context) throws FacesException {
    Set factoryNames = FactoryFinder.getFactoryNames();
    // keyed on resource names, factory name is the value
    Map resourceNames = expandFactoryNames(factoryNames);
    //Search for factory files in the jar file
    Set services = context
        .getResourcePaths(META_INF_SERVICES_LOCATION);
    // retainAll performs the intersection of the factory
    // names that we are looking for the ones found, only the
    // services found that match the expected factory names 
    // will be retained
    services.retainAll(resourceNames.keySet());
    Iterator itr = services.iterator();
    FactoryConfig config = new FactoryConfig();
    while (itr.hasNext()) {
      String resourceName = (String) itr.next();
      InputStream is = context
          .getResourceAsStream(resourceName);
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String className = null;
      try {
        className = br.readLine();
      } catch (IOException e) {
        throw new FacesException(
            "Unable to read class name from file "
                + resourceName, e);
      }
      try {
        Class.forName(className);
      } catch (ClassNotFoundException e) {
        throw new FacesException("Unable to find class "
            + className, e);
      }
      config.setFactory((String) resourceNames
          .get(resourceName), className);
    }
    return config;
  }

So after completing this code and testing it, I realized that the configuration was not actually being updated. Following the standard of the other code in this class that did similar things, I decided to pass in the configuration object that maintained the overall configuration. And instead of just making the change and then tracking down the compilation problems, I applied the refactoring.

Change Method Signature - Apply the Refactoring

The first step in using any of the refactorings is to invoke it via the context menu in the Java editor. For this refactoring to work, you must select a method signature or any line in the method body. Keep in mind that for a particular refactoring to be available, you must have an element selected that the desired refactoring can effect. Figure 1 shows the refactoring menu item selected over the selected method name.

I almost always end up double-clicking on the method name just to make sure that I'm invoking the refactoring on the correct element.

After invoking the refactoring, you will see a dialog box that looks like Figure 2.

There are two things that need to be changed to have this method match the rest of the methods in the class. First, the return type must be changed to void and an additional parameter of type FacesConfig must be added. Since this method returns a value and the return type is being changed to void, Eclipse will complain that the result of the refactoring will not compile. You can safely hit Continue and then remove the return statement after the refactoring is complete. Figure 3 shows the updated values.

Notice that the default value for the new parameter must be specified and that it is defaulted to null. For simple values like String or int, you can specify the value in this dialog box. For more complex values, you will have to do some work after refactoring. Now that we have the values changed and specified, click the OK button. After doing some internal checking, Eclipse will report that a void method should not return a value. As stated earlier, it is OK to ignore this warning and click the Continue button. After the refactoring completes, the return statement can be deleted. There is one more small change to make; we need to apply the factory configuration to the overall configuration object facesConfig. The refactored code is shown in Listing 3

Listing 3 Refactored performMetaInfFactoryConfig


protected void performMetaInfFactoryConfig(
      ExternalContext context, FacesConfig facesConfig)
      throws FacesException {
    Set factoryNames = FactoryFinder.getFactoryNames();
    // keyed on resource names, factory name is the value
    Map resourceNames = expandFactoryNames(factoryNames);
    //Search for factory files in the jar file
    Set services = context
        .getResourcePaths(META_INF_SERVICES_LOCATION);
    // retainAll performs the intersection of the factory
    // names that we are looking for the ones found, only the
    // services found that match the expected factory names
    // will be retained
    services.retainAll(resourceNames.keySet());
    Iterator itr = services.iterator();
    FactoryConfig config = new FactoryConfig();
    while (itr.hasNext()) {
      String resourceName = (String) itr.next();
      InputStream is = context
          .getResourceAsStream(resourceName);
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String className = null;
      try {
        className = br.readLine();
      } catch (IOException e) {
        throw new FacesException(
            "Unable to read class name from file "
                + resourceName, e);
      }
      try {
        Class.forName(className);
      } catch (ClassNotFoundException e) {
        throw new FacesException("Unable to find class "
            + className, e);
      }
      config.setFactory((String) resourceNames
          .get(resourceName), className);
    }
    facesConfig.setFactoryConfig(config);
  }

Now that the code is refactored you can easily search for all the uses of the method and change the default null value to be a more appropriate value. You can use the context menu's References->Workspace to have Eclipse search the whole workspace for calls to the method. In this example the method is protected so it makes things a bit easier to do manually but it is a great excuse to get some experience using Eclipse's great search features.

More Stories By Bill Dudney

Bill Dudney is Editor-in-Chief of Eclipse Developer's Journal and serves too as JDJ's Eclipse editor. He is a Practice Leader with Virtuas Solutions and has been doing Java development since late 1996 after he downloaded his first copy of the JDK. Prior to Virtuas, Bill worked for InLine Software on the UML bridge that tied UML Models in Rational Rose and later XMI to the InLine suite of tools. Prior to getting hooked on Java he built software on NeXTStep (precursor to Apple's OSX). He has roughly 15 years of distributed software development experience starting at NASA building software to manage the mass properties of the Space Shuttle.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
digitwiz101 06/22/04 10:37:59 AM EDT

A useful trick with this refactoring is to change the default to something like DOES_NOT_COMPILE or ZZZZZZ. This way, when you recompile after the refactoring, the compiler will immediately alert you with problems for each place where you need to examine the calls to the refactored method.

@ThingsExpo Stories
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, discussed new ways of thinking and the approaches needed to address the emerging challenges of security i...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that Elastifile will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...