Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Liz McMillan, Stackify Blog, Progress Blog

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)

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.


@ThingsExpo Stories
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze 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. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that B2Cloud 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. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.