DRY up java (lambda functions?) -


I'm writing a program in Java that essentially tests a bunch of things ...

every call, I need to check for NullPointerExceptions , StackOverflow , IndexOutOfBounds , etc. ... < P> This is repeating me now Pattern in each of my ways:

  try {doSomething (); } Hold (NullPointerExceptions npe) {// Some Impressions} Catch (Stack Overflow Soi) {// Some Impressions} Catch (IndexOutBoond IOB) {// Print something}   

Since I I can call the throw exception to back to the main (because I'm actually doing the same thing) To run in requires the next test).

I want to write a Lambda tester that I can pass the function, but I can not find any way to do this with Java :(.

I 'like Want to do something:

  Private zero testing (method m, e hopeful) {try (if (! M.run (.) Equals (expected value)) system.out.println ( "Failure Test:" + m.name () + ". The value was" + m.run () + "," + expected value ");} hold () {// see above}}    

all Better than you can use an interface in Java:

  interface doSomething  gt; & gt; {e doSomething ();} < / Code>  

Your test method can look like this:

  Private Zero Testing (DoSomething  I , E expected value) {try (if (m.doSomething (.) Equals (expected values) System.out.println ("FAILED test");} hold () {// handle exception}}   

e needs to be expanded > & Gt; Because you are equal to test inside .

This is called a SAM (single abstract method) interface. The use of SAM classes and interfaces to simulate lambdass is a common occurrence in Java. I have also called them "Sambadas".

Edit: My solution is not required to modify the existing sections:

  DoSomething foo = New DoSomething & lt; String & gt; () {Public string doSomething () {Return "Hello World"; }}; Test (af, "hello world");    

Comments

Popular posts from this blog

qt - switch/case statement in C++ with a QString type -

python - sqlite3.OperationalError: near "REFERENCES": syntax error - foreign key creating -

Python's equivalent for Ruby's define_method? -