Functional Interface giving error in eclipse - functional-interface

#FunctionalInterface
interface GetQuery {
abstract StringBuilder fetchQuery();
}
I have written code like above but it says not a functional interface. why is that?
Should the functional interface be always inside a class?

Related

Call abstract java class from jruby with a generic

Currently facing an issue while writing a similar java class in Jruby.
Example:
In Java:
public class Client extends ClientConnection<ChannelType> {
//do some stuff
}
In Jruby:
class Client < Java::'package_name'::ClientConnection
//do some stuff
end
Don't know how to pass ChannelType class in Jruby code while rewriting the Client class
The short version is, you can't unfortunately.
The JRuby wiki explains it as such here (https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#beware-of-java-generics):
If a Java class is defined with Java generics, the types are erased during compilation for backwards compatibility. As a result, JRuby will have problems with automatic type conversion. For example, if you have a Map, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.

Calling C# method from C++ code in WP8

I'm interested in calling a C# method from C++ code in Windows Phone 8. I have already learned how to pass a callback function to C++ code from C# via delegate declarations in my C++ code, but I am looking to see if I can do any of the following:
Call certain methods directly from the C++ code. This would involve somehow inspecting the C# object makeup from C++, and seems unlikely to me, but I thought I'd ask you all anyway
Trigger events in the C# code, which can then be handled by C# methods
Use a dispatcher to call C# callbacks in the Main UI thread so that the callbacks can modify UI elements
Use a dispatcher to trigger events in the C# code, (Essentially a merging of the above two points)
In short, I am looking for as many C++ -->C# communication tips as you guys can throw me, I want to learn it all. :)
By getting an object in C# code to implement a Windows RT interface, and passing down a reference to this object, it is possible to do all of the above with a bit of set-up (if I understand correctly - not sure about exactly what you want to do with your Dispatcher examples - you might want to wrap the Dispatcher on the C# side).
Create a Windows Runtime component library.
Define a public interface class in a C++/CX header for the C# to implement (C++ to call) (e.g. ICallback).
Define a public ref class in a C++/CX header for the C++ to implement (C# to call) (e.g. CppCxClass).
Add a method in CppCxClass that passes and stores an ICallback. (A C++ global variable is shown for consiseness, I recommend you review this to see if you can find a better place to store this in your code-base).
ICallback^ globalCallback;
...
void CppCxClass::SetCallback(ICallback ^callback)
{
globalCallback = callback;
}
Reference the WinRT library in your C# code.
C# code: create an instance of CppCxClass using var cppObject = new CppCxClass().
C# code: create a class which implements ICallback (e.g. CSharpCallbackObject).
C# code: pass an instance of CSharpCallbackObject down to C++. E.g. cppObject.SetCallback(new CSharpCallbackObject()).
You can now call C# with globalCallback->CallCsharp(L"Hello C#");. You should be able to extend either ICallback and/or CppCxObject to do the rest of your tasks.
After a lot of headaches trying to figure out the required code, I think it's worth posting the final version here
C++/CX
//.h
[Windows::Foundation::Metadata::WebHostHidden]
public interface class ICallback
{
public:
virtual void Exec( Platform::String ^Command, Platform::String ^Param);
};
//.cpp
ICallback ^CSCallback = nullptr;
void Direct3DInterop::SetCallback( ICallback ^Callback)
{
CSCallback = Callback;
}
//...
if (CSCallback != nullptr)
CSCallback->Exec( "Command", "Param" );
C#
public class CallbackImpl : ICallback
{
public void Exec(String Command, String Param)
{
//Execute some C# code, if you call UI stuff you will need to call this too
//Deployment.Current.Dispatcher.BeginInvoke(() => {
// //Lambda code
//}
}
}
//...
CallbackImpl CI = new CallbackImpl();
D3DComponent.SetCallback( CI);

SWIG: generate additional (hand-rolled) Java class

I'm using SWIG to generate a Java JNI wrapper for my DLL.
As part of it, I want to generate a custom exception class, but I want to provide the complete Java class implementation for my exception class myself.
I can of course just put my Java class in a separate file, but is it possible to embed such a hand-rolled Java class into a SWIG script?
Unless the class is an inner class of some sort you're pretty much left with writing it as a separate file since that's what it needs to be when you come to compile the Java.
I'm slightly puzzled why you would want to write your own pure Java exception class though - the normal thing to do with SWIG would be derive from std::exception, even if it's through a %inline directive and merge the C++ exception hierarchy with the Java one naturally and for free.
There is a workaround you could use if you really want (although I personally would neverdo it) to generate a pure Java class from the SWIG interface though:
%module test
%nodefaultctor MyException;
%typemap(javabody) MyException %{
// Java stuff goes here (or in javacode typemap)
%}
%typemap(javafinalize) MyException ""
%typemap(javadestruct) MyException ""
struct MyException {};
Which generates:
public class MyException {
// stuff goes here
}
But since that is clearly an ugly hack I'd strongly recommend avoiding it entirely and just writing the class like normal in your source distribution.

What is a class interface?

I'm currently working my way through Code Complete and the word "interface" keeps popping up! I'm trying to get my head round what an interface is. Can you define the term? Also what actually makes up a "class interface"?
In general, an interface is simply "what the class looks like to the rest of the world".
For example, this class in Java:
class MyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
could be said to have just the Bar function in its interface. Internally it has a few other members, but they're private, so they're not visible to the outside world.
More commonly, interfaces are also specific types in the language, for example in the following, MyClass implements the interface IMyClass:
interface IMyClass {
public void Bar(string s);
}
class MyClass implements IMyClass {
private string data;
private string Foo() {...}
public void Bar(string s){...}
}
The interface is now expressed in code, so that any time a variable of type IMyClass is expected, an object of type MyClass can be used, because it implements the correct interface.
I think a good way to define an interface is as follows
An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object
The actual implementation from language to language may have funny little differences but the principle holds.
I considered adding implemented interfaces to the list above but left it off because it seemed to be a bit too language specific. I think it's OK though because the end effect is almost the same. Tacking on more interfaces is just adding more methods, fields and properties to the contract.
The interface to a class is its "public face" that other classes can see. It separates the the class's implementation from the way it interacts with other classes. That way different implementations can be swapped out and other classes don't need to know anything about what's behind the interface.
An interface can include both data and function members.
It's external face to the world. Usually the set of public methods (members) it exposes.
Technically however they would be 2 different things
An interface would be a public contract. e.g.
interface ILogger
{
void Log(String str);
}
A class would then 'implement' this interface - in a way saying that it provides this functionality
class ConsoleLogger : ILogger
{
public ConsoleLogger() { ... }
public void Log(String str)
{
Console.WriteLine("Console Logger " + str);
}
// private stuff
}
Users of this service / interface do not have to concern themselves with how it is implemented or who is implementing it? By depending on an interface, the actual implementation can be switched at will.
Interface is definition of set of methods that class can impelement. It's mostly used for interface polymorphism.
A interface is like a class but not quite. It has similar traits like a class but it is not an interface. An interface has a variables and methods, "just like the class but the methods declared in interface are by default abstract (only method signature, no body)".
http://beginnersbook.com/2013/05/java-interface/
Interfaces have two definitions. It depends in what context the term Interface is used.
A Classes Interface refers to all the implemented public methods of a class.
An Interface as a Type. i.e using the keyword interface to declare an Interface.
interface Movable{
moveStraight();
moveLeft();
moveRight();
stop();
}
So now a class, lets say, Car can implement the interface Movable. This is what is know as the contract. If class Car implements interface Movable, Car guarantees to provide implementations for all the methods declared in Movables
declaration.
To conclude, generally an Interface is addressed as a type (definition 2) in a language specific programming context. You will find the first definition on fewer occasions usually in a theoretical or design context.
The classical real life example of an interface is the controls a car.
The break, gas, and wheel would be the interface.
The engine and other mechenical aspects would be the implementation.
These mechanical aspects can change, we wouldn't know because our interface remains the same.
This is the power of an interface, it hides implementation details so we can work on a higher level of abstraction. We can directly use the functionality of the interface usually without worrying about how the code underneath it is implemented.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.