Method overriding and Functional Interface complie error - java-8

I have replicated an error that I ran into while using Java 8 #FunctionalInterface (eclipse). The following does not compile; Refined produces the error:
#FunctionalInterface
interface Functioner<TFunnel, TFan> {
Function<TFunnel, TFan> funnelledThenFanned();
}
#FunctionalInterface
interface Receiver<T, TFan>
extends Functioner<Supplier<? extends T>, TFan> {}
#FunctionalInterface
interface Giver<TFunnel, T>
extends Functioner<TFunnel, Supplier<T>> {}
#FunctionalInterface
interface Refined<T, R>
extends Function<T, R>, Receiver<T, Supplier<R>>, Giver<Supplier<? extends T>, R> {
#Override
public abstract R apply(T arg);
#Override
public default Function<Supplier<? extends T>, Supplier<R>> funnelledThenFanned() {
...
}
}
Refined extending all of Function, Receiver and Giver causes the error; remove any one of these, and the code compiles. Is this the correct behavior? If so, how can/should I refactor?
UPDATE
This seems to produce a similar error:
#FunctionalInterface
interface Another<TFunnel, T>
extends Functioner<TFunnel, Supplier<T>>, Giver<TFunnel, T> {
public abstract void newMethod();
#Override
public default Function<TFunnel, Supplier<T>> funnelledThenFanned() {
...
}
}
Also, I'll note that without #FunctionalInterface everything compiles; interface instances just cannot be expressed as a lambda.

Functioner has an abstract method funnelledThenFanned(), and Another adds newMethod(), making 2 abstract methods, which exceeds the limit of 1 imposed by #FunctionalInterface.
There is no mystery here.

This was Eclipse bug 453552, which was fixed as of 4.6M1, so any Neon release (currently Neon.1, soon Neon.2) contains the fix.

Switching from Eclipse Mars to Oxygen solved this problem. Thank you.

Related

How do Hooks in Webflux / Spring Reactor work (using switchIfEmpty as an example)?

If I use switchIfEmpty for a Mono for example, I have a hard time locating where the actual comparison (if the Mono is in fact empty) is happening. The first thing my IDE jumps to, is the snippet below.
public final Mono<T> switchIfEmpty(Mono<? extends T> alternate) {
return onAssembly(new MonoSwitchIfEmpty(this, alternate));
}
However, onAssembly only calls a static method / value in the Hooks abstract class. That hook "onEachOperatorHook" does seem to use an Functional Interface, but I can't seem to find where this is placed / coded.
The comments also mention pointcuts, but I also don't find any hints into any #Aspect annotated classes, so I assume it's implemented with the Hooks only.
Can anyone point me in the right direction, where the Hooks actually take the information from (supposedly a Lambda) for comparing the two Monos in case of switchIfEmpty?
Many thanks.
The logic is taking place inside SwitchIfEmptySubscriber<T>:
static final class SwitchIfEmptySubscriber<T> extends Operators.MultiSubscriptionSubscriber<T, T> {
final Publisher<? extends T> other;
boolean once;
SwitchIfEmptySubscriber(CoreSubscriber<? super T> actual, Publisher<? extends T> other) {
super(actual);
this.other = other;
}
public void onNext(T t) {
if (!this.once) {
this.once = true;
}
this.actual.onNext(t);
}
public void onComplete() {
if (!this.once) {
this.once = true;
this.other.subscribe(this);
} else {
this.actual.onComplete();
}
}
public Object scanUnsafe(Scannable.Attr key) {
return key == Attr.RUN_STYLE ? RunStyle.SYNC : super.scanUnsafe(key);
}
}
In case of an empty Mono:
onComplete() is triggered
this.once is false since onNext() has not been executed
this.other publisher (the alternative Mono given in switchIfEmpty) gets subscribed

Autowiring interface vs class

If there are more than one implementation of an interface, then I would have to use #Qualifier to indicate which class I want to autowire with. Wouldn't it make more sense to autowire the class directly instead of interface?
This is what object oriented programming (especially abstraction and polymorphism) is about.
You build the classes independendent of concrete implementations and use an interface.
This allows you to change what implementation you use at any point.
Assume you have this:
public interface I{
void doSomething();
}
#Component("a")
public class A implements I{
public void doSomething(){
//...
}
public void doSomethingElse(){
//...
}
}
#Component("b")
public class B implements I{
public void doSomething(){
//...
}
}
If you use
#Autowired
private A yourVariable;
you might be tempted to use the doSomethingElse() method that is an implementation detail (by what reason whatsoever).
However, if you use
#Qualifier("a")
private I yourVariable;
this cannot happen as the method is not present in the interface.
This gives you the ability to swap the implementation at any time.
Wouldn't it make more sense to autowire the class directly instead of interface?
This pretty much depends on how exactly do you work with qualifiers but in general, the answer is "No", autowiring the class is a bad thing to do if you have an interface - you should always work by interface.
Here are the examples:
interface I { void foo(); }
class IImpl1 implements I {
void foo() {System.out.println("Impl1");
pubic void bar() {// another method - why not?}
}
class IImpl2 implements I { void foo() {System.out.println("Impl2"); }
Note, that an implementation IImpl1 has an additional method bar that doesn't belong to the interface I
Case 1:
#Component
public class Driver {
#Autowired
private IImpl1 i;
}
Here class Driver is tightly could to the concrete implementation IImpl1 in general I can call method bar from the Driver class because I have this implementation, but in this case if I'll have to switch the implementation of Driver in future you'll have to also change the code: both change the reference, and also get rid of calls to IImpl1.bar() that might be not that easy to do - its a change in logic. As a result, the whole polymorphic behavior is lost.
By far its the worst way to program.
Now, consider Case 2:
#Component
public class Driver {
#Autowired
#Qualifier("someLogicalName") // under the hood it spring will map it to IImpl1 but you don't know that here
I i;
}
In this case - the things are much better - you never couple the driver to the concrete implementation at the level of code. This means that in general its enough to change the qualifier to get another implementation. You can't call bar anymore - it won't compile.
You also do not know what the implementation will be injected. If in future the implementation of the component that actually implements the logic of "someLogicalName" will change (by that I mean that you'll create a new class IImpl3), you won't feel it here - you'll place that qualifier on that new class and all the places that use it will get that implementation automatically.
Case 3:
#Configuration
public class MyConfiguration {
#Bean
public Driver driver(#Qualifier("someLogicalName") I i) {
return new Driver(i);
}
}
public class Driver {
private final I i;
public Driver(I i) { // in real life this constructor can be generated by
// lombok or something, put it here for the sake of completeness
this.i = i;
}
}
This by far the most "clean" approach - conceptually its really similar to case 2, however in this case you don't place the qualifier at the level of Driver class at all, in fact, the class Driver is not even aware at the level of code / metadata that its related to Spring anyhow. Of course all the "advantages" of case 2 are also applicable here as well.

TypeScript - ReSharper shows error for generic inheritance but project builds fine

After upgrading to ReSharper 10 the following error is shown but it builds without any error.
Class 'BaseTourModule' cannot extend class 'BaseModule': Types of property 'settings' of types 'BaseModule' and 'BaseTourModule' are incompatible
Type parameter 'TSetup' constraint isn't related to 'TSetup'
Type parameter 'TSetup' is incompatible with 'BaseTourModuleSetup', which is not type parameter
Whereas BaseModule is defined as
export abstract class BaseModule<TSetup extends BaseModuleSetup> {
protected settings: TSetup;
}
and BaseModuleSetup
export abstract class BaseModuleSetup {
protected translations: { [index: string]: string; } = {};
abstract isValid(): boolean;
}
The concrete implementation of BaseTourModule (where the error is thrown) is:
export abstract class BaseTourModule<TSetup extends BaseTourModuleSetup> extends BaseModule<TSetup> {
}
Last, but not least, this is the implementation of BaseTourModuleSetup
export abstract class BaseTourModuleSetup extends BaseModuleSetup {
}
I'm using Visual Studio 2015 Professsional and the project is building against ECMAScript 5 using TypeScript 1.6. Is this an error by ReSharper or is there something wrong which I don't see?
That's a bug in ReSharper 10.0. Is already fixed for bugfix update 10.0.1, which will be released relatively soon.
Looks like you used casting in your inheritance, and from what I understood, it should look like this:
export abstract class BaseModuleSetup {
protected translations: { [index: string]: string; } = {};
abstract isValid(): boolean;
}
export abstract class BaseModule extends BaseModuleSetup {
protected settings: TSetup;
}
export abstract class BaseTourModuleSetup extends BaseModuleSetup {
}
export abstract class BaseTourModule extends BaseTourModuleSetup {
}
Anyways, (Without really knowing what your are trying to achieve) it looks like your are over complicating this with class hierarchy.
If you want, you can explain what are your goals and we can build the best class diagram for your needs.

Dependency Injection with Interface implemented by multiple classes

Update: Is there a way to achieve what I'm trying to do in an IoC framework other than Windsor? Windsor will handle the controllers fine but won't resolve anything else. I'm sure it's my fault but I'm following the tutorial verbatim and objects are not resolving with ctor injection, they are still null despite doing the registers and resolves. I've since scrapped my DI code and have manual injection for now because the project is time sensitive. Hoping to get DI worked out before deadline.
I have a solution that has multiple classes that all implement the same interface
As a simple example, the Interface
public interface IMyInterface {
string GetString();
int GetInt();
...
}
The concrete classes
public class MyClassOne : IMyInterface {
public string GetString() {
....
}
public int GetInt() {
....
}
}
public class MyClassTwo : IMyInterface {
public string GetString() {
....
}
public int GetInt() {
....
}
}
Now these classes will be injected where needed into layers above them like:
public class HomeController {
private readonly IMyInterface myInterface;
public HomeController() {}
public HomeController(IMyInterface _myInterface) {
myInterface = _myInterface
}
...
}
public class OtherController {
private readonly IMyInterface myInterface;
public OtherController() {}
public OtherController(IMyInterface _myInterface) {
myInterface = _myInterface
}
...
}
Both controllers are getting injected with the same interface.
When it comes to resolving these interfaces with the proper concrete class in my IoC, how do I differentiate that HomeController needs an instance of MyClassOne and OtherController needs an instance of MyClassTwo?
How do I bind two different concrete classes to the same interface in the IoC? I don't want to create 2 different interfaces as that breaks the DRY rule and doesn't make sense anyway.
In Castle Windsor I would have 2 lines like this:
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>());
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>());
This won't work because I will only ever get a copy of MyClassTwo because it's the last one registered for the interface.
Like I said, I don't get how I can do it without creating specific interfaces for each concrete, doing that breaks not only DRY rules but basic OOP as well. How do I achieve this?
Update based on Mark Polsen's answer
Here is my current IoC, where would the .Resolve statements go? I don' see anything in the Windsor docs
public class Dependency : IDependency {
private readonly WindsorContainer container = new WindsorContainer();
private IDependency() {
}
public IDependency AddWeb() {
...
container.Register(Component.For<IListItemRepository>().ImplementedBy<ProgramTypeRepository>().Named("ProgramTypeList"));
container.Register(Component.For<IListItemRepository>().ImplementedBy<IndexTypeRepository>().Named("IndexTypeList"));
return this;
}
public static IDependency Start() {
return new IDependency();
}
}
I hope you can use service overrides.
Ex.
container.Register(
Component.For<IMyService>()
.ImplementedBy<MyServiceImpl>()
.Named("myservice.default"),
Component.For<IMyService>()
.ImplementedBy<OtherServiceImpl>()
.Named("myservice.alternative"),
Component.For<ProductController>()
.ServiceOverrides(ServiceOverride.ForKey("myService").Eq("myservice.alternative"))
);
public class ProductController
{
// Will get a OtherServiceImpl for myService.
// MyServiceImpl would be given without the service override.
public ProductController(IMyService myService)
{
}
}
You should be able to accomplish it with named component registration.
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassOne>().Named("One"));
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClassTwo>().Named("Two"));
and then resolve them with
kernel.Resolve<IMyInterface>("One");
or
kernel.Resolve<IMyInterface>("Two");
See: To specify a name for the component
Typically DI containers follow Register, Resolve and Release patterns. During the register phase there are two steps. The first is to specify the mapping as you are doing. The second step is to specify the rules which govern which to inject where.
This problem is very common when we try to address Cross cutting concerns using decorators. In these situations, you have multiple classes(decorators) implementing a single interface.
Briefly, we need to implement IModelInterceptorsSelector which allows you to write imperative code that decides which Interceptor to apply to which types or members.
This is elaborately described in the book Dependency Injection in .Net book by Mark Seemann. Look for chapter 9 interception or search for the above interface.
I am not an expert at this, but was searching for the exact same problem and found the ans in the above book.
Hope this helps.
Regards
Dev1

CDI events and generics

I'm trying to send events and do this generically. I mean - create one abstract base DAO class with generic type and fire the event from its method. This should work for all descendants. This works if I define the exact type, but doesn't - if I use generics. What I mean:
AbstractDAO (with generics - doesn't fire the event):
public abstract class AbstractDAO<T extends Persistable> implements Serializable {
#Inject #PostSaveEvent Event<T> postSaveEvent;
public T saveOrUpdate(T object) throws DatabaseException {
T obj = em.merge(object);
postSaveEvent.fire(obj);
}
}
AbstractDAO (no generics, just simple class cast - fires the event):
public abstract class AbstractDAO<T extends Persistable> implements Serializable {
#Inject #PostSaveEvent Event<Polis> postSaveEvent;
public T saveOrUpdate(T object) throws DatabaseException {
T obj = em.merge(object);
postSaveEvent.fire((Polis)obj);
}
}
PolisDAO class, which extends AbstractDAO and defines the generic type:
#Stateless
#Named
#PolisType
public class PolisDAO extends AbstractDAO<Polis> {
// some methods (saveOrUpdate is not overriden!)
}
My observer class:
#Stateless
#Named
public class ProlongationService {
public void attachProlongationToPolisOnSave(#Observes #PostSaveEvent Polis polis) throws DatabaseException {
// ... DO smth with polis object. This is NOT called in the first case and called in the second
}
THis is very strange for me, as "fire()" method for CDI event should define the event type on runtime, not during compilation or deployment... When I debug, I see, that
postSaveEvent.fire(obj);
from the first sample operates exactly with Polis entity. But no event is fired nevertheless...
Upd. I tried the base generic class, but no luck:
#Inject #PostSaveEvent Event<Persistable> postSaveEvent;
Thanks.
This should, in theory, work, however in practice inspecting the type of generic objects at runtime with Java Reflection is, at times, impossible. This is due to type erasure. IIRC the type of the concrete sub class isn't erased, so it should be possible to reconnect this, but I guess the implementation isn't doing this right now.
File this as a bug in the http://issues.jboss.org/browse/WELD issue tracker (if you are using Weld), with the classes you provide as an example and we can try to fix it.
To work around, try injecting the event into the concrete subclass, and passing it as an argument, or using an accessor method, to get it into the abstract super class.

Resources