Comparing C#'s attributes and Java's marker interfaces - java

Yesterday I came across attributes in C#, the [Serializable] to be precise. As I understand it, they are used like metadata, to provide some information about your class.
Also, I learned that Java has "marker interfaces", the ones with no methods, that serve the purpose of explaining the class, i.e. marking some characteristic of the class, for example the Serializable interface.
I was wondering: can you make a parallel between the two? Are they similar, or even the same?

C# attributes are more like Java annotations. (I believe that's where Java got the idea.)
Marker interfaces are a Java 1.0 construct that are rarely used in new code, if ever. I don't find them to be useful. I would not recommend reviving the practice.
Java interfaces should be for separating declaration of method signatures ("what") from implementation ("how"). They should be like C++ pure virtual classes, not attributes or annotations.

several years ago , Java didn't support attributes. Therefore, to "tag" a class or an interface so that
they could be checked at runtime, you would use marker interfaces,
which is basically an empty interface but you can still check if an instance can be casted to this interface.
In .NET, marker interfaces should not be used except for special use cases (such as allowing the use of extension methods),
because attributes provide a better way to mark classes (and lots more) with metainformation. The same goes for Java 5 and newer,
where annotations were introduced and should be used instead.
Marker interfaces:
1) are a bit easier to check for using dynamic type checks (´obj is IMarker´);
2) allowed for functional and data extensibility in the future (i.e. turning a “marker” interface into a “full” interface that actually declares some members);
3) can be used in generic type constraints;
Attributes:
provide a clearer separation of metadata;
allow for specifying additional information via their constructors or properties;
allow for multiple application to an entity;
are general-purpose in terms of applicability to different kinds of entities, not just classes;
It heavily depends on the particular application's architecture and design whether it's appropriate to use a marker interface or an attribute in a particular case.

Related

Minimizing interfaces in Golang

In golang, interfaces are extremely important for decoupling and composing code, and thus, an advanced go program might easily define 1000s of interfaces .
How do we evolve these interfaces over time, to ensure that they remain minimal?
Are there commonly used go tools which check for unused functions ?
Are there best practices for annotating go functions with something similar to java's #Override, which ensures that a declared function is properly implementing a expected contract?
Typically in the java language, it is easy to keep code tightly bound to an interface specification because the advanced tooling allows us to find and remove functions which aren't referenced at all (usually this is highlighted automatically for you in any common IDE).
Are there commonly used go tools which check for unused functions ?
Sort of, but it is really hard to be sure for exported interfaces. oracle can be used to find references to types or methods, but only if you have all of the code that references you availible on your gopath.
can you ensure a type implements a contract?
If you attempt to use a type as an interface, the compiler will complain if it does not have all of the methods. I generally do this by exporting interfaces but not implementations, and making a constructor:
type MyInterface interface{
Foo()
}
type impl struct{}
func (i *impl) Foo(){}
func NewImpl() MyInterface{
return &impl{}
}
This will not compile if impl does not implement all of the required functions.
In go, it is not needed to declare that you implement an interface. This allows you to implement an interface without even referencing the package it is defined in. This is pretty much exactly the opposite of "tightly binding to an interface specification", but it does allow for some interesting usage patterns.
What your asking for isn't really a part of Go. There are no best practices for annotating that a function satisfies an interface. I would personally say the only clear best practice is to document which interfaces your types implement so that people can know. If you want to test explicitly (at compile time) if a type implements an interface you can do so using assignment, check out my answer here on the topic; How to check if an object has a particular method?
If you're just looking to take inventory of your code base to do some clean up I would recommend using that assignment method for all your types to generate compile time errors regarding what they don't implement, scale down the declarations until it compiles. In doing so you should become aware of the disparity between what might be implemented and what actually is.
Go is also lacking in IDE options. As a result some of those friendly features like "find all references" aren't there. You can use text searching tricks to get around this, like searching func TheName to get only the declaration and .TheName( to get all invocations. I'm sure you'll get used to it pretty quickly if you continue to use this tooling.

When is a reference to the object class required?

What is the function of the class Object in java? All the "objects" of any user defined class have the same function as the aforementioned class .So why did the creators of java create this class?
In which situations should one use the class 'Object'?
Since all classes in Java are obligated to derive (directly or indirectly) from Object, it allows for a default implementation for a number of behaviours that are needed or useful for all objects (e.g. conversion to a string, or a hash generation function).
Furthermore, having all objects in the system with a common lineage allows one to work with objects in a general sense. This is very useful for developing all sorts of general applications and utilities. For example, you can build a general purpose cache utility that works with any possible object, without requiring users to implement a special interface.
Pretty much the only time that Object is used raw is when it's used as a lock object (as in Object foo = new Object(); synchronized(foo){...}. The ability to use an object as the subject of a synchronized block is built in to Object, and there's no point to using anything more heavyweight there.
Object provides an interface with functionality that the Java language designers felt all Java objects should provide. You can use Object when you don't know the subtype of a class, and just want to treat it in a generic manner. This was especially important before the Java language had generics support.
There's an interesting post on programmers.stackexchange.com about why this choice was made for .NET, and those decisions most likely hold relevance for the Java language.
What Java implements is sometimes called a "cosmic hierarchy". It means that all classes in Java share a common root.
This has merit by itself, for use in "generic" containers. Without templates or language supported generics these would be harder to implement.
It also provides some basic behaviour that all classes automatically share, like the toString method.
Having this common super class was back in 1996 seen as a bit of a novelty and cool thing, that helped Java get popular (although there were proponents for this cosmic hierarchy as well).

Questions concerning an interface class

I know this is a question that has been asked a 100 times over but I would like to provide some of my own definitions to see if I understand an interface correctly.
Questions:
What is an interface?
An interface defines the structure for code design. An interface lays the foundation for your design and is made up of a collection of abstract methods and contains behaviors that a class must implement.
When to use an interface?
When similar methods of a design are to be reused across a project. This creates the structure of the behavior within a a project.
Why use an interface?
You use an interface in a project to create the foundation much like the construction of a new home. When a new home is built the frame is built, then the walls and doors and so on are added.
My above answers are what I describe as an interface and would like to know whether I am correct or not? If not, then please explain?
Thanks
You use an interface so that any class can make use of it as long as they implement it. That is why List is so cool and we use it in everyday programming.
Cows and Goats are both animals and they eat, walk, sleep, etc. You do not want to declare the same behaviors separately. If you now have a new animal, you will have to define the similar behaviors again. An interface forces you to implement the required behaviors.
I would argue that an interface is more like a an optional contract -- you specify the method names, parameters, and return type, and if a class chooses to implement the interface, it must then conform to the terms of that contract. It's more like an API spec than a design foundation, as interfaces are relatively flexible.
Note that this flexibility gives you considerable leeway in how you choose to use interfaces. As long as the implementing class provides the agreed-upon methods, the implementation is entirely up to you. There are interfaces (e.g. Serializable) that require no methods, and simply act as markers for the programmer's intent regarding a certain class.
Another use of interfaces is to mitigate the disadvantages of the fact that Java doesn't support multiple inheritance. Though each implementing class must contain the actual code, you might use an interface in an 'inheritance-like' way, to indicate that a certain set of classes derives behavior (in name, if not necessarily in implementation) from some common, more abstract pattern.
I would definitely suggest looking through the javadocs (perhaps the Collections framework) for more examples of interfaces. To continue with the contract analogy, the main use of interfaces is as a sort of API that specifies behavior you can count on, without having to know the implementation details.
The problem with the home analogy is that it's too restrictive-- interfaces don't restrict the design of a class as much as a foundation prescribes a certain structure for a building. Additionally, a building can only have one foundation, and in Java, there is no limit to the number of interfaces a class may implement.
Think of a TV remote analogy.
What
Its a standard way of using a Television(any television...flat screen, CRT, LED, LCD, Plasma etc).
So its basically an interface to a Television. Now, all TV remotes must have some basic common buttons (On, Off, Vol+, Vol-, Ch+, Ch-), these are the methods which should be present in the interface. Different brands implement these using different techs.
When
Now all Television brands want to share this standard way of controlling a Television (which is a big complicated machine).
Why
Think about it. It helps the consumer. As far as the consumer is concerned, he/she does not need to know how to manually operate the Television or from inside(you can do that from the circuit board!)

Interfaces, what if not all implementations use all methods?

I'm fairly new to programming against interfaces and am trying to get it right as a major tool for developing test driven.
Currently we have a lot of Manager classes that all implement a CRUD interface. However some Managers don't yet do updates and some don't do delete, some may never do so.
Not implemented exception?
Is it okay, to just
throw new NotImplementedException()
until the method gets implemented or even for all time if it never does?
(obviously with a source code comment telling the programmer "this method is not supposed to be used, as e.g. Types like 'male' 'female' do never get deleted)?
Split?
Or should I split my CRUD interface into Creatable, Readable(Searchable), Updatable and Deletable? Wouldn't that clutter my class definition?
PersonManager implements Creatable<Person>, Updateable<Person>, Deletable<Person>, Searchable<Person>
Split and combine?
Or should I combine some interfaces like all 4 into CRUD and maybe some other combinations like Read + Update?
Maybe that would also create a load of interfaces where one has to click through a big inheritence path to find out which interface implements all the desired atomic interfaces for the current situation (I need read and create, so which one just implements the two? and this can get a lot more complex quickly)
IMO, for the middle stage - it is OK to use NotImplementedException, until you finish implementing it.
However, as a permanentsolution - I believe it is a bad practice [in most cases].
Instead, I'd create an interface that contains behavior common to all implementing classes, and use subinterfaces to cluster them up for more specific behavior.
The idea is similar to java standard SortedSet, which extends a Set - we wouldn't want to regard Set as SortedSets and give a variable of this type a value of HashSet, instead we use a sub-interface, SortedSet for this purpose.
Generally you would like to throw UnsupportedOperationException which is a runtime exception, clearly mentioning that the requested operation is not supported.
Having loads of interfaces will lead to too many files and also if someone tries to look at them they will get confused. Java docs don't help much either in such cases.
Splitting interface makes sense if there are too many operations for one interface, and not all operations are logically binded together.
For database operation rarely its the case as you will have some basic operation which will be true for most of the scenario.
NotImplementedException doesn't mean that class doesn't support this action. It means it's not implemented, but it will be in the future.
From logical point of view all interface methods must be implemented, and must work well. But if you leave it, and write an application just for yourself, then you will remember about this limitation. In other hand I would be angry that some developer implemented interface and left it unimplemented. So I don't think you can leave interface method not implemented just for future development.
My suggestion is rather to modify interfaces, then use exceptions inside implemented methods.
In frameworks that support covariance and contravariance, it can be very useful to split up interfaces and then define some composite interfaces. For frameworks that do not offer such support, (and even sometimes on frameworks which do) it is sometimes more helpful to have an interface include methods which individual implementations may or may not support (implementations should throw an exception when unsupported actions are attempted); if one is going to do that, one should include methods or properties by which outside code can ask what actions are supported without needing to use any code that will throw an exception.
Even when using interfaces that where support for actions is optional, however, it may sometimes be helpful to define additional interfaces which guarantee that certain actions will be available. Having interfaces which inherit other interfaces without adding new members can be a good way to do this. If done properly, the only extra work this will require on behalf of implementations is to make sure they declare themselves as the most specific type applicable. The situation for clients is a little more complex: if clients' needs can be adequately expressed in the type system, clients can avoid the need for run-time type-checking by demanding specific types. On the other hand, routines that pass instances between clients may be complicated by some client's demands for more specific type than the instance-passing code itself would otherwise require.

Why does the Collections class contain standalone (static) methods, instead of them being added to the List interface?

For all the methods in Collections that take a List as their first argument, why aren't those methods simply part of the List interface?
My intuition is: given a List object, that object itself should "know" how to perform on itself operations such as rotate(), shuffle(), or reverse(). But instead, as a Java programmer, I have to review both the methods in the List interface, as well as the static methods "over there" in the Collections class, to ensure I'm using a canonical solution.
Why were some methods placed as static standalone methods in the Collections class, instead of being added to the List interface (and presumably thus implemented by some existing or would-be base class)?
I'm trying to better understand the design decisions behind the Java collections framework.
Is there some compelling OO design principle here that I'm overlooking? Or was this distinction done simply for some practical, performance reason?
The point is that given suitable primitive operations (remove, set etc) a bunch of more high level operations (sort, shuffle, binary search) can be implemented once rather than being implemented by every single list implementation.
Effectively, java.util.Collections is like .NET's Enumerable class - full of general purpose methods which can work on any collection, so that they can share a single implementation and avoid duplication.
Rational Behind the List Interface's Methods
The List interface is a very core part of the Java runtime and is already a little onerous to fully implement all of the members when rolling out your own List implementations. So, adding extra methods that aren't directly related to the definition of a list is a bit extraneous. If you need those methods on a List implementation, why not subclass the interface and then require them?
If you where going to come along say in version 1.3 and add functionality to the List interface by adding new utility methods, you will break all past implementors of the interface.
From a Domain-Driven Design perspective, the utility methods in Collections are not part of the normal domain of a list.
Regarding OO design principals, I think it would be important to make the distinction between application OO design and language runtime OO design.
The authors of Java may do things very differently now that they have hindsight and perspective of many years of usage of the API. That said the C# IList interface is quite similar to Java's and C#'s authors did have the perspective.
It's certainly a judgement call at some level. I think the main trade-off to consider is this: When you add a method to an interface, every implementer of that interface must write code to implement it.
If the semantics of that method are such that different implementations of the interface will best implement those semantics in very different ways, then it's better to put it in the interface. (Of course, if the semantics simply can't be defined in terms of other methods in the interface, then it must be its own method in the interface.)
On the other hand, if the semantics are such that they can be defined in terms of other methods in the interface, and implementers of the interface will just tend to write the same code over and over again, then it's better to make a utility method that takes an instance of the interface as an argument.
They are utility methods and not core List functionality. The List interface would just get bloated if you added every possible operation you could do on a List. And the operations in Collections do not need to know about the internals of a List, they operate on the public interface so can happily live in an external class.
There are two explanations here:
Historical: Collections class was created after List interface. Designers chose to preserve backward compatibility of already existing interface. Otherwise a lot of developers would have to change their code.
Logical: The methods you are talking about do not require internal knowledge on List implementation and can be implemented over ANY collection implementing it.

Categories