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.
Related
I have a class which is implements the decorator pattern. I need to check whether a specific class appear in the inheritance chain. Normally, I would just use instanceof.
However, I don't have the class definition during dev time. In other words, I get the class name (as a String) at run time. In this situation, how could I check this given class name appears in the inheritance chain?
Firstly, sounds horrible. Reflection is usually a really bad idea.
Edit: As #Holger points out in the comments, dynamic checking of type hierarchies is also a really bad idea. (Shame there's more than one new language feature coming for that. Ho hum.) Even more generally, keep your type hierarchies flat. But that's a whole new kettle of fish. In my experience, it's reflection that typically (not always, Credit Suisse!) highlights and promotes confusion.
Having said that: You will, of course, need the fully qualified class name (although you could probe a sequence of packages). From there, Class.forName methods will allow you to recover the Class object (though if you are using multiple class loaders, it could get messier). Then you just need Class.isAssignableFrom.
I've been asked this question and am frankly stumped:
Instead of writing abstract methods we could try to fake them with exceptions, like this:
public int someMethod(int someparameter) {
throws new RuntimeException("unimplemented");
}
What would be the purpose of doing this and can anyone provide an example of code for an abstract method that the above is trying to fake? Any help is greatly appreciated. Thank you.
I can think of one (possibly) valid use case: You have an abstract class, and a number of other classes throughout your project that extended it. (Or the abstract class is in an open-source library, so you have no idea what other classes throughout the universe might be extended from it.) Now, you find that it's useful to add new abstract methods to this class. But if you add abstract methods to the class, this breaks every other class that has already extended it, because those classes need to be changed to contain override for the new methods. So I can see how, in some cases, it might be considered more feasible to add them as non-abstract methods and have them throw exceptions just in case a new class that extends it uses the new methods but forgets to write an overriding method. It won't be caught at compile-time, but at least it might be caught during testing.
I'm not sure how legitimate this reason is, since it's also possible to define a new abstract class NewImprovedWhatever that extends the old one, to contain the new methods. That may pose its own maintenance challenges, though. I'm not sure.
I did notice that Java defines an abstract class java.net.SocketImpl, that contains two non-abstract methods, shutdownInput() and shutdownOutput(), whose default implementation is to throw an exception:
protected void shutdownInput() throws IOException {
throw new IOException("Method not implemented!");
}
The comments indicate that they were added in 1.3, so perhaps that's the exact reason it was done this way, i.e. not to require modification of other classes that already extended SocketImpl. But I don't know for sure.
In any case, a design like this would surely be really bad code, if the class were designed that way from scratch. But the nice O-O concepts we learn about in class aren't always so nice in practice when existing code has to be modified.
I have sometimes thrown UnsupportedOperationException from a method whose functionality has not yet been implemented. (There is also a NotImplementedException in Apache Commons which is a subclass of UnsupportedOperationException.) This was always meant as a placeholder and a message to others using the related class or service that the method is not yet complete. Such code never made it to production, however.
The purpose of doing this would be to purposefully write BAD CODE.
If one wants to confuse its readers and want them to feel the agony of going through their code, then one writes such code.
It also shows lack of designing skills in the code.
A poorly written API will have such code.
Don't do that.
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
I'm looking to implement my own set of Exceptions for a projects I am currently working on. The project relies on a core framework with a base framework exception MyFrameworkException (I am also writing this framework).
For any given project I would like to throw several different types of Exceptions and I can't decide between using multiple subclasses or a single subclass with some form of an Enum as a constructor parameter.
In both cases I have:
public class MyFrameworkException extends Exception { /*...*/ }
Option 1:
public class MyProjectBaseException extends MyFrameworkException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
public class SpecificExceptionType1 extends MyProjectBaseException { /*...*/ }
Then, throughout the project I would throw the specific exception for any problem that occurs.
Option 2:
public class MyProjectException extends MyFrameworkException {
public static enum Type {
SpecificType1, SpecificType2, SpecificType3
}
public MyProjectException( Type type ) { /*...*/ }
}
Here I would always throw MyProjectException with the specific enum type for any problem that occurs. I'd provide some mechanism so that a switch statement could be performed on any MyProjectException based on the type enum.
What's the best way to handle exceptions in projects, especially those sharing a common infrastructure? Are the two options above good solutions? Why or why not? And what are any better solutions?
The chief disadvantage to Option 2 (a common exception + enum) is that you lose some of the utility of checked exceptions. A method pretty much has to say simply "something framework-related might go wrong":
public void foo()
throws MyFrameworkException
...rather than "x or y might go wrong":
public void foo()
throws SomethingWentWrongException, SomethingElseWentWrongException
It means a function that may need to handle one framework exception has to be prepared to handle any of them, whereas if you're specific, a function need only be prepared to handle the exceptions that are thrown by the framework methods it calls.
So for me, a hierarchy such as Option 1 (it needn't be quite so flat, if a structure suggests itself) is the way to go. That said, there are people who don't like checked exceptions at all, and for them I suspect the above is not a compelling argument. :-)
Edit And picking up duffymo's point: I've assumed you were talking about exceptions you really did have to create. Absolutely throw standard exceptions wherever it makes sense (which is nearly everywhere). Don't create your own MyFrameworkIllegalArgumentException, for instance, just use IllegalArgumentException (or its various subclasses).
I would go with exceptions extending java.lang.RuntimeException with descriptive class names.
If you have so many business-specific exceptions that this becomes oppressive, it means you're probably doing it wrong.
See Joshua Bloch's advice about favoring standard exceptions.
I wouldn't inherit from a generic MyFrameworkException, as long as you dont provide any functionality in there common to all projects. Else, always extend Exception.
Normally you should throw meaningful exceptions at domain/layer boundaries. So regarding your question, you should go with option 1, having in mind the point above. Option 2 would increase code complexity, as you will always have to check for the exception type to determine what went wrong. Let the exception class speak for itself.
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.