Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an interfaceFileService
And an implementation of it FileServiceBean
I want to be able to process multiple filetypes.
e.g. fileService.processFile(FileDescriptor);
Where, the fileDescriptor is a class e.g.
public class FileDescriptor {
#Column(name = "FILE_TYPE")
protected String fileType;
}
Then I want multiple extensions of the FileServiceBean to process different filetypes. And FileServiceBean would have all the methods common to all filetypes.
e.g.
PhotoProcessingBean extends FileProcessingBean
VideoProcessingBean extends FileProcesingBean
How do I make the interface decide what implementation to use? I am rather new to this and not really quite sure how to ask the question to search google for the answer.
Ideally it would not just accept FileDescriptor. e.g. It could be something else like just File.
fileService.processFile(Object);
Well, in the end you have to put the decision logic somewhere, the only question is where?
I think this is a classic application of the factory-pattern: you create an object (the "factory") which has the sole purpose of deciding which concrete implemenation of a common interface to create for a given case. See https://en.wikipedia.org/wiki/Factory_method_pattern
Along the lines of:
PhotoProcessingBean extends FileProcessingBean {...}
VideoProcessingBean extends FileProcesingBean {...}
class FileProcessingFactory {
public static FileService createFileService(FileDescriptor descriptor) {
switch(descriptor.getFileType()) {
case 'Photo': return new PhotoProcessingBean();
case 'Video': return new VideoProcessingBean();
default: // do some error handling
}
}
}
And using it:
for(FileDescriptor descriptor : /* wherever they come from */) {
FileService processor = FileProcessingFactory.createFileService(descriptor);
processor.processFile(descriptor);
}
Sure enough you can also soften up the interface by accepting objects instead of file descriptors. This depends on the concrete application.
Assuming you have an interface:
public interface IFileService{
void processFile();
}
And the FileProcessingBean class that implements this:
public class FileProcessingBean implements IFileService{
//other code here
#Override
public void processFile(){
//add code for implementation of method
}
}
If you have two other classes that extend FileProcessingBean:
public class PhotoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing PHOTO...");
}
}
public class VideoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing VIDEO...");
}
}
If you would like to use it:
//This is an OOP concept called Polymorphism:
IFileService photoProcess = new PhotoProcessingBean();
IFileService videoProcess = new VideoProcessingBean();
Calling photoProcess.processFile(); and videoProcess.processFile() would yield different the implementations:
photoProcess.processFile();
videoProcess.processFile();
And you'll get the following output:
Processing PHOTO...
Processing VIDEO...
Regarding your point about not just accepting FileDescriptor but also 'something else', my recommendation would be to either know exactly what sort of arguments you are expecting, and then either implementing overriding methods or via an interface. It would not be wise to use Object as a method argument as Object is a superclass from which all objects are descendants of. You would essentially be opening the 'floodgates' and potentially run into runtime errors.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
my question is more a personnal mind challenge than a production purpose... which means that despite there are obviously better ways to achieve my goal* , I am curious about how - AND IF - I could do it this way.
*I am thus not interested in other ways atm.
I would like to "register" within a list several classes objects (Foo.class, Bar.class, etc.) sharing a common static method inherited from a common parent class.
Then I want to iterate over this list, and invoke that static method.
The following code is wrong indeed, but it may at least show what I am trying to achieve:
======== Classes definition
public class SomeGenericClass {
public abstract static String getType();
}
public class SomeSpecializedClassA extends SomeGenericClass{
public static String getType(){
return "I am of type A";
}
}
public class SomeSpecializedClassB extends SomeGenericClass{
public static String getType(){
return "I am of type B";
}
}
======== Main
class Main{
void main(){
List<Class<SomeGenericClass>> classes = new ArrayList<Class<SomeGenericClass>> ();
classes.add(SomeSpecializedClassA.class);
classes.add(SomeSpecializedClassB.class);
for((SomeGenericClass.class)Class c : classes){
System.out.println(c.getMethod("getType", null).invoke(null, null));
}
}
}
========
Any idea?
sharing a common static method inherited from a common parent class.
This is impossible; static methods do not 'do' inheritance, hence why they are called static methods. There is NO way to specify that a given class adheres to a spec, where 'the spec' involves 'has static method XYZ'.
Why do you think java has the cliché of having 'factories'? A factory is just a container concept where a single instance of a class is the place you ask questions about the concept of another class: A "PersonFactory" is a class for which usually only a single instance exists and it answers questions about persons in general. Most usually the constructor (which doesn't 'do' specs/interfaces either), but anything else goes too.
Then I want to iterate over this list, and invoke that static method.
Reflection can do this. It'd be horrible code style, hard to maintain, and all around entirely the wrong way to go about it. You're asking me: "May I have a gun because there is an annoying mosquito balanced on my left toe", and that's the bazooka. If you want to take it and let er rip, okay. Your funeral.
So what's the better way?
Why is 'static' important here? It's not. Register 'TypeOracle' objects:
public interface CommandHandlerFactory {
String getCommand();
CommandHandler makeHandler();
}
public interface CommandHandler {
void handleCommand(UserInfo sendingUser, String cmdData);
}
public class WelcomeHandler {
#Override
public void handleCommand(UserInfo sendingUser, String cmdData) {
sendMsg("Well hello there, " + sendingUser.getUserName() + "!");
}
}
channelBot.registerHandler(new CommandHandlerFactory() {
#Override
public String getCommand() {
return "/hello";
}
#Override
public CommandHandler makeHandler() {
return new WelcomeHandler();
}
}
That's how you do it in a non-blow-your-feet-right-off fashion.
NB: A comment on your question suggest using asm. This is an utterly nonsensical comment; ASM has nothing to do with this and can't help you. Ignore this comment.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
If inherited method does not contain a call to super in first statement, I need a compile error, requires constructor-like behavior. Is it possible to do this?
public class ModelBase {
protected int defaultCount;
public void init() {
defaultCount = 10;
}
}
public class Model extends ModelBase {
#Override
public void init() {
System.out.println(defaultCount);
super.init();//need error or notification
}
}
Note that requiring a call to super at all is considered an anti-pattern, in part because there is no way to enforce it, or to enforce that it is called at the right point in the method etc.
One way to do this with plain Java is not to require a call to super at all, but rather to provide a non-overrideable method which calls a subclass-specific method at the right time.
For example:
class YourClass {
final void yourMethod() {
// Stuff you want to happen first.
// and then at the end, call
subclassSpecific();
}
protected void subclassSpecific() {}
}
Now, subclasses can override that method to provide specific behavior that will occur after the rest of the things in yourMethod:
class YourSubclass extends YourClass {
#Override protected void subclassSpecific() {
// Whatever.
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hi to refactor code of 50k+ lines of code which one is better Inheritance or Composition.
My approach is as follows:
Create the subclass that will extend parent class(needs refactoring).
create interface for subclass
transfer the inner public methods to the child class that are also declared in interface of child class.
Now why this approach:
1.Parent Class want to refactor is #ManagedBean and spring #Component.
#Component
public class MBean extends ManagedBean{
#Autowired
transient SomeService someService;
private void calltoPriavateMethod(){
//100loc
}
public void calltoPublicMethod(){
//200loc
}
public void getExportJson(){
//100 loc
try{
calltoPrivateMethod()
}catch(Exception e){
//catch exception
}
try{
calltoPublicMethod()
}catch(Exception e){
//catch exception
}
}
}
Solution I tried
public Interface ChildMBeanInterface{
calltoPublicMethod();
}
#Component
public class ChildMbean extend MBean implements ChildMBeanInterface{
calltoPublicMethod(){
//200 loc copied here
}
}
#Component
public class MBean extends ManagedBean{
#Autowired
transient SomeService someService;
#Autowired
ChildMBeanInterface childMBeanInterface;
public void getExportJson(){
//100 loc
try{
calltoPrivateMethod()
}catch(Exception e){
//catch exception
}
try{
childMBeanInterface.calltoPublicMethod()
}catch(Exception e){
//catch exception
}
}
}
JSF CODE : is directly calling getExportJson()
<p:commandLink id="exportCaseWithJsonId"
value="Export Data" partialSubmit="true"
onclick="PF('statusDialog').show();"
action="#{MBean.getExportCaseJSON}" process="#this"
immediate="true">
So my is Question my class structure looks like this ? Is my approach is fine or it can be improved. Please give suggestions.
MBean is JSF managed Bean and this contains many other functions for different services.function that are called from jsf are public, however some inner method calls are private as well as public.
In general, favor Composition over Inheritance. Inheritance has many limitations that don't apply to composition, and it can make things way too complicated.
Before getting started, you need to know which parts can be seperated. Take a piece of paper, map out the usages of your fields and the relations of the methods. Try to determine which parts are isolated. Then move that part to a different class. (And obviously, you can't isolate parts of code that call methods or use fields of the super class).
Here is an example of a piece of code that contains a lot of code regarding listeners.
class Foo {
List<Listener> listeners;
// and 101 other fields
public void addListener(...) { }
public boolean removeListener(...) { }
private void notifyListeners(...) { }
// and 101 other mthods
private void somethingHappens() {
notifyListeners();
}
}
In a case like this you could regard the listeners part as an isolated feature of the class. The fields and methods which are used by this part of code, are not used by other methods, meaning you could isolate them.
So, you could move them to a new "feature class" named Listeners for example.
class Listeners() {
List<Listener> listeners;
public void add(...) { ... }
public boolean remove(...) { ... }
public void notifyListeners(...) { ... }
}
Now, in the original class, most code dissapears.
class Foo {
Listeners listeners = new Listeners();
public Listeners getListeners() { ... }
private void somethingHappens() {
listeners.notifyListeners();
}
}
(Note: the new Listeners() could also go in a protected createListeners() method, which still allows subclasses to override the behavior which you just isolated.)
Your class gets a lot thinner. But it does mean that the usages and signatures change a little. i.e. addListener(...) vs getListeners().add(...). And that may be a problem.
So, before you get started, you should determine if that is a problem or not. For internal usage this can't be a problem. But if you implemented an interface it certainly will be.
You could just add thin wrapper methods that forward requests. But often this won't be a big step forward. You moved some code, and you added some new. You may end up wondering if it's worth it. It's a trade-off worth considering if there are a lot of private methods and only a limited amount of public ones.
Alternatively, sometimes with legacy code, you may just chose to divide your classes in collapsable sections. That in itself can be a step forward.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make an abstract algorithm class for informed search with different heuristics. My idea was to have different subclasses overwrite the default heuristic() method, but the dynamic binding seems not to be working when I call the subclasses.
In astar.java:
public interface Astar {
abstract String heuristic();
}
In search.java
public class Search implements Astar {
public String heuristic() { return "default heuristic"; }
}
In EuclidianSearch.java:
public class EuclidianSearch extends Search {
#Override
public String heuristic() { return "Euclidian"; }
}
In ChebyshevSearch.java:
public class ChebyshevSearch extends Search {
#Override
public String heuristic() { return "Chebyshev"; }
}
In main.java:
EuclidianSearch e_search = null; ChebyshevDistance ch_search = null;
Search[] SearchObjects = {e_search, ch_search};
for(Search so : SearchObjects) {
System.out.println(so.heuristic());
}
When run, it displays:
default heuristic
default heuristic
I define the array in terms of Search so I can be flexible: eventually, I want to have five or more different heuristics. Why doesn't the heuristic() method of the subclass override that of the superclass?
You will get NullPointerException for calling so.heuristic() because you don't instance class, use these codes :
EuclidianSearch e_search = new EuclidianSearch();
ChebyshevDistance ch_search = new ChebyshevDistance();
but it is not sufficient to solve you problem, you should implement AStart interface by diffrent classes. don't forget that a class which implement a interface should implement all interface method. otherwise, you should define an abstract class to define only some methods and override remain methods in other classes with extend you previous class.
public class Search implements Astar {
#Override
public String heuristic() { return "default heuristic"; }
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there a way in Java to have methods that can be accessed by certain Classes?
class CommonClass{
void methodAvailableForClassA() {code goes here}
void methodAvailableForClassB() {code goes here}
}
class A{
CommonClass cc;
public void useCC(){
cc.methodAvalableForClassA();
}
}
class B{
CommonClass cc;
public void useCC(){
cc.methodAvalableForClassB();
}
}
What I am asking is if there is a way to make available methods to certain classes
As I wrote in the comments you're not providing enough context and I suspect that this problem can be avoided with a better design.
That said, you can "hack" it by overloading the same method with the different types of the classes, and have the objects send themselves to the method:
class CommonClass{
void methodAvailableForClass(A a) {...}
void methodAvailableForClass(B b) {...}
}
class A{
CommonClass cc;
public void useCC(){
cc.methodAvailableForClass(this);
}
}
class B{
CommonClass cc;
public void useCC(){
cc.methodAvailableForClass(this);
}
}
This is an X/Y Problem:
You are asking the wrong question, you are asking about a solution that is inappropriate and not the problem.
You should keep methods that are localized to a specific class specialization or implementation of an interface with that implementation.
This is know as High Cohesion and Loose Coupling.
You are trying to do the exact opposite of both of these things, and that is not a good path to be going down.
Any time you have something that is a catch all like CommonClass you are creating a tangled mess of dependencies on completely unrelated things.
Solution:
Those methods that are specialized for each of those classes should be owned by those classes that use them.
As mentioned elsewhere you should be looking for loose coupling - as long as ClassA and ClassB both know about CommonClass you've got strongly coupled code and you've got this kind of problem. However, if you split out separate interfaces which represent the various roles which CommonClass may play then you may be able to pass an instance of CommonClass to each of ClassA and ClassB but as an instance of separate roles which only give the client classes access to specific methods.
e.g.
public interface RoleForA {
void methodAvailableForClassA();
}
public interface RoleForB {
void methodAvailableForClassB();
}
public class CommonClass implements RoleForA, RoleForB {
....
}
public class ClassA {
private final RoleForA cc;
public void useCC(){
cc.methodAvailableForClassA();
}
}
public class ClassB{
private final RoleForB cc;
public void useCC(){
cc.methodAvailableForClassB();
}
}
The major caveat here is that CommonClass shouldn't just be a dumping ground for all kinds of unrelated functionality. It needs to maintain cohesiveness so you should only do this for the right reason. One example of that might be providing a read-only interface to CommonClass to ClassA and a write-only interface to ClassB. The other thing to be aware of is that the interfaces involved shouldn't be simply tailored to the ClassA/B use cases or else any loose-coupling is purely illusory.