Solved

Java refactoring: removing duplicate code

Posted on 2014-07-24
7
240 Views
Last Modified: 2014-07-24
In the following scenario I have:

interface IClassA

abstract class ClassA implements IClassA

concrete classes ClassB1 and ClassB2 extend ClassA


ClassB1 and ClassB2 both have methods DoStuff()

The code for DoStuff() is identical in both ClassB1 and ClassB2

Is it possible to refactor this to get rid of the identical code?

public interface IClassA {

	public int DoStuff();
	public int ClassSpecific();
}



public abstract class ClassA implements IClassA {

	//public ClassA(){}
	
	public void aCommonMethod() {
	}
}



public class ClassB1 extends ClassA {
	
	public ClassB1(){}
	

	@Override
	public int DoStuff() 
	{
		return ClassSpecific();
	}


	@Override
	public int ClassSpecific()
	{
		return 9;
	}
}



public class ClassB2 extends ClassA {

	public ClassB2(){}

	
	@Override
	public int DoStuff() 
	{
		return ClassSpecific();
	}
	
	
	@Override
	public int ClassSpecific()
	{
		return 5;
	}
}

Open in new window

(Imagine DoStuff() is a lot more complicated than it is here, but it does have buried in it a call to ClassSpecific().)
0
Comment
Question by:deleyd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 27

Accepted Solution

by:
dpearson earned 500 total points
ID: 40217786
Can you not just move DoStuff() to classA?

Doug
0
 

Author Comment

by:deleyd
ID: 40217814
Here's my real doStuff() class:
    public double getValueAs(TemperatureUnits units) { 
		if (units == TemperatureUnits.FAHRENHEIT) {
            return asFahrenheit().doubleValue();
        }
        else if (units == TemperatureUnits.CELSIUS) {
            return asCelsius().doubleValue();
        }
        else if (units == TemperatureUnits.KELVIN) {
            return asKelvin().doubleValue();
        }
        else
        {
            throw new InvalidParameterException("Unhanded Temperature Unit " + units.toString());
        }
    }

Open in new window

methods asFahrenheit(), asCelsius(), asKelvin() are the Class Specific methods.

Moving the code to the abstract superclass (ClassA), it complains, because the superclass doesn't define asFahrenheit, asCelsius, asKelvin.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40217835
Make the methods static in the abstract class then.
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:deleyd
ID: 40217900
I get:

"Cannot make a static reference to the non-static method ClassSpecific() from type IClassA."
0
 
LVL 27

Expert Comment

by:dpearson
ID: 40217967
In that case I think you'll want to define
asFahrenheit, asCelsius, asKelvin
in the interface/abstract class as well.

You'll need a common "something" (abstract class/interface) for the shared code to be able to call common methods like "asCelsius" and have them execute the right specific implementation.

As you say, since the code is identical this should be solvable with the right hierarchy.  But the interface (or abstract class) will need to include all of the methods that are shared between the two concrete classes.

Doug
0
 

Author Closing Comment

by:deleyd
ID: 40218106
I was missing the keyword 'abstract' !

I had public class AbstractClass

Now it works great once I noticed that. Thank you!
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 40218260
Well done Doug! ;)
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Android development question 2 104
Java: anonymous class 4 52
Delphi Firemonkey: if the Sms contain special characters it won't send it 3 80
What browser will run Java? 7 168
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Suggested Courses

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question