2

I have an interface like this:

    public interface Foobar
    {
        default void foo( Bar bar )
        {
            foo( bar, 1 );
        }

        default void foo( Bar bar, int n )
        {
            for ( int i = 0; i < n; i++ )
            {
                foo( bar );
            }
        }
    }

In the beginning I thought it'd be fine just as:

    default void foo( byte[] b )
    {
        foo( b, 0, b.length );
    }

    void foo( byte[] b, int off, int len );

My problem is that I want to execute foo either once or n times. Any implementing class may override either one or both of them. (The second method exists for batching purposes in a performance critical system)

But it seems that my solution using default isn't good style as it is possible to override none of them and calling either leads to an infinite loop (and eventually to a StackOverflow).

So, my question is: What would be good OOP style compromise?

Androbin
  • 991
  • 10
  • 27

1 Answers1

2

Your IFoo interface can look like this -

public interface IFoo {

    default void foo(Bar bar, int n) {
        for (int i = 0; i < n; i++) {
            foo(bar);
        }
    }

    void foo(Bar bar);

}

and your Foo class implementing the IFoo interface can be like this -

public class Foo implements IFoo{

    @Override
    public void foo(Bar bar) {
        // process foo logic

    }

}

You do not need to enforce the single loop logic inside the interface, instead the call the foo straight away.

  • "//process foo logic" is what I want the implementing class to do – Androbin Aug 07 '16 at 12:39
  • 1
    If you want to force that behaviour to the implementing class, then no need to keep it as `default`. However, `foo(Bar)` must be implemented at the interface level as `default`. – Tejas Unnikrishnan Aug 07 '16 at 12:41
  • 1
    If you think, this answer works for you, let me know, I will edit the answer so it becomes more readable. – Tejas Unnikrishnan Aug 07 '16 at 12:42
  • Of course I could remove the default but the reason interface level method defaults exist is for the sake of convenience. I will remove it if I get no better suggestion. – Androbin Aug 07 '16 at 12:47
  • 1
    You can have one more more `default void fooLoop(Bar,n)` which will have the looping logic, while the actual foo logic can be enforced to all implementing classes – Tejas Unnikrishnan Aug 07 '16 at 12:50
  • You mean, I should remove the first method and call foo(bar, 1) instead? – Androbin Aug 07 '16 at 12:52
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120350/discussion-between-tejas-unnikrishnan-and-androbin). – Tejas Unnikrishnan Aug 07 '16 at 13:02