All the interfaces in Java like Serializable, Cloneable, Observable etc are suffixed with "-able". However, java.lang.Throwable is not an interface but a class.
I understand the usage of java.lang.Throwable but I cannot understand why it is named in that fashion. Is there a specific reason for this anomaly ?
An interview lost to the dustbins of the internet with James Gosling, an ex-VP of Sun and a main architect of Java explains why the decision was made to make Throwable a class and not an interface. The main reason was because throwables needed to track state:
JDC: Why is Throwable not an interface? The name kind of suggests it should have been.
Being able to catch for types, that is, something like try{}catch (<some interface or
class>), instead of only classes. That would make [the] Java [programming language]
much more flexible.
JG: The reason that the Throwable and the rest of those guys are not interfaces is
because we decided, or I decided fairly early on. I decided that I wanted to have some
state associated with every exception that gets thrown. And you can't do that with
interfaces; you can only do that with classes. The state that's there is basically
standard. There's a message, there's a snapshot, stuff like that — that's always there.
and also, if you make Throwable an interface the temptation is to assign, to make any
old object be a Throwable thing. It feels stylistically that throwing general objects
is probably a bad idea, that the things you want to throw really ought to be things
that are intended to be exceptions that really capture the nature of the exception and
what went on. They're not just general data structures.
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.
It encompasses all the things that can be thrown, in much the way as an interface/abstract classes do. I guess that should be the logic behind having a -able suffix. While this is not a point of argument... you should not, in general, assume anything that ends with able is an interface.
Update
Another example from real life, is in one of my projects... I had to make a (abstract) super class whose subclasses can be cached (in MemcacheD). It abstracted all the logic required to add, delete, update cache. What would be a good name for it? I named it Cacheable. The idea is if it's Cacheable it will be cached.
So, it's just semantics -- nothing to with naming pattern. The only naming pattern Java has are given here: Java Naming Convention
Related
Java 17 has introduced sealed classes which can permit only specific classes to extend them and would otherwise be final
I understand the technical use-case, but can't think of any real life use cases where this would be useful?
When would we want only specific classes to be able to extend a particular class?
In our own projects, if we want a new class to extend the sealed class can't we just add it to the permitted classes? Wouldn't it be better to just not make the class final or sealed in that case to avoid the slight overhead?
On the other hand, while exposing a library for external use how would a sealed class know beforehand which classes it should permit for extension?
sealed classes provide the opposite guarantee to open classes (the default in Java). An open class says to implementors "Hey, you can subclass me and override my non-final methods", but it says to users "I have no idea what subclasses look like, so you can only use my own methods directly". On the flipside, sealed classes are very restrictive to implementors "You cannot subclass me, and you can only use me in these prescribed ways", but very powerful to users: "I know in advance all of my subclasses, so you know that if you have an instance of me, then it must be one of X, Y, or Z". Consequently, adding a subclass to a sealed class is a breaking change.
It may be helpful to think of sealed classes less as "restricted classes" and more as "enums with superpowers". An enum in Java is a finite set of data values, all constructed in advance. A sealed class is a finite set of classes that you set forth, but those classes may have an infinite number of possible instances.
Here's a real-world example that I wrote myself recently. This was in Kotlin, which also has sealed classes, but it's the same idea. I was writing a wrapper for some Minecraft code and I needed a class that could uniformly represent all of the ways you can die in Minecraft. Long story short, I ended up partitioning the death reasons into "killed by another living thing" and "all other death reasons". So I wrote a sealed interface CauseOfDeath. Its two implementors were VanillaDeath (which took a "cause of damage" as its constructor argument, basically an enum listing all of the possible causes) and VanillaMobDeath (which took the specific entity that killed you as its constructor argument).
Since this was clearly exhaustive, I made it sealed. If Minecraft later adds more death reasons, they will fit into one of the two categories ("death by entity" or "death by other causes"), so it makes no sense for me or anyone else to ever subclass this interface again.
Further, since I'm providing very strong guarantees about the type of death reason, it's reasonable for users to discriminate based on type. Downcasting in Java has always been a bit of a code smell, on the basis that it can't possibly know every possible subclass of a class. The logic is "okay, you've handled cases X and Y, but what if someone comes along and writes class Z that you've never heard of". But that can't happen here. The class is sealed, so it's perfectly reasonable for someone to write a sort of pseudo-visitor that does one thing for "death by entity" and another for "death by other", since Java (or Kotlin, in my case) can be fully confident that there are not, and never will be, any other possibilities.
This makes more sense as well if you've used algebraic data types in Haskell or OCaml. The sealed keyword originated in Scala as a way to encode ADTs, and they're exactly what I just described: a type defined as the (tagged) union of a finite number of possible collections of data. And in Haskell and OCaml, it's entirely normal to discriminate on ADTs as well using match (or case) expressions.
I have a number of custom Exception-inheriting classes in my package, which do not differ from their base class. The only purpose I have them is to distinguish one exception cause from the other, when it is thrown. This is how one of my Exception class looks like:
package com.XXX;
/**
* Thrown when query format is invalid.
*/
public class InvalidFormatException extends Exception {
/**
* Public ctor.
* #param m Supplementary message
*/
public InvalidFormatException(final String m) {
super(m);
}
}
The problem is that all classes are absolutely identical, like twins. The only thing which is different is their names. I don't like this situation, since it's an obvious code duplication. In other languages (like PHP, Python, etc.) I would declare these classes on-fly during runtime, but Java doesn't allow this, as well as I understand. Is there any workaround?
You may create a generic class with a code property settable with the controller. This way you can have only one class and instance when thrown.
That said, I don't agree when you say classes are twins. They represent totally different functional exception. Based on the separation of concerns pattern, the current implementation is the correct one. Using my generic class will mix concerns in your class and that should be forbidden.
Moreover, I see you inherit from Exception... I will not explains a lot but you should use RuntimeException for functional exceptions in your application. Look around on the web, there is a lot of literature about it.
The simple answer is "no", you cannot easily declare on the fly classes with Java. That noted, if you really wanted to do this, it is possible, you'll need to study how Java can compile classes at runtime. Another simplification is if all your exception classes are the same, excepting their names, you could define a base Exception class of your own that they extend.
Another thought, what value are you getting from having all these different Exception classes? Are you clients going to handle things differently depending on what Exception's thrown? If not, I'd suggest examining the Exception hierarchy you've created and simplifying.
Then, if you go that far, consider using RuntimeException as well. This might be grounds for a holy war, but if you really don't do anything special with what's thrown, there's not much value in forcing you client to deal with it. See Bruce Eckel's article on the subject for some perspective.
Some classes in the standard Java API are treated slightly different from other classes. I'm talking about those classes that couldn't be implemented without special support from the compiler and/or JVM.
The ones I come up with right away are:
Object (obviously) as it, among other things doesn't have a super class.
String as the language has special support for the + operator.
Thread since it has this magical start() method despite the fact that there is no bytecode instruction that "forks" the execution.
I suppose all classes like these are in one way or another mentioned in the JLS. Correct me if I'm wrong.
Anyway, what other such classes exist? Is there any complete list of "glorified classes" in the Java language?
There are a lot of different answers, so I thought it would be useful to collect them all (and add some):
Classes
AutoBoxing classes - the compiler only allows for specific classes
Class - has its own literals (int.class for instance). I would also add its generic typing without creating new instances.
String - with it's overloaded +-operator and the support of literals
Enum - the only class that can be used in a switch statement (soon a privilege to be given to String as well). It does other things as well (automatic static method creation, serialization handling, etc.), but those could theoretically be accomplished with code - it is just a lot of boilerplate, and some of the constraints could not be enforced in subclasses (e.g. the special subclassing rules) but what you could never accomplish without the priviledged status of an enum is include it in a switch statement.
Object - the root of all objects (and I would add its clone and finalize methods are not something you could implement)
References: WeakReference, SoftReference, PhantomReference
Thread - the language doesn't give you a specific instruction to start a thread, rather it magically applies it to the start() method.
Throwable - the root of all classes that can work with throw, throws and catch, as well as the compiler understanding of Exception vs. RuntimeException and Error.
NullPointerException and other exceptions such as ArrayIndexOutOfBounds which can be thrown by other bytecode instructions than athrow.
Interfaces
Iterable - the only interface that can be used in an enhanced for loop
Honorable mentions goes to:
java.lang.reflect.Array - creating a new array as defined by a Class object would not be possible.
Annotations They are a special language feature that behaves like an interface at runtime. You certainly couldn't define another Annotation interface, just like you can't define a replacement for Object. However, you could implement all of their functionality and just have another way to retrieve them (and a whole bunch of boilerplate) rather than reflection. In fact, there were many XML based and javadoc tag based implementations before annotations were introduced.
ClassLoader - it certainly has a privileged relationship with the JVM as there is no language way to load a class, although there is a bytecode way, so it is like Array in that way. It also has the special privilege of being called back by the JVM, although that is an implementation detail.
Serializable - you could implement the functionality via reflection, but it has its own privileged keyword and you would spend a lot of time getting intimate with the SecurityManager in some scenarios.
Note: I left out of the list things that provide JNI (such as IO) because you could always implement your own JNI call if you were so inclined. However, native calls that interact with the JVM in privileged ways are different.
Arrays are debatable - they inherit Object, have an understood hierarchy (Object[] is a supertype of String[]), but they are a language feature, not a defined class on its own.
Class, of course. It has its own literals (a distinction it shares with String, BTW) and is the starting point of all that reflection magic.
sun.misc.unsafe is the mother of all dirty, spirit-of-the-language-breaking hacks.
Enum. You're not allowed to subclass it, but the compiler can.
Many things under java.util.concurrent can be implemented without JVM support, but they would be a lot less efficient.
All of the Number classes have a little bit of magic in the form of Autoboxing.
Since the important classes were mentioned, I'll mention some interfaces:
The Iterable interface (since 1.5) - it allows an object to participate in a foreach loop:
Iterable<Foo> iterable = ...;
for (Foo foo : iterable) {
}
The Serializable interface has a very special meaning, different from a standard interface. You can define methods that will be taken into account even though they are not defined in the interface (like readResolve()). The transient keyword is the language element that affects the behaviour of Serializable implementors.
Throwable, RuntimeException, Error
AssertionError
References WeakReference, SoftReference, PhantomReference
Enum
Annotation
Java array as in int[].class
java.lang.ClassLoader, though the actual dirty work is done by some unmentioned subclass (see 12.2.1 The Loading Process).
Not sure about this. But I cannot think of a way to manually implement IO objects.
There is some magic in the System class.
System.arraycopy is a hook into native code
public static native void arraycopy(Object array1, int start1,
Object array2, int start2, int length);
but...
/**
* Private version of the arraycopy method used by the jit
* for reference arraycopies
*/
private static void arraycopy(Object[] A1, int offset1,
Object[] A2, int offset2, int length) {
...
}
Well since the special handling of assert has been mentioned. Here are some more Exception types which have special treatment by the jvm:
NullPointerException
ArithmeticException.
StackOverflowException
All kinds of OutOfMemoryErrors
...
The exceptions are not special, but the jvm uses them in special cases, so you can't implement them yourself without writing your own jvm. I'm sure that there are more special exceptions around.
Most of those classes isn't really implemented with 'special' help from the compiler or JVM. Object does register some natives which poke around the internal JVM structures, but you can do that for your own classes as well. (I admit this is subject to semantics, "calls a native defined in the JVM" can be considered as special JVM support.)
What /is/ special is the behaviour of the 'new', and 'throw' instructions in how they initialise these internal structures.
Annotations and numbers are pretty much all-out freaky though.
This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 7 years ago.
How do you name different classes / interfaces you create?
Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.
When this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.
How do you name interfaces and classes in this regard?
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck.
An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc that implements Truck.
When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck. Since only the sub-classes will ever see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No, you see List and ArrayList, and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have a situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface in most cases.
However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.
Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair
I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).
So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.
in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).
Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.
For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).
I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.
The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.
If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List - interface for the "conceptual" object
ArrayList - concrete implementation of interface
LinkedList - concrete implementation of interface
AbstractList - abstract "partial" implementation to assist custom implementations
I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.
I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?
Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I use both conventions:
If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.
But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.
In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).
TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.
If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do?
For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements java.util.Map by wrapping some immutable object and exposing it's data as key/value pairs. In this case the methods put and putAll don't make sense as I have no way to modify the underlying object. So the question is what should those methods do?
Any method that cannot be implemented according to the semantics of the interface should throw an UnsupportedOperationException.
That depends on your business case. 2 options:
Do nothing.
Throw an UnsupportedOperationException.
Use whichever makes more sense. If you do nothing, you are not obeying the contract of the interface. However, throwing a runtime exception can wreak havoc on the calling code. Thus, the decision will have to be made based on how you will be using the class. Another option would be to use a simpler or different interface, if possible.
Do note that the Java library goes the exception route in the specific case of read-only collections.
It was noted below that UnsupportedOperationException is a part of the java collections framework. If your situation is outside of collections, and the semantics bother you, you can roll your own NotImplementedException, or if you are already using commons-lang, you could use theirs.
That read-only collection already provided by Java throw the UnsupportedOperationException during write operations is already an unfortunate design hack. The collection classes should have been written with separate read-only and write-only interfaces that are both inherited by the full read-write interface. Then you know what you're getting.
Your two choices are really only:
Do nothing.
Throw an exception.
Both have disadvantages. In the first case, by having an empty method, you could mislead the programmer into thinking something happened to your data. The second case breaks the whole idea of polymorphism inherent in interfaces.
Note that UnsupportedOperationException is only OK because of the particular property of the Java Collections Framework, that implementations are permitted to "goof off" implementing part of the interface because they're immutable.
So it's fine for put() (assuming all the mutator methods do the same thing), but a Map which throws UnsupportedOperationException from the size() method would just be broken. If you're trying to implement a kind of map which doesn't know how big it is, you may be in trouble (although sometimes you can return Integer.MAX_VALUE).
Also note that the class documentation for UnsupportedOperationException says that it is part of the Java Collections Framework. Outside the collections framework, throwing UnsupportedOperationException is not be expected and could lead to client code that plain doesn't work. Sure, it's a RuntimeException, but just because you can throw it doesn't mean that your method will work if it always does.
Instead you could either refactor the interface (perhaps splitting it in two), or else rethink why this class is claiming to be a Foo when it plainly isn't, since it can't do the things that Foos are defined to be able to do.