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

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.

Related

Typescript best practices : Interfaces versus Classes [duplicate]

In C# there's a quite huge difference between interfaces and classes. Indeed, a class represents a reference-type, so that we can actually create objects modeled on that class, while interfaces are meant to be contracts that a class sign to in order to ensure the existence of a certain behavior. In particular we can't create instances of interfaces.
The whole point with interfaces is to expose behavior. A class implements it by giving one explicit implementation of said behavior.
In that case, although interfaces may contain properties, most of the time we care about interfaces because of behavioral issues. So most of the type, interfaces are just contracts of behavior.
On TypeScript, on the other hand, I've seem something that made me quite uneasy, and in truth I've seen this more than once, which is the reason for this question.
In one tutorial I saw this:
export interface User {
name: string; // required with minimum 5 chracters
address?: {
street?: string; // required
postcode?: string;
}
}
But wait a minute. Why User is an interface? If we think like C#, User shouldn't be an interface. In truth, looking at it, it seems like we are defining the data type User, instead of a contract of behavior.
Thinking like we do in C#, the natural thing would be this:
export class User {
public name: string;
public address: Address;
}
export class Address {
public street: string;
public postcode: string;
}
But this thing of using interfaces like we do with classes, to just define a data type, rather than defining a contract of behavior, seems very common in TypeScript.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#? How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Consider that in Javascript, data is often exchanged as plain objects, often through JSON:
let data = JSON.parse(someString);
Let's say this data is an array of User objects, and we'll pass it to a function:
data.forEach(user => foo(user))
foo would be typed like this:
function foo(user: User) { ... }
But wait, at no point did we do new User! Should we? Should we have to write a class User and map all the data to it, even though the result would be exactly the same, an Object with properties? No, that would be madness just for the sake of satisfying the type system, but not change anything about the runtime. A simple interface which describes how the specific object is expected to look like (to "behave") is perfectly sufficient here.
I also came to Typescript from a C# background and have wondered the same things. I was thinking along the lines of POCOs (is POTO a thing?)
So what interfaces are meant for in TypeScript?
The Typescript Handbook seems to say that interfaces are meant for "defining contracts within your code".
Why do people use interfaces in TypeScript like we use classes in C#?
I agree with #deceze's answer here.
John Papa expands on the subject of classes and interfaces on his blog. He suggests that classes are best suited for "creating multiple new instances, using inheritance, [and] singleton objects". So, based on the intent of Typescript interfaces as described in the Typescript Handbook and one man's opinion, it would appear that classes are not necessary to establish contracts in Typescript. Instead, you should use interfaces. (Your C# senses will still be offended.)
Interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
If I understand the question, you are asking if interfaces should establish contracts of behavior or contracts of structure. To this, I would answer: both. Typescript interfaces can still be used the same way interfaces are used in C# or Java (i.e. to describe the behavior of a class), but they also offer the ability to describe the structure of data.
Furthermore, my coworker got on me for using classes instead of interfaces because interfaces produce no code in the compiler.
Example:
This Typescript:
class Car implements ICar {
foo: string;
bar(): void {
}
}
interface ICar {
foo: string;
bar(): void;
}
produces this Javascript:
var Car = (function () {
function Car() {
}
Car.prototype.bar = function () {
};
return Car;
}());
Try it out
Interfaces in typescript are similar to interfaces in C# in that they both provide a contract. However opposed to C# interfaces which only contain methods typescript interfaces can also describe fields or properties that objects contain. Therefore they can also be used for things which are not directly possible with C# interfaces.
A major difference between interfaces and classes in typescript is that interfaces don't have a runtime representation and there won't be any code emitted for them. Interfaces are very broadly usable. For example you can use object literals to construct objects with satisfy an interface. Like:
let user: User = {
name: 'abc',
address: {
street: 'xyz',
},
};
Or you can assign any data objects (e.g. received through JSON parsing) to an interface (but your pre-checks should assert that it's really valid data). Therefore interfaces are very flexible for data.
On the other hand classes have a type associated at runtime to them and there is code generated. You can check the type at runtime with instanceof and there's a prototype chain set up. If you define User as a class it won't be a valid user unless you call the constructor function. And you can't just define any kind of suitable data to be a User. You would need to create a new instance and copy the properties over.
My personal rule of thumb:
If I'm dealing with pure data (of varying sources) I use interfaces
If I'm modelling something which has an identity and state (and probably attached methods to modify the state) I'm using a class.
How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Interfaces in TypeScript are shape contracts, describing the expected structure of an object. If a value has a certain interface annotation, you expect it to be an object featuring the members defined in the interface. Members can be values or functions (methods). Generally, their behavior (function bodies) is not part of the contract. But you can specify if they are readonly or not.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#?
Typescript interfaces can play the same role as C# interfaces if they are expected to be implemented by TypeScript classes.
But not only a class can implement an interface; any kind of value can:
interface HelloPrinter {
printHello(): void
}
The following object is not a class but nevertheless implements the interface:
{
printHello: () => console.log("hello")
}
Thus we can do
const o: HelloPrinter = {
printHello: () => console.log("hello")
}
and the TypeScript compiler won't complain.
The object implements our interface without forcing us to write a class.
Working with interfaces is more lightweight than working with (interfaces and) classes.
But if you need to know the type name (class/interface name) during runtime then classes are the right choice, because interface names are only known at compile time.
Using only the native deserialization mechanism, you cannot deserialize an instance of a specific class. You can only deserialize into a plain-old-javascript-object. Such objects can adhere to typescript interfaces but cannot be an instance of a class. If you need to deal with data that crosses a serialization boundary such as data expected from a webservice, use interfaces. If you need to generate new instances of such values yourself, just construct them literally or create a convenience function that returns them - objects that adhere to that interface.
A class can itself implement an interface, but it might get confusing if you expect to deal with both locally constructed class instances AND deserialized, reconstituted plain objects. You'd never be able to rely on the class-basis of the object and so there'd be no benefit of also defining it as a class for that exact purpose.
I've had success in creating a ServerProxy module responsible for sending code back and forth from a webservice - the webservice call and the returned result. If you're binding to knockout models or similar, you can have a class that encapsulates the ui-bound model with a constructor that knows how to lift a returned plain-old-javascript-object that adheres to the webservice's interface-only contract into an instance of your model class.

Returning an instance in Java

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.

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.