Returning an instance in Java - interface

We cannot create an instance of an interface.
But why does Arrays.asList(Object[] a) in the Java API, return a List (List being an interface)?
Thank you!

It creates an instance of a class which implements the interface.
You don't know what that class is; it could even use a different class every other Tuesday (it doesn't).
You just use the class through the interface.

Java and OOO programming in general lets you define how an object should be used (that´s the interface of the object) so only the library implementor needs to worry about the gory details of how things actually work. That´s why it is good practice to never return a class itself but just an interface, in addition to better maintanibility it will also let you use mocks or stubs objects when coding tests for your applications.
Java in particular let´s you create an interface implementation on fly. i.e you can do something like
return new List() {
boolean add() {...}
void addAll {...}
...
}
This is of course an overkill for complex interfaces like List but actually very handy for smaller interfaces.

Related

GWT serialization should not return interfaces: what about parameters and contained objects?

There are already a few questions regarding the fact that methods in GWT RPC should not return an interface like List, but rather a concrete class like ArrayList, because otherwise "GWT needs to include all possible implementations". See e.g. In GWT, why shouldn't a method return an interface?
Here's my question: is this limited to the return type itself? How about parameters of the method? And what if the return object contains an interface, e.g.
public class MyReturnObject implements IsSerializable {
List<String> listOfUnspecifiedType1;
List<Long> listOfUnspecifiedType2;
...
}
The examples I have seen all talk of the return type itself. I don't see why it would be a problem to return an interface, but not a problem to return an object which just wraps an interface; but maybe I am missing something?
It's clear from the linked question that it applies recursively (and as soon as you understand why you should use the most derived types as possible, it becomes obvious that it is recursive).
This is also true of method arguments, not only the return types and their fields: if you send a List<X> then GWT has to generate serialization code for all List classes: ArrayList, LinkedList, etc.
And of course the same applies to classes, not only interfaces: AbstractList is no different from List.
And because generation comes before optimization, all possible classes from the source path will be included, not only those that you use in your code; and then they come in the way of the optimization pass, as all those classes are now used by your app.
Therefore, the rule is: use the most specific types as possible. The corollary is: don't fear DTOs, don't try to send your business/domain objects at all cost.

Why doesn't Scala have static members inside a class?

I know you can define them indirectly achieve something similar with companion objects but I am wondering why as a language design were statics dropped out of class definitions.
The O in OO stands for "Object", not class. Being object-oriented is all about the objects, or the instances (if you prefer)
Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism. Simply put, statics aren't object-oriented.
Scala, on the other hand, is object oriented. Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.
They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.
Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated. These things have no place in any well-designed language that wishes to describe itself as object-oriented.
Concerning why it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:
The way I look at it, though, is that singleton objects allow you to
do the static things where they are needed in a very concise way, but
also benefit from inheritance when you need to. One example is it is
easier to test the static parts of your program, because you can make
traits that model those parts and use the traits everywhere. Then in
the production program use a singleton object implementations of those
traits, but in tests use mock instances.
Couldn't have put it better myself!
So if you want to create just one of something, then both statics and singletons can do the job. But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.
In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.
I also posted this question on scala users google group and Bill Venners one of the authors of "Programming in scala" reply had some insights.
Take a look at this: https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/6vZJgi42TIMJ and https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/oTrLFtwGjpEJ
Here is an excerpt:
I think one
goal was simply to be simpler, by having every value be an object,
every operation a method call. Java's statics and primitives are
special cases, which makes the language more "complicated" in some
sense.
But another big one I think is to have something you can map Java's
statics to in Scala (because Scala needed some construct that mapped
to Java's statics for interop), but that benefits from OO
inheritance/polymorphism. Singleton objects are real objects. They can
extend a superclass or mix in traits and be passed around as such, yet
they are also "static" in nature. That turns out to be very handy in
practice.
Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) http://www.artima.com/scalazine/articles/goals_of_scala.html
Here is an excerpt:
First, we wanted to be a pure object-oriented language, where every value is an object, every operation is a method call, and every variable is a member of some object. So we didn't want statics, but we needed something to replace them, so we created the construct of singleton objects. But even singleton objects are still global structures. So the challenge was to use them as little as possible, because when you have a global structure you can't change it anymore. You can't instantiate it. It's very hard to test. It's very hard to modify it in any way.
To Summarize:
From a functional programming perspective static members are generally considered bad (see this post by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.
Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop).
These are the things that pop into my head when I think about how statics could complicate things:
1) Inheritance as well as polymorphism would require special rules. Here is an example:
// This is Java
public class A {
public static int f() {
return 10;
}
}
public class B extends A {
public static int f() {
return 5;
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.f());
B b = new B();
System.out.println(b.f());
A ba = new B();
System.out.println(ba.f());
}
}
If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like #Override annotation, which is of course optional and the friendly "The static method f() from the type A should be accessed in a static way" warning. This leads us to
2) The "static way" of accessing stuff is a further special rule, which complicates things.
3) Static members cannot be abstract. I guess you can't have everything, right?
And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.
It's true, static member don't exists, BUT, it's possible to associate a singleton object to each class:
class MyClass {
}
object MyClass {
}
to obtain similar results
Object oriented programming is all about objects and its states(Not touching state full and stateless objects in Java). I’m trying to stress “Static does not belong to objects”. Static fields cannot be used to represent a state of an object so it’s rational to pull off from objects.

In Scala, plural object name for a container of public static methods?

I've written a Scala trait, named Cache[A,B], to provide a caching API. The Cache has the following methods, asyncGet(), asyncPut(), asyncPutIfAbsent(), asyncRemove().
I'm going to have a few static methods, such as getOrElseUpdate(key: A)(op: => B). I don't want methods like this as abstract defs in the Cache trait because I don't want each Cache implementation to have to provide an implementation for it, when it can be written once using the async*() methods.
In looking at Google Guava and parts of the Java library, they place public static functions in a class that is the plural of the interface name, so "Caches" would be the name I would use.
I like this naming scheme actually, even though I could use a Cache companion object. In looking at much of my code, many of my companion objects contain private val's or def's, so users of my API then need to look through the companion object to see what they can use from there, or anything for that matter.
By having a object named "Caches" is consistent with Java and also makes it clear that there's only public functions in there. I'm leaning towards using "object Caches" instead of "object Cache".
So what do people think?
Scala's traits are not just a different name for Java's interfaces. They may have concrete (implemented) members, both values (val and var) and methods. So if there's a unified / generalized / shared implementation of a method, it can be placed in a trait and need not be replicated or factored into a separate class.
I think the mistake starts with "going to have a few static methods". Why have static methods? If you explain why you need static methods, it will help figure out what the design should be.

What is the base of all interfaces in .net, just like the base for all classes is the object

I would like to pass an interface to a method signature which takes Object as its parameter, so I wonder about this question
public Stream GetViewStream(string viewName, object model, ControllerContext context)
instead of object I shall like to pass an interface Imodel, without modifying the signature. Is there a base class for interfaces?
Also in the new mvc2 is there a way to avoid controllercontext altogether?
I'd only answer the first question - Why there's no common base interface for all interfaces ?
First of all, there's no common pre-defined base interface for all interfaces, unlike the System.Object case. Explaining this can get very interesting.
Let us assume, you could have a common interface for all interfaces in the system. That means, all interfaces will need to force their implementations to provide implementation-details for that common base interface. In general, interface are used to give specific special behaviors to their concrete implementation classes. Obviously you only want to define an interface when you only know what to do and don't know HOW to do that. So, if you let there be a common base interface for all interface and force the implementations to expect them to provide details of how to do it - why would you want to do it ? What common task each class should do that varies from one another ?
Lets look at the other side of the coin, why we have System.object as base class of any .Net type - It is simple it gives you some methods that have COMMON implementation for any .Net type and for those methods that it might vary from type-to-type they have made it virtual ex: .ToString()
There's possibly no assumption of any
system-wide interface method which is
virtual/abstract to all its
implementations.
One common practice of using Interface is say, defining a particular behavior to any type. Like I'd have an interface IFlyable which will give Fly() to all types that implement IFlyable. This way I can play with any Flyable object regardless of its inheritance hierarchy coming into picture. I can write a method like this..
public void FlyTheObject(IFlyable flyingObject)
{
flyginObject.Fly();
}
It does not demand anything from the object but the implementation of the Fly() method.
EDIT
Additionally, All interfaces will resolve to Object because interfaces cannot be instantiated. The object is always of a concrete class that can be instantiated. This class may or may not implement your interface but as we know, any .Net type is ultimately based to System.Object, so you will be able to take the instance into an object type regardless of the fact if it implements a particular interface or not.
No, there is no base class for interfaces. Nor there is base interface for interfaces.
As for your second question (and partly first one) - what are actually you trying to do?
There is no base class for interfaces, but you can pass any interface variable e.g:
private IEnumerable<int> myInterfaceVariable = new List<int>();
to your method because by definition anything that is stored in that variable must be an instance of a class that inherits from the interface - therefore it must be an object.
The following compiles fine:
public class InterfaceAsObject
{
private IEnumerable<int> myInterfaceVariable = new List<int>();
private void CallDoSomething()
{
DoSomething(myInterfaceVariable);
}
private void DoSomething(object input)
{
}
}
Re 1, there is no base interface, but if I understand you correctly, you can achieve what I think you want by just passing your object that implements IModel via the model parameter and cast (and check!) the parameter to IModel. I use 'as' and check for null.
If you don't need total flexibility, a better way of doing this is to define the interface that the model parameter must support. If the specific objects support derived interfaces (e.g. IDerivedModel : IModel) this will work too.
Look up a text-book on polymorphism.

What is an empty interface used for

I am looking at nServiceBus and came over this interface
namespace NServiceBus
{
public interface IMessage
{
}
}
What is the use of an empty interface?
Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.
This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.
#Stimpy77 Thanks! I hadn't thought of it that way.
I hope you'll allow me to rephrase your comment in a more general way.
Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.
Also known as a Marker Interface:
http://en.wikipedia.org/wiki/Marker_interface_pattern
In java Serializable is the perfect example for this. It defines no methods but every class that "implements" it has to make sure, that it is really serializable and holds no reference to things that cannot be serialized, like database connections, open files etc.
In Java, empty interfaces were usually used for "tagging" classes - these days annotations would normally be used.
It's just a way of adding a bit of metadata to a class saying, "This class is suitable for <this> kind of use" even when no common members will be involved.
Normally it's similar to attributes. Using attributes is a preferred to empty interfaces (at least as much as FxCop is aware). However .NET itself uses some of these interfaces like IRequiresSessionState and IReadOnlySessionState. I think there is performance loss in metadata lookup when you use attributes that made them use interfaces instead.
An empty interface acts simply as a placeholder for a data type no better specified in its interface behaviour.
In Java, the mechanism of the interface extension represents a good example of use. For example, let's say that we've the following
interface one {}
interface two {}
interface three extends one, two {}
Interface three will inherit the behaviour of 'one' and 'two', and so
class four implements three { ... }
has to specify the two methods, being of type 'three'.
As you can see, from the above example, empty interface can be seen also as a point of multiple inheritance (not allowed in Java).
Hoping this helps to clarify with a further viewpoint.
They're called "Mark Interfaces" and are meant to signal instances of the marked classes.
For example... in C++ is a common practice to mark as "ICollectible" objects so they can be stored in generic non typed collections.
So like someone over says, they're to signal some object supported behavior, like ability to be collected, serialized, etc.
Been working with NServiceBus for the past year. While I wouldn't speak for Udi Dahan my understanding is that this interface is indeed used as a marker primarily.
Though I'd suggest you ask the man himself if he'd had thoughts of leaving this for future extension. My bet is no, as the mantra seems to be to keep messages very simple or at least practically platform agnostic.
Others answer well on the more general reasons for empty interfaces.
I'd say its used for "future" reference or if you want to share some objects, meaning you could have 10 classes each implementing this interface.
And have them sent to a function for work on them, but if the interface is empty, I'd say its just "pre"-work.
Empty interfaces are used to document that the classes that implement a given interface have a certain behaviour
For example in java the Cloneable interface in Java is an empty interface. When a class implements the Cloneable interface you know that you can call run the clone() on it.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces.
For example
An application of marker interfaces from the Java programming language is the Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.
An empty interface can be used to classify classes under a specific purpose. (Marker Interface)
Example : Database Entities
public interface IEntity {
}
public class Question implements IEntity {
// Implementation Goes Here
}
public class Answer implements IEntity {
// Implementation Goes Here
}
For Instance, If you will be using Generic Repository(ex. IEntityRepository), using generic constraints, you can prevent the classes that do not implement the IEntity interface from being sent by the developers.