Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 307
  • Last Modified:

How to design with Interfaces in Java and use them properly ?

Hi,
I am trying to design with interfaces and use the interfaces properly...
Here is what I am trying to do:
I would like to create an interfaces as:

public interface ErrorHandler {
   
    public void HandleError(Object message); //handle just a message
    public void HandleError(Object message, Throwable throwable); //handle a message alongwith a throwable stackTrace

}

Now, I want to implement the interfaces and use it in my application ?
How can I go about doing that?
Here are the assumption:
I will actually create/send an email message with the message/throwable ....(This is implementation specific... no need to explain this...)

But what I really need is to understand how I really go about implementing and using this interface ?

I found this website to be helpful but can't figure out how I pass the arguments for my interface???????

http://www.artima.com/designtechniques/interfaces3.html


Thanks..
_Esam
0
_Esam
Asked:
_Esam
  • 9
  • 7
  • 6
  • +3
2 Solutions
 
CEHJCommented:
Firstly, your method names should be in camel case. One implementation would be


class X implements ErrorHandler {
    public void handleError(Object message, Throwable t) {
        System.err.println(message);
        t.printStackTrace();
    }
}

Open in new window

0
 
CEHJCommented:
(The other message should be there too or it won't compile)
0
 
sciuriwareCommented:
You are working in a good direction, but your purpose is more
important than some design pattern that you want to follow.

An interface FORCES a class to have some methods that supply some service.
That's one side.
At the same time implementing an interface adds a qualification to a class
that makes its objects acceptable to those program pieces that TRUST
that the implementing class does really do something useful when those methods
are called.
So, it's a matter of relying on those services.
To make it easier for the callers, try to offer that, what makes it more useful
to them: throwing an Exception of any kind? Finding a way to publish the message?

Ask yourself this question: what would I demand if somebody else was setting up
this interfacing?

;JOOP!
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
spoxoxCommented:
Not hard stuff.

You have your interface in your question. The simplest way to "implement" the interface is

public MyNewClass implements ErrorHandler {
//...here you have a method corresponding to each abstract method from the interface class ErrorHandler
//...ie,
    public void HandleError(Object message) //handle just a message
  {
/...do something
  };
    public void HandleError(Object message, Throwable throwable) //handle a message alongwith a throwable stackTrace
  {
/...do something
  };
}
0
 
_EsamAuthor Commented:
Now, I understood this part ..
Now, how do I design a class that uses this interface and uses the interfaces to send the error not the implementation ?
Like: say ... in my application there were some errors and I want to send it using the interface not the implementation...
as in ... Interrogator.makeItTalk(cc);

"src > the url above "

Thanks.
_Esam...

interface Talkative {
 
    void talk();
}
 
abstract class Animal implements Talkative {
 
    abstract public void talk();
}
 
class Dog extends Animal {
 
    public void talk() {
        System.out.println("Woof!");
    }
}
 
class Cat extends Animal {
 
     public void talk() {
        System.out.println("Meow.");
    }
}
 
class Interrogator {
 
    static void makeItTalk(Talkative subject) {
        subject.talk();
    }
}
 
Given this set of classes and interfaces, later you can add a new class to a completely different family of classes and still pass instances of the new class to makeItTalk(). For example, imagine you add a new CuckooClock class to an already existing Clock family: 
 
 
class Clock {
}
 
class CuckooClock implements Talkative {
 
    public void talk() {
        System.out.println("Cuckoo, cuckoo!");
    }
}
 
Because CuckooClock implements the Talkative interface, you can pass a CuckooClock object to the makeItTalk() method: 
 
 
class Example4 {
 
    public static void main(String[] args) {
        CuckooClock cc = new CuckooClock();
        Interrogator.makeItTalk(cc);
    }
}

Open in new window

0
 
_EsamAuthor Commented:
Say...
In my application I have an error message:
String errrorStr = "Error occurred while processing X";
Exception ex = new MyException("");

How do I pass these arguments to the interface methods ...thru  a delegate ???

Thanks.
_Esam...
0
 
CEHJCommented:
You call the class that implements the interface with them
0
 
_EsamAuthor Commented:
Exactly . how so ?
0
 
CEHJCommented:
errorHandlerImplementer.handleError("This is the error for you!", new RuntimeException());
0
 
_EsamAuthor Commented:
I am not convinced somehow ...
This sounds like - implementation specific !!!

What was the purpose of the Interface then ????

I would like it interface specific ...

How I do that ?

Thanks.
_Esam..
0
 
_EsamAuthor Commented:
Here is what I have so far:


public interface ErrorHandler {
   
    public void handleError();
   
}


public class ErrorProcessor {
   
    public void processError(ErrorHandler eh){
        eh.handleError();
    }
}


public class FmsErrorHandler implements ErrorHandler{
   

    public void handleError(){
     
        try{
            System.out.println("Sending error message");

        }
        catch(Exception exception){
          exception.printStackTrace();
           
      }
    }
}


public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor();
        eProcessor.processError(fmsEH);
    }
}


NOW, what I really need is to have two args in my interface method ..
like:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}

and implement and use likewise ....

I can't make the connection for these arguments ???

Please advise !!!

Thanks much ...

_Esam.
0
 
spoxoxCommented:
1)
public class ErrorProcessor {
   
    public void processError(ErrorHandler eh){ // this wants to be FmsErrorHandler, not ErrorHandler
        eh.handleError();
    }
}
------- - - - - ------- - - - - ------- - - - - ------- - - - - ------- - - - - ------- - - - -
2)  NOW, what I really need is to have two args in my interface method ..
like:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}

OK, add the new handleError method to the ErrorHandler class, then implement it in FmsErrorHandler. As the signature is different from the existing handleError() method, you can do this.
0
 
CEHJCommented:
public void processError(ErrorHandler eh){
        eh.handleError();
    }

will have to process (pass) those arguments
0
 
objectsCommented:
your ErrorProcessor class serves not purpose really, and you don't want to be passing an ErrorHandler around everywhere. Would be better written as:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}


public class ErrorProcessor {
    private ErrorHandler errorHandler;
    public class ErrorProcessor(ErrorHandler errorHandler) {
      this.errorHandler = errorHandler;
   }
   
    public void processError(Object message, Throwable throwable){
        errorHandler.handleError(message, throwable);
    }
}


public class FmsErrorHandler implements ErrorHandler{
   

    public void handleError(Object message, Throwable throwable){
     
        System.out.println(message);
          throwable.printStackTrace();
    }
}


public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(fmsEH);
        eProcessor.processError("test", new Exception());
    }
}
0
 
_EsamAuthor Commented:
>>your ErrorProcessor class serves not purpose really,

Could you please let me know why this is?

Thanks.
_Esam..
0
 
objectsCommented:
because you could just call the error hqndler directly
0
 
_EsamAuthor Commented:
>>because you could just call the error hqndler directly

As CEHJ illustrated earlier like:
errorHandlerImplementer.handleError("This is the error for you!", new RuntimeException());

OR to say:

public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        fmsEH.handleError("test", new Exception());
    }
}

Please let me know..

Thanks.
_Esam...
0
 
CEHJCommented:
Yes, that's it
0
 
objectsCommented:
as i posted in my earlier cmment
0
 
_EsamAuthor Commented:
What purpose does the interface serve then ?

This is the million $ question then :)

I am trying to grasp this interface thing ...

I am trying to design to the interfaces not implementation...
How I accomplish it then ?

Thanks..
_Esam
0
 
objectsCommented:
you can still use your ErrorProcessor. Just the way you had it previously was redendant.
With the changesa I posted above it allows you to hide the ErrorHandler from your application code.
And allow you to add generic error handling to your processort, without having to add it to every error handler implementation
Otherwise theres no real point in having an interface at all :)

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(fmsEH);
        eProcessor.processError("test", new Exception());
    }
0
 
objectsCommented:
>What purpose does the interface serve then ?

if you wanted to have differnt error handler implementations, then you could just change the wiring of your processor
without changing any of your application code

eg.

    public static void main(String[] args) {
        ErrorHandler eh = new XyzErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(eh);
        eProcessor.processError("test", new Exception());
    }
0
 
_EsamAuthor Commented:
What I agree is that:
>>
if you wanted to have differnt error handler implementations, then you could just change the wiring of your processor
without changing any of your application code

eg.

    public static void main(String[] args) {
        ErrorHandler eh = new XyzErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(eh);
        eProcessor.processError("test", new Exception());
    }

<<
The purpose of the interface should be to allow multiple implementation ..
And the client shouldn't have to know the details of the implementation ...

If I am to invoke directly on the implementation,
Then my interface is just a dummy one....

I believe I should have the delegate .. ErrorProcessor ...

Or What would be the best approach to accomplish what I am trying to do ...
With the interface ?

Thanks much !
_Esam....
0
 
objectsCommented:
i'd use a deleagte, thatway you could also make it a singleton so you don't have to pass it around to every class that needs it (which is probably all of them)
0
 
CEHJCommented:
>>
If I am to invoke directly on the implementation,
Then my interface is just a dummy one....
>>

Not sure what the above means. One always invokes an implementation - it's not possible to do otherwise

What you'd normally do is use the reference to an interface, as opposed to an implementation. e.g.

Writer out = new FileWriter(f);
out.write(chars);

(An abstract class is functionally equivalent)
0
 
gnoonCommented:
>What purpose does the interface serve then ?
I think, the story begins at principal of "Java Inheritance and Polymorphism".

The rules are
- a class must inherit from a parent class (Object class by default).
- a class can inherit from many interfaces, and MUST implements all methods defined in those interfaces.

And I think, the most helpful of interface is to make sure that a class has the methods, which can be called from anywhere, defined in the interface.

For example

interface Inf1 {
  public void M1();
}

class Class1 implements Inf1 {
  public void M1() {
    System.out.println("Class1.M1()");
  }
  public void M2() {
    System.out.println("Class1.M2()");
  }
}

class Class2 extends Class1 {
  public void M() {
    System.out.println("Class2.M()");
  }
}

Class2 cls2 = new Class2();

cls2.M(); // just call to a known-method of Class2

if(cls instanceof Class1) { // test if it's subclass of Class1

  // At here, we know that we can call to the method M1() if we cast it back to Class1
  Class1 cls1 = (Class1) cls2;

  // then call to M1()
  cls1.M1();
}

Also this is equivalent

if(cls instanceof Inf1) { // test if it's subclass of Inf1
  Inf1 inf1 = (Inf1) cls2;
  inf1.M1();
}
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 9
  • 7
  • 6
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now