Equivalent of Java's anonymous class in C#? - java

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();
}
}
...
}

Related

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

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);

Call method on template argument without knowing a base class in Java

I would like to write a generic algorithm, which can be instantiated with different objects. The objects are coming from 3rdparty and they have no common base class. In C++, I just write the generic algorithm as a template which takes the particular object as its argument. How to do it in Java?
template <class T>
class Algorithm
{
void Run(T& worker)
{
...
auto value = workder.DoSomething(someArgs);
...
}
};
In C++, I don't need to know anything about the T, because the proper types and availability of methods are checked during compilation. As far as I know,
in Java I must have a common base class for all my workers to be able to call methods on them. Is it right? Is there a way how to do similar stuff in Java?
I can't change my 3rdparty workers, and I don't want to make my own abstraction of all workers (including all types which the workers are using, etc.).
Edit:
Since I want to write the generic algorithm only once, maybe it could be a job for some templating language which is able to generate Java code (the arguments to the code template would be the workers)?
My solution:
In my situation, where I cannot change the 3rdparty workers, I have chosen Java code generation. I have exactly the same algorithm, I only need to support different workers which all provides identical interface (classes with same names, same names of methods, etc.). And in few cases, I have to do a small extra code for particular workers.
To make it more clear, my "workers" are in fact access layers to a proprietary DB, each worker for a single DB version (and they are generated).
My current plan is to use something like FreeMaker to generate multiple Java source files, one for each DB version, which will have only different imports.
The topic to look into for you: generics
You can declare a class like
public class Whatever<T> {
which uses a T that allows for any reference type. You don't need to further "specialize" that T mandatorily. But of course: in this case you can only call methods from Object on instances of T.
If you want to call a more specific method, then there is no other way but somehow describing that specification. So in your case, the reasonable approach would be to introduce at least some core interfaces.
In other words: there is no "duck typing" in Java. You can't describe an object by only saying it has this or that method. You always need a type - and that must be either a class or an interface.
Duck typing isn't supported in Java. It can be approximated but you won't get the convenience or power you're used to in C++.
As options, consider:
Full-on reflection + working with Object - syntax will be terrible and the compiler won't help you with compilation checks.
Support a pre-known set of types and use some sort of static dispatching, e.g a big switch / if-else-if block, a type -> code map, etc. New types will force changing this code.
Code generation done during annotation processing - you may be able to automate the above static-dispatch approach, or be able to create a wrapper type to each supported type that does implement a common interface. The types need to be known during compilation, new types require recompilation.
EDIT - resources for code generation and annotation processing:
Annotation processing tutorial by #sockeqwe
JavaPoet, a clean code generation tool by Square
If you really don't have any way to get it done correctly with generics you may need to use reflection.
class A {
public String doIt() {
return "Done it!";
}
}
class B {
public Date doIt() {
return Calendar.getInstance().getTime();
}
}
interface I {
public Object doIt();
}
class IAdapter implements I {
private final Object it;
public IAdapter(Object it) {
this.it = it;
}
#Override
public Object doIt() {
// What class it it.
Class<?> itsClass = it.getClass();
// Peek at it's methods.
for (Method m : itsClass.getMethods()) {
// Correct method name.
if (m.getName().equals("doIt")) {
// Expose the method.
m.setAccessible(true);
try {
// Call it.
return m.invoke(it);
} catch (Exception e) {
throw new RuntimeException("`doIt` method invocation failed", e);
}
}
}
// No method of that name found.
throw new RuntimeException("Object does not have a `doIt` method");
}
}
public void test() throws Exception {
System.out.println("Hello world!");
Object a = new IAdapter(new A()).doIt();
Object b = new IAdapter(new B()).doIt();
System.out.println("a = "+a+" b = "+b);
}
You should, however, make every effort to solve this issue using normal type-safe Java such as Generics before using reflection.
In Java all your Workers must have a method DoSomething(someArgs), which doesn't necessarily imply that they extend the same base class, they could instead implement an interface Worker with such a method. For instance:
public interface Worker {
public Double DoSomething(String arg1, String arg2);
}
and then have different classes implement the Worker interface:
One implementation of Worker:
public class WorkerImplA implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
Another implementatin of Worker:
public class WorkerImplB implements Worker{
#Override
public Double DoSomething(String arg1, String arg2) {
return null; // do something and return meaningful outcome
}
}
The different WorkerImpl classes do not need to extend the same common base class with this approach, and as of JavaSE 8 interfaces can have a default implementation in any method they define.
Using this approach Algorithm class would look like:
public class Algorithm {
private String arg1;
private String arg2;
public Algorithm(String arg1, String arg2){
this.arg1 = arg1;
this.arg2 = arg2;
}
public void Run(Worker worker){
worker.DoSomething(arg1, arg2);
}
}

How to design Java class(es) that can optionally function as Singleton?

Here's the scenario:
public class A {
public A {}
void doSomething() {
// do something here...
}
}
Right now, the class is setup where you can create multiple instances. But I also see a need where I might want to restrict the class to only one instance, i.e. Singleton class.
The problem is I'm not sure how to go about the design of accomplishing both goals: Multiple instances and one instance. It doesn't sound possible to do in just one class. I imagine I'll need to use a derived class, an abstract class, interface, something else, or some combination.
Should I create class A as a base class and create a derived class which functions as the singleton class?
Of course, the first thing should always be to question the necessity to use singletons. But sometimes, they are simply a pragmatic way to solve certain problems.
If so, the first thing to understand is: there is no solution that can "enforce" your requirements and prevent mis-use, but here is a "pattern" that helps a lot by turning "intentions" into "meaningful" code:
First, I have an interface that denotes the functionality:
interface WhateverService { void foo() }
Then, I have some impl for that:
class WhateverServiceImpl implements WhateverService {
#Override
void foo() { .... }
Now, if I need that thing to exist as singleton, I do
enum WhateverServiceProvider implements WhateverService {
INSTANCE;
private final WhateverService impl = new WhateverServiceImpl();
#Override
void foo() { impl.foo() }
and finally, some client code can do:
WhateverService service = WhateverServiceProvider.INSTANCE;
service.foo()
(but of course, you might not want to directly assign a service object, but you could use dependency injection here)
Such architectures give you:
A clear separation between the core functionality, its implementation and the singleton concept
Guaranteed singleton semantics (if there is one thing that Java enums are really good for ... then it is that: providing fool-proof singletons!)
Full "testability" (you see - when you just use the enum, without making it available as interface ... then you have a hard time mocking that object in client code - as you can't mock enums directly).
Update - regarding thread safety:
I am not sure what exactly you mean with "singleton concept".
But lets say this: it is guaranteed that there is exactly one INSTANCE object instantiated when you use enums like that, the Java language guarantees that. But: if several threads are turning to the enum, and calling foo() in parallel ... you are still dealing with all the potential problems around such scenarios. So, yes, enum "creation" is thread-safe; but what your code is doing ... is up to you. So is then locking or whatever else makes sense.
I think you should take a look at this question:
Can a constructor in Java be private?
The Builder pattern described there could be a somewhat interesting solution:
// This is the class that will be produced by the builder
public class NameOfClassBeingCreated {
// ...
// This is the builder object
public static class Builder {
// ...
// Each builder has at least one "setter" function for choosing the
// various different configuration options. These setters are used
// to choose each of the various pieces of configuration independently.
// It is pretty typical for these setter functions to return the builder
// object, itself, so that the invocations can be chained together as in:
//
// return NameOfClassBeingCreated
// .newBuilder()
// .setOption1(option1)
// .setOption3(option3)
// .build();
//
// Note that any subset (or none) of these setters may actually be invoked
// when code uses the builer to construct the object in question.
public Builder setOption1(Option1Type option1) {
// ...
return this;
}
public Builder setOption2(Option2Type option2) {
// ...
return this;
}
// ...
public Builder setOptionN(OptionNType optionN) {
// ...
return this;
}
// ...
// Every builder must have a method that builds the object.
public NameOfClassBeingCreated build() {
// ...
}
// The Builder is typically not constructible directly
// in order to force construction through "newBuilder".
// See the documentation of "newBuilder" for an explanation.
private Builder() {}
}
// Constructs an instance of the builder object. This could
// take parameters if a subset of the parameters are required.
// This method is used instead of using "new Builder()" to make
// the interface for using this less awkward in the presence
// of method chaining. E.g., doing "(new Foo.Builder()).build()"
// is a little more awkward than "Foo.newBuilder().build()".
public static Builder newBuilder() {
return new Builder();
}
// ...
// There is typically just one constructor for the class being
// constructed that is private so that it may only be invoked
// by the Builder's "build()" function. The use of the builder
// allows for the class's actual constructor to be simplified.
private NameOfClassBeingCreated(
Option1Type option1,
Option2Type option2,
// ...
OptionNType optionN) {
// ...
}
}
Link for reference:
https://www.michaelsafyan.com/tech/design/patterns/builder
I am not sure that this is what you are looking for, but you can use Factory pattern. Create 2 factories, one will always return the same singleton, while the other one will create a new A object each time.
Factory singletonFactory = new SingetonFactory();
Factory prototypeFactory = new PrototypeFactory();
A a = singletonFactory.createA();
A b = singletonFactory.createA();
System.out.println(a == b); // true
A c = prototypeFactory.createA();
A d = prototypeFactory.createA();
System.out.println(c == d); // false
class A {
private A() {}
void doSomething() { /* do something here... */}
}
interface Factory {
A createA();
}
class SingetonFactory implements Factory {
private final A singleton = new A();
public A createA() {
return singleton;
}
}
class PrototypeFactory implements Factory {
public A createA() {
return new A();
}
}

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.

Interfaces in java

Code 1:
public class User1 implements MyInterface
{
#Override
public void doCalculation() { }
}
public class User2 implements MyInterface
{
#Override
public void doCalculation() { }
}
interface MyInterface
{
public void doCalculation();
}
Code 2:
public class User1
{
public void doCalculation() { }
}
public class User2
{
public void doCalculation() { }
}
Here in my Code 1 I have MyInterface which has an empty method doCalculation().
That doCalculation() is used by user1 and user2 by implementing MyInterface.
Where as in my Code 2 I have two different classes with defined doCalculation() method.
In both the cases code1 and code2 I myself have to write the implementation. My method doCalculation() is just an empty method.
So what is the use of MyInterface here?
It only provides me the method name or skeleton (is that the only advantage of interface)?
Or else would I save any memory while using MyInterface?
Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2.
More than that is there any more advantage on using an interface.
Interfaces are used a lot because they are basically a blueprint of what your class should be able to do.
For example, if you are writing a video game with characters, you can have an interface that holds all the methods that a character should have.
For example
public interface Character {
public void doAction();
}
And you have 2 characters, for example an ally and an enemy.
public class Ally implements Character {
public void doAction() {
System.out.println("Defend");
}
}
public class Enemy implements Character {
public void doAction() {
System.out.println("Attack");
}
}
As you can see, both classes implement the interface, but they have different actions.
Now you can create a character which implements your interface and have it perform its action. Depending on if it's an enemy or an ally, it'll perform a different action.
public Character ally = new Ally();
public Character enemy = new Enemy();
And in your main program, you can create a method that accepts any object that implements your interface and have it perform it's action without knowing what kind of character it is.
void characterDoAction(Character char) {
char.doAction();
}
If you would give ally to this method, the output would be:
Defend
If you would give enemy to this method, the output would be:
Attack
I hope this was a good enough example to help you understand the benefits of using interfaces.
There are a lot of advantages of interface driven programming.
What does "program to interfaces, not implementations" mean?
Basically you are defining a contract in an interface and all the classes which implement the interface have to abide by the contract.
Answers to your queries:
1.It only provides me the method name or skeleton (is that the only advantage of interface)?
--> Its not just about providing the method name but also defining what the class implementing the interface can do.
2.Or else would I save any memory while using MyInterface?
--> Nothing to do with the memory
Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2.
--> see the advantages of interface driven programming.
4.More than that is there any more advantage on using an interface.
--> Plenty,specially dependency injection , mocking , unit testing etc.
A very good explanation can be found here when-best-to-use-an-interface-in-java. It really depends on what you're building and how much scalability, code duplications, etc you want/don't want to have.
Many classes use interfaces to perform some function, relying on other programmers to implement that interface respecting the contract that an interface govern. Such classes are, for example, KeyListeners, MouseListeners, Runnable, etc.
For example: JVM knows what to do with a Thread, how to start it, stop it, manipulate it, but it does not know what your Thread should do, so you have to implement the Runnable interface.
Interfaces offer you a level of abstraction which can be leveraged in other classes. For example, if you have an interface called GemetricFigure, in a class that prints girth of a GeometricFigure you could iterate over a list of all GeometricFigures like:
public class Canvas {
private List<GeometricFigure> figures;
public void print() {
for (GeometricFigure figure : figure) {
System.out.println(figure.getGirth());
}
}
}
And if the GeometricFigure has only that method:
public interface GeometricFigure {
public Double getGirth();
}
You wouldn't care how Square or Circle implement that interface. Otherwise, if there were no interface, you could not have a list of GeometricFigures in Canvas, but a list for every figure type.
With the interface approach you can do the following:
List<MyInterface> list = new ArrayList<MyInterface();
list.add(new User1());
list.add(new User2());
for(MyInterface myInterface : list) {
myInterface.doClaculation()
}
This does not work with the second approach. Interfaces are for the code that use your classes - not for your classes themselves.
You can use interfaces in many cases. Also the situation you describes: You needn't to know, which implementation you have.
For example you have anywhere in your code a method, that returns the current singed in user even you don't know if it is User1 or User2 implementation, however that both of them can calculate something by method doCalculation. I add a really dummy example of that situation:
public void dummyExampleCalculation() {
getCurrentUser().doCalculation();
}
public MyInterface getCurrentUser() {
if(...) {
return new User1();
} else {
return new User2();
}
}
That is what Object Oriented Programming is all about.Interfaces are used to perform polymorphism. You said, you can implementations in code2 for both the classes, what if in future there is user3 who needs to doCalculation. You can just implement that interface and write your calculation in your own form.
When you want to provide a basic functionality to all your users abstract classes comes into picture where in you can declare an abstract method do calculation and provide implementation of that basic functionalities which then each user will extend and can doCalculation in their own way.
Interface is like a contract that your implementing class should satisfy. Usually, you will write an interface and make all your other class's implement it with their own implementation.
Example:
interface IExporter {
public void export();
}
public class PDFExport implements IExporter {
public void export(){
//code for PDF Exporting
}
}
public class XLSExport implements IExporter {
public void export(){
//code for XLS Exporting
}
}
public class DOCExport implements IExporter {
public void export(){
//code for DOC Exporting
}
}
Interface in Java is used to impose an implementation rule on classes. That means you can declare the signature of functions in interfaces and then implement these function in various classes by exactly following the function signature.
You can see a clear and realistic example on the following webpage
http://www.csnotes32.com/2014/10/interface-in-java.html

Categories

Resources