Different ways of Implementing Interface in C# vs Java [duplicate] - java

I am wondering if there is some inline short way of creating a class implementing a interface. Just like there are the anonymous methods but with implementing interfaces.
The problem is:
interface iSomeInterface
{
void DoIt();
}
public void myMethod(iSomeInterface param)
{
...
}
And I would like to use it like this:
object.myMethod(new { override DoIt() { Console.WriteLine("yay"); } } : iSomeInterface);
Any ideas?
Sorry in case its a duplicate.

Sorry, no inline implementation of classes in C#. There are only Anonymous Types, but they don't support adding interfaces (see for example Can a C# anonymous class implement an interface?) (nor they support adding methods or fields... They only support properties).
You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious.

You can create a class that wraps an Action and implements that interface:
public sealed class SomeAction : ISomeInterface
{
Action action;
public SomeAction (Action action) { this.action = action; }
public void DoIt() { this.action(); }
}
This allows you to use it as follows:
object.myMethod(new SomeAction(() => Console.WriteLine("yay"));
This is of course only very practical if you are going to reuse SomeAction, but this is probably the most convenient solution.

That is pretty common in java but there is no way you can do it in C#. You can pass a functions or procedures as parameters though:
public void myMethod(Action act)
{
act();
}
myMethod( () => Console.WriteLine("yay") );
Several (generic) version of Action (procedure with parameters and no return value) and Func (functions with parameters and return value) exist.

Look for the "ImpromptuInterface" NuGet package.
With the combination of this package and ExpandoObject, you can do something like this
//Create an expando object and create & assign values to all the fields that exists in your interface
dynamic sigObj = new ExpandoObject();
sigObj.EmployeeKey = 1234;
//Create the object using "ActLike" method of the Impromptu class
INewSignatureAcquired sig = Impromptu.ActLike<INewSignatureAcquired>(sigObj);

Related

Extend a Java Enum with additional functions

I have an enum from a common Library (it cannot be changed) as a field from a Class.
I need to use that enum values as a switch-case in order to do something accordingly (for example save some data to a database).
This is for a Java 11 micro-service using Spring as a framework.
What I did before knowing the enum has to stay immutable, I avoided an ugly switch case with an overridden abstract function inside the enum like this:
public enum InvoiceStatus {
DRAFT {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.draft(inputMessage);
}
},
VALID {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.valid(eiInvoiceFileMessage);
}
},
NOT_VALID {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.notValid(eiInvoiceFileMessage);
}
};
//+20 more values...
#Autowired
InvoiceFileService invoiceFileService;
public abstract void action(InputMessage inputMessage);
}
and I simply called the enum like this, so with different values from the enum the called function from the service would be different without writing a long switch-case.
invoice.getStatus().action(inputMessage);
Now the new requirement needs the enum to live inside a common library so it can refer to InvoiceFileService class which will be only local to my project.
I tried different options like HashMaps but the code went ugly and un-maintainable.
Is there a clean way to extend the simple enum (with only values definition) and add to it the abstract function to do stuff? maybe java 8 added some new way to do this.
You could create a wrapper enum.
public enum WrappedInvoiceStatus {
DRAFT(InvoiceStatus.DRAFT, this::someAction),
// other values
private WrappedInvoiceStatus(InvoiceStatus status, Action action) {
this.status = status;
this.action = action;
}
private interface Action { // can be one of Java default functional interfaces as well
void doSomething(InputMessage msg);
}
private void someAction(InputMessage msg) {
// behavior
}
// some plumbing required
}
Basically I’m suggesting using wrapping and lambda expressions or method references. The world of functional programming takes some getting used to. Not everyone is a fan. Your mileage may vary.
As others already said, you can not extend the enum at runtime.
But an enum can implement an interface.
So the basic idea is:
You make an interface with the action as sole abstract method:
public interface InvoiceAction {
void action(InputMessage message);
}
Your enum implements that interface
public enum InvoiceStatus implements InvoiceAction {
// ... no other changes needed
}
In all the cases where you only need to use the actual action, change InvoiceStatus to InvoiceAction. This is the most risky change. Make sure to recompile all code.
Because InvoiceAction only has one abstract method, it's a functional interface, and can be implemented with a lambda expression:
invoice.setStatus(msg -> ...);
This change is probably the most invasive change, but it might be the right thing to do - if you need a different action next time, you won't have the same problem as today.
Enum type is not extendable and implicitly final as specified in JLS:-
An enum declaration is implicitly final unless it contains at least one enum constant that has a class body (§8.9.1).
Hence a class could not extends an enum type. However you could use wrapper or adapter pattern to add additional behaviours/fields of the enum. For example:-
#Service
public class SimpleInvoiceFileService implements InvoiceFileService{
private final InvoiceStatus invoiceStatus;
public SimpleInvoiceFileService(InvoiceStatus status){
invoiceStatus = status;
}
#Override
public void draft(InputMessage input){
this.invoiceStatus.action(input);
}
#Override
public void valid(InputMessage input){
this.invoiceStatus.action(input);
}
// Add more methods to InvoiceFileService interface
// as required and override them here.
}
JLS Reference:-
https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.9

Java Hibernate: What would be the better design to get rid of casting

I use Hibernate for persistence.
Suppose I have an entity which contains information about the document and the necessary information for producing it (either printing or sending by email). Just like this:
The problem here is that DocumentInformation holds reference to abstract class DocumentProductionConfiguration not to the subclasses DocumentPrintConfiguration or DocumentEmailConfiguration.
So when I actually need to get appropriate configuration I have two choices: either use instanceof + casting or use visitor pattern to trick Java so that it would actually understand in the runtime which configuration it is dealing with.
Using casting:
public class XmlBuilder{
public XMLMessage buildXmlMessage(DocumentInformation documentInformation){
if(documentInformation.getDocumentProductionConfiguration() instanceOf DocumentPrintConfiguration){
DocumentPrintConfiguration printConfig = (DocumentPrintConfiguration) documentInformation.getDocumentProductionConfiguration();
XMLMessageConfig xmlConfig = handlePrintConfig(printConfig);
}
}
public XMLMessageConfig handlePrintConfig(DocumentPrintConfiguration printConfig){
....build that XMLMessageConfig....
}
}
Using visitor pattern:
I need to add a new interface for XmlBuilder to implement
public interface XmlBuilderVisitor<T> {
T handlePrintConfig(DocumentPrintConfiguration printConfig);
}
public class XmlBuilder implements XmlBuilderVisitor<XMLMessageConfig> {
#Override
public XMLMessageConfig handlePrintConfig(DocumentPrintConfiguration printConfig){
....build that XMLMessageConfig....
}
public XMLMessage buildXmlMessage(DocumentInformation documentInformation){
XMLMessageConfig xmlMessageConfig = documentInformation.getDocumentProductionConfiguration().buildConfiguration(this);
}
}
public abstract class DocumentProductionConfiguration{
public abstract <T> T buildConfiguration(XmlBuilderVisitor<T> visitor);
}
public class DocumentPrintConfiguration extends DocumentProductionConfiguration{
public <T> T buildConfiguration(XmlBuilderVisitor<T> visitor){
return visitor.handlePrintConfig(this);
}
}
Both of these solutions are kinda meh... The first one because it violates open-closed principle (I will need to always maintain these ifs...).
The second one in this sense is better: once you add new configuration, compiler will guide you through the process: first, you will need to implement appropriate method in the configuration itself, then in all the visitor classes. On the other hand, it is pretty awkward that I am basically passing service to the entity...
So I feel like I am treating symptoms rather than the problem. Maybe the design itself needs some changes? But I am not sure how it could be improved...
I would reccomend pushing the "handle" functionality into the DocumentProductionConfiguration and subclasses. So that the DocumentPrintConfiguration would contain a handle function that builds and returns a XMLMessageConfig. Then your XmlBuilder becomes:
public class XmlBuilder{
public XMLMessage buildXmlMessage(DocumentInformation documentInformation){
XMLMessageConfig xmlConfig = documentInformation.getDocumentProductionConfiguration().handle();
}
}

Can enum as singleton extend a class [duplicate]

Having something like this:
public enum Token
{
FOO("foo", "f"),
QUIT("quit", "q"),
UNKNOWN("", "");
...
public parse(String s) {
for (Token token : values()) {
...
return token;
}
return UNKNOWN;
}
}
An abstract class:
abstract class Base
{
private boolean run;
Base() {
run = true;
while (run) {
inp = getInput();
act(inp);
}
}
public boolean act(String s) {
boolean OK = true;
switch (Token.parse(inp)) { /* Enum */
case FOO:
do_foo();
break;
case QUIT:
run = false;
break;
case UNKNOWN:
print "Unknown" + inp;
OK = false;
break;
}
}
return OK;
}
}
And the extender:
class Major extends Base
{
}
What I want is to extend act as in if super does not handle it then try to handle it in Major. E.g. add PRINT_STAT("print-statistics", "ps") - but at the same time let the Base class handle defaults like QUIT.
Is this a completely wrong approach?
What I have done so far is add an interface Typically:
public interface BaseFace
{
public boolean act_other(String inp);
}
And in class Base implements BaseFace:
case UNKNOWN:
OK = act_other(inp);
And in class Major:
public boolean act_other(String inp) {
if (inp.equals("blah")) {
do_blah();
return true;
}
return false;
}
Does this look like a usable design?
And, major question:
Is there some good way to extend the Token class such that I can use the same switch approach in Major as in Base? What I wonder is if there for one is a better design and second if I have to make a new Token class for Major or if I somehow can extend or otherwise re-use the existing.
Edit: Point of concept is to have the Base class that I can easily re-use in different projects handling various types of input.
All enums implicity extend Enum. In Java, a class can extend at most one other class.
You can, however, have your enum class implement an interface.
From this Java tutorial on Enum Types:
Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.
Edit for Java 8:
As of Java 8, an interface can include default methods. This allows you to include method implementations (but not state) in interfaces. Although the primary purpose of this capability is to allow evolution of public interfaces, you could use this to inherit a custom method defining a common behavior among multiple enum classes.
However, this could be brittle. If a method with the same signature were later added to the java.lang.Enum class, it would override your default methods . (When a method is defined both in a class's superclass and interfaces, the class implementation always wins.)
For example:
interface IFoo {
public default String name() {
return "foo";
}
}
enum MyEnum implements IFoo {
A, B, C
}
System.out.println( MyEnum.A.name() ); // Prints "A", not "foo" - superclass Enum wins
Your problem seems a good candidate for the Command Pattern
It is a good practice to use an enum as a logical group of supported actions. IMO, having a single enum to group all supported actions will improve the readability of your code. With this in mind, the Token enum should contain all the supported action types
enum Token
{
FOO("foo", "do_foo"),
QUIT("quit", "do_quit"),
PRINT_STATS("print", "do_print_stats"),
UNKNOWN("unknown", "unknown")
.....
}
Consider creating an interface Actor which defines an a method say act as shown below:
public interface Actor
{
public void act();
}
Instead of having a single Base class that does too may things, you can have one class per supported command for e.g.
public class FooActor implements Actor
{
public void act()
{
do_foo(); //call some method like do_foo
}
}
public class PrintActor implements Actor
{
public void act()
{
print_stats(); //call some print stats
}
}
Finally, there will be a driver code that will take in as input the action to be performed, initialize the appropriate Actor and execute the action by invoking the act() method.
public class Driver
{
public static void main(String[] args)
{
String command; // will hold the input string from the user.
//fetch input from the user and store it in command
Token token = Token.parse(command);
switch(token)
{
case FOO:
new FooActor().act();
break;
case PRINT_STATS:
new PrintActor().act();
break;
....
}
}
}
Such a design will ensure that you can easily add new commands and the code remains modular.
As other say here, You can't extend enum. From design perspective this solution looks like it's too tightly coupled. I would advise to use more dynamic approach for this. You can create some kind of behavior map:
Map<Token, Runnable> behaviors;
This map could be easily modified or replaced. You can even store some sets of those predefined behaviors. In example:
behaviors.get(Token.parse(inp)).run();
(some additional checks are needed here of course)
And last note: in most cases avoid inheritance
You need to factor out an interface. It is, after all, a fairly common practice to always start with an interface, then provide an abstract class to supply some default implementations. If you have an interface, you can make the enum implement the interface.

Equivalent of Java's anonymous class in C#?

I am trying to port an SDK written in java to C#.
In this software there are many "handler" interfaces with several methods (for example: attemptSomethingHandler with success() and several different failure methods). This interface is then implemented and instantiated anonymously within the calling class and passed to the attemptSomething method of the SomethingModel class. This is an async method and has several places where it could fail or calls another method (passing on the handler). This way, the anonymous implementation of attemptSomethingHandler can reference private methods in the class that calls attemptSomething.
In C# it is not possible to anonymously implement an interface. I could explicitly implement a new class, but this implementation would be unique to this calling class and not used for anything else. More importantly, I would not be able to access the private methods in the calling class, which I need and do not want to make public.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
I've been reading up on delegates but this would require passing as many delegates as there are methods in the handler interface (as far as I can tell).
What is the appropriate way to do this in C#? I feel like I'm missing out on a very common programming strategy. There simply must be an easy, clean way to structure and solve this problem.
Using delegates:
void AttemptSomethingAsync(Action onSuccess, Action<string> onError1, Action onError2 = null) {
// ...
}
// Call it using:
AttemptSomethingAsync(onSuccess: () => { Yes(); }, onError1: (msg) => { OhNo(msg); });
Or, using a class
class AttemptSomethingHandler {
Action OnSuccess;
Action<string> OnError1;
Action OnError2;
}
void AttemptSomethingAsync(AttemptSomethingHandler handler) {
// ...
}
// And you call it like
AttemptSomethingAsync(new AttemptSomethingHandler() {
OnSuccess = () => { Yes() };
});
Or events
public delegate void SuccessHandler();
public delegate void ErrorHandler(string msg);
class SomethingModel {
public event SuccessHandler OnSuccess;
public event ErrorHandler OnError1;
public void AttemptSomethingAsync() {
// ...
}
}
// Use it like
var model = new SomethingModel();
model.OnSuccess += Yes;
model.AttemptSomethingAsync();
private void Yes() {
}
In C#, we don't have anonymous types like Java per se. You can create an anonymous type which contains fields like so:
var myObject = new { Foo = "foo", Bar = 1, Quz = 4.2f }
However these cannot have methods placed in them and are only passable into methods by use of object or dynamic (as they have no type at compile-time, they are generated by the compiler AFAIK)
Instead in C# we use, as you said, delegates or lambdas.
If I understand your pickle correctly, you could implement a nested private class like so:
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
var obj = new MyInterface();
obj.Foo();
}
private class MyInterface : IMyInterface
{
public void Foo()
{
// stuff
}
}
}
Now MyClass can create an instance of MyInterface which implements IMyInterface. As commentors have mentioned, MyInterface can access members of MyClass (although you most certainly want to try and stick to using publicly accessible members of both types).
This encapsulates the "anonymous" class (using Java terms here to make it simpler) and also means that you could potentially return MyInterface as an IMyInterface and the rest of the software would be none the wiser. This is actually how some abstract factory patterns work.
Basically, I need to run different code from the calling class depending on what happens in the SomethingModel class methods.
This smells of heavy coupling. Oh dear!
It sounds to me like your particular problem could use refactoring. In C# you can use Events to solve this (note: Can, not should). Just have an Event for each "branch" point of your method. However I must say that this does make your solution harder to envisage and maintain.
However I suggest you architect your solution in a way such that you don't need such heavy coupling like that.
You could also try using a Pipeline model but I'm not sure how to implement that myself. I know that jetty (or is it Netty? the NIO for Java by JBOSS) certainly used a similar model.
You may find that throwing out some unit tests in order to test the expected functionality of your class will make it easier to architect your solution (TDD).
You can use nested classes to simulate anonymous classes, but in order to use nested classes in the same way as Java you will need to pass a reference to the outer class. In Java all nested and anonymous classes have this by default, and only static ones do not.
interface IMyInterface
{
void Foo();
}
class MyClass
{
public void Bar()
{
IMyInterface obj = new AnonymousAnalog(this);
obj.Foo();
}
private class AnonymousAnalog : IMyInterface
{
public void Foo(MyClass outerThis)
{
outerThis.privateFieldOnOuter;
outerThis.PrivateMethodOnOuter();
}
}
...
}

Anonymous interface implementation

I´ve read 'C# anonymously implement interface (or abstract class)' thread for implementing an interface anonymously. But I wondered if this is also possible using .NET 2.0 (NO LINQ) using delegates or any similar approach. I know from JAVA the following possible:
MyClass m = MyMethod(new MyInterface() {
#override
public void doSomething() {...}
}
(I hope I remember well, is a time ago that I used JAVA, but I suppose it was something similar). This might be helpful whenever a method needs an instance of an interface and is called only once so there is no need to create a new class for this single approach.
.NET 2.0 also supported anonymous delegates, it's just that the syntax was a bit more verbose compared to lambdas, and type inference didn't work. And there were no extension methods in C# 2.0 (although you were able to use C# 3.0 and compile against .NET 2.0), which are the basis of LINQ and being able to operate on interfaces.
Compare:
.NET 2.0: delegate(int i) { return (i < 5); }
.NET 3.5: i => i < 5
.NET 2.0 also lacks common generic delegate signatures (Func and Action), but you can also easily define them yourself (for all combinations of parameters you like):
public delegate void Action<T>(T item);
public delegate Tresult Func<T, Tresult>(T item);
So, whatever approach your linked answer used to mimic anonymous interfaces can be represented using .NET 2.0 delegates, at the expense of added verbosity. Making you ask yourself: "is this really that shorter to write?"
[Update]
If your interface is a single method interface, like:
interface IFoo
{
string Bar(int value);
}
class SomeOtherClass
{
void DoSomething(IFoo foo);
}
then you might get rid of it entirely and simply use a delegate instead:
class SomeOtherClass
{
void DoSomething(Func<int, string> bar);
}
new SomeOtherClass().DoSomething(delegate(int i) { return i.ToString(); });
If you have an interface with many methods that you want to be able to implement inline in many different places, you can use something like this:
interface IFoo
{
string GetSomething();
void DoSomething(int value);
}
// conditional compile, only if .NET 2.0
#if NET_2_0
public delegate void Action<T>(T item);
public delegate Tresult Func<Tresult>();
#endif
class DelegatedFoo : IFoo
{
private readonly Func<string> _get;
private readonly Action<int> _do;
public DelegatedFoo(Func<string> getStuff, Action<int> doStuff)
{
_get = getStuff;
_do = doStuff;
}
#region IFoo members simply invoke private delegates
public string GetSomething()
{ return _get(); }
public void DoSomething(int value)
{ _do(value); }
#endregion
}
Which would allow you to pass delegates to the DelegatedFoo class inline:
var delegated = new DelegatedFoo(
delegate() { return ""; }, // string GetSomething()
delegate(int i) { } // void DoSomething(int)
);
Using .NET 4 the C# 4.0 syntax it would look a bit cleaner due to syntactic sweetness of lambdas and named parameters:
var delegated = new DelegatedFoo(
getStuff: () => "",
doStuff: i => { }
);
I know that this may not be exactly what you are hoping for, but if you absolutely have to do it, you can use any of the mocking frameworks available to request an object which implements the interface and then add implementations for the methods. This is a standard practice in TDD.
Also, you can simply use anonymous delegates to achieve most of your needs as per John Skeet's advice in the question your mention.

Categories

Resources