Dependency Injection - Proper use of interfaces? [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been reading about DI and best practices, and still haven't found the answer to this question. When should I use interfaces?
Some developers suggest to add interface for every object that is being injected. This would make a modular application.
Some other are against this.
So my question is which one is correct?
EDIT:
Below are the two sides, I still don't see the advantage of using interfaces. In both cases I can easily mock classes, and change the implementations
Using interfaces
bind(IUserStorage.class).to(UserStorage.class);
// Unit test
bind(IUserStorage.class).to(Mock(UserStorage.class));
Not using interfaces
bind(UserStorage.class).to(UserStorage.class);
// Unit test
bind(UserStorage.class).to(Mock(UserStorage.class));

I can't believe using interfaces is againt OOP principles!
I would definitely use interfaces in this scenario. It means you're loosely coupling your components and can easy mock and/or substitute alternatives. Lots of DI frameworks will use the interfaces in order to provide additional functionality (e.g. create proxy objects mapped to the real objects, but with additional features).
As such I would try and use interfaces for all but the most trivial of injected objects. At some stage you're going to want to make use of substitutability, framework code generation etc. and retrofitting interface usage is an additional pain that it's easy to avoid at the beginning of a project.

Interface based design is the cornerstone of IoC, here is a short description of Interface-based design (Sorry that I'm referencing my own blog, but I just finished an article about this, it was an extract from my MS Thesis):
Nandigam et al. defines Interface-based design as "a way of developing
object-oriented systems where one consciously and proactively defines
and uses interfaces wherever possible in a design to reap the benefits
of designing with interfaces" [Nan09]. Applications with an
interface-based design follow the principle "program to an interface,
not an implementation". This principle brings the following benefits
to the resulting system [Dav03]: flexibility (describes the system
robustness to change), extensibility (the ease with which a system may
accommodate additions) and pluggability (the ability that allows
substitutions of objects with identical interfaces at run-time).
Once you mix interface design with IoC you obtain the following benefits:
Tasks are decoupled from the implementation.
Increases modularity where modules rely on other modules solely on their contracts (interfaces).
Increases pluggability and replacing a module does not have a cascading effect on other modules.
To answer your question, I would use interfaces for different types of modules. For example, one per service or repository.
I do not create interfaces for controllers or Model classes (MVC apps).
All this, as a side effect, facilitates testing.

If you use interfaces or at least abstract/inheritable classes you can change the behaviour of the program by an easy exchange of the implementation (inject another class) in the DI/IoC config.
Using interfaces is a good practice (imho). This is especially very important if you are writing UnitTests which needs mocks. It is much harder to write UnitTests with a good coverage (not to say impossible in most "real world" cases) if you're not using interfaces.
I think you should use an interface if there might be a chance that the injected part could change. It should be easy to extend your implementation, see Open-Closed-Principle. => This will require the exchange of modules/parts/implementations... ask yourself what would happen if your class has no virtual functions to override and you are forced to change the implementation.
I would use interfaces at least for the public classes / parts of your code (the parts other programmers would use).
Having a look at your sample. The problem is at the wiring part and not only the binding of a class as (default) implementation of an interface (binding works, but wiring could break).
For example if you have 2 implementations (C# sample here, should be the same in Java etc., too):
public interface IUserStorage
{
void Write(object something);
}
public class UserStorageTextFile : IUserStorage
{
public void Write(object something) { ... }; // stores to text file
}
public class UserStorageDB : IUserStorage
{
public void Write(object something) { ... }; // stores to DB
}
public class MyStorageClient
{
public MyStorageClient(IUserStorage storage) { ... } // copy to private field and use it etc.
}
Depending on your IoC it should be easy to wire
an instance of MyStorageClient to your binding of IUserStorage.
bind(IUserStorage.class).to(UserStorageDB.class); // Java sample, eh?
But if your MyStorageClient is strongly forced to use DB already...
public class MyStorageClient
{
public MyStorageClient(UserStorageDB storage) { ... } // copy to private field and use it etc.
}
... it is imposible to wire it up with the UserStorageTextFile class except the UserStorageTextFile is inherited from UserStorageDB... but why should you have a dependency to e.g. Oracle drivers (required by UserStorageDB) if you only want to write a simple text file?
I think the sample is clear enough and shows up the benefits of using interfaces...
but if not... try to do this:
bind(UserStorageDB.class).to(UserStorageTextFile.class);
// and in another config/module/unitTest
bind(UserStorageTextFile.class).to(Mock(UserStorageDB.class));
// and try to wire it against your client class, too (both ways, meaning one config for TextFile and load a config for the DB after changing only the configuration)

Your question states "some developers [are for this]" and "some developers [are against this]", so there is no right answer. But this is why I agree that interfaces are overused
If you are creating a library, choosing when to use interfaces is important. It is harder to create a maintainable contract when you don't control how your code is consumed.
If, however, you are creating an application, it less likely to require an interface, because the public interface of a class can serve as the maintainable contract to consuming code. Let's say version 1 looks like this:
public class UserStorage
{
public void Store(User user) { /* ... */ }
}
You don't even need refactoring tools to change it to this:
public interface UserStorage
{
public void Store(User user);
}
class TheImplementation implements IUserStorage
{
public void Store(User user) { /* ... */ }
}
Then you can easily use refactoring tools to rename the interface to IUserStorage.
So when you are writing non-library code, you can usually get away with a class until you need swappable implementations, decorators, etc. You should use an interface when the public interface of the class does not suit your needs. (For example, see the interface segregation principle)
In short - having an interface that is 1:1 with a class is unnecessary indirection in application code.

Related

What's the pattern name for wrapping access to static methods/variables?

Following on from the question How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?, how would you describe the following pattern which I've needed to implement on several occasions?
The scenario is that I'm referencing a static method or variable from a third-party class, but I want to hide it behind an interface so that I can mock it for testing.
For example, in Java the commons-lang library has a SystemUtils class with constants IS_OS_WINDOWS etc. I want to run tests which are independent of the underlying OS and mimic various OSs, so I wrap access to the constant as follows:
interface ISystemUtils {
boolean isOsWindows();
}
class SystemUtilsImpl implements ISystemUtils {
#Override
public boolean isOsWindows() {
return SystemUtils.IS_OS_WINDOWS;
}
}
Is this a Proxy, a generic "wrapper", or something else?
This is called a Facade:
A facade is an object that provides a simplified interface to a larger
body of code, such as a class library. A facade can:
make a software library easier to use, understand and test, since the
facade has convenient methods for common tasks;
make the library more readable, for the same reason
reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system
wrap a poorly designed collection of APIs with a single well-designed API.
The Facade pattern is a good answer, although I do agree that it normally (in my experience at least) expose a number of different operations/classes. With that said, a number of other patterns can also serve the same purpose - Proxy would likely be my first choice, but Adaptor or Mediator could also be a good fit. Another term for this that you may also come across is a "delegate".

Scala testable code with inheritance and mixins

I've developed a lot of code in Java and dabbled in Groovy and Haskell which has now led me to Scala.
I feel relatively comfortable with the functional side of Scala, but I'm finding myself a bit shaky on object oriented design in Scala, because it feels a bit different to Java, in particular due to traits/mix-ins.
I aim to write code that is as testable as possible, which in my Java development has always translated into focus on
Immutability where possible
Prefer injection of state by constructors
ALWAYS go for composition instead of inheritance (heavily influenced by, and likely an over-reaction to this post on SO)
Now I'm trying to land on my feet in this new Scala territory, and I'm having a hard time figuring out what approach I should go for here, in particular whether I should start using inheritance for some purposes.
Programming Scala (Wampler and Payne; O'Reilly, 2nd Edition) has a section with considerations ("Good Object-Oriented Design: A Digression"), and I've read a number of posts on SO, but I haven't seen explicit mentions of the design consideration of testability. The book offers this advice on using inheritance:
An abstract base class or trait is subclassed one level by concrete classes, including case classes.
Concrete classes are never subclassed, except for two cases:
Classes that mix in other behaviors defined in traits (...)
Test-only versions to promote automated unit teting.
When subclassing seems like the right approach, consider partitioning behaviors into traits and mix in those traits instead.
Never split logical state across parent-child type boundaries.
Some digging on SO also suggests that sometimes mix-ins are preferable to composition.
So in essence I have two questions:
Are there common cases where it would be better, even considering testability, to use inheritance?
Do mix-ins offer good ways to enhance the testability of my code?
The trait usage in the Q/A you referenced was really dealing with the flexibility provided by mixing in traits.
In example, when you extend a trait explicitly the compiler locks the types of the class and the super-class at compile time. In this example MyService is a LockingFlavorA
trait Locking { // ... }
class LockingFlavorA extends Locking { //... }
class MyService extends LockingFlavorA {
}
When you used a typed self reference (as shown in the Q/A you pointed to):
class MyService {
this: Locking =>
}
.. the Locking can refer to Locking itself, or any valid subclass of Locking. The author then mixes in the locking implementation at the call site, without explicitly creating a new class for that purpose:
val myService: MyService = new MyService with JDK15Locking
I think when they say you can ease testing, they're really talking about using this functionality to emulate what we Java developers would normally do with composition and mock objects. You simply make a mock Locking implementation and mix that one in during test, and make a real implementation for runtime.
To your question: is this better or worse than using a mocking library and dependency injection? It would be hard to say, but I think in the end a lot of it is going to come down to how well one technique or the other plays with the rest of your codebase.
If you're already using composition and dependency injection to good effect, I would reckon that continuing with that pattern may be a good idea.
If you're just starting out and don't really have the need for all that artillery yet, or haven't philosophically decided that dependency injection is right for you, you can get you a lot of mileage from mixins for a very small cost in runtime complexity.
I think the true answer will prove to be highly situational.
TL;DR below
Question 1) I think it's a situationally useful alternative to composition/dep-inj, but I don't think it provides any major gain other than perhaps simplicity.
Question 2) Yes it can improve testability, largely by emulating mock objects via trait implementations.
I have made could experience using a combination of mix-ins and composition.
so by example use component to mixin behaviour into a specific trait. The example below shows a structure using multiple dao layer traits in a class.
trait ServiceXXX {
def findAllByXXX(): Future[SomeClass]
}
trait ServiceYYY {
def findAllByYYY(): Future[AnotherClass]
}
trait SomeTraitsComponent {
val serviceXXX: ServiceXXX
val serviceYYY: ServiceYYY
}
trait SomeTraitsUsingMixing {
self: SomeTraitsComponent =>
def getXXX() = Action.async {
serviceXXX.findAllByXXX() map { results =>
Ok(Json.toJson(results))
}
}
def getYYY() = Actiona.async {
serviceYYY.findAllByYYY() map {results =>
Ok(Json.toJson(results))
}
}
}
After that you can declare a concrete component and bind it by example to the companion object:
trait ConreteTraitsComponent extends SomeTraitsComponent {
val serviceXXX = new ConcreteServiceXXX
val serviceYYY = new ConcreteServiceYYY
}
object SomeTraitsUsingMixing extends ConreteTraitsComponent
Using this pattern yo could easily create a test component and using mock to test the concrete behaviour of your tait/class:
trait SomeTraitsComponentMock {
val serviceXXX = mock[ServiceXXX]
val serviceYYY = mock[ServiceYYY]
}
object SomeTraitsUsingMixingMock extends SomeTraitsComponentMock
And in you spec you could declare control the results of the services using ScalaMock http://scalamock.org/

Java Interface Naming Conventions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I work on a Java web-app that uses Spring for dependency injection and JMock for mocking out these dependencies in our unit tests.
Currently our team is at a point were we have a few different opinions in terms of how to name certain interfaces that we use. We have no issue with naming the interfaces in our domain that have multiple implementations, that is simple. However, when it comes to interfaces for which we only have one implementation and intend on only having one implementation in the future, we have hit a snag.
The reason that we have such interfaces is purely for mocking, for example, we have services and repositories that we mock out in our unit tests and these services will be named "DocumentMappingService" or for repositories "EmployeeRepository". At the moment some of the guys just prefix the associated interface name with an "I", i.e. "IDocumentMappingService" and "IEmployeeRepository". Others name the interface as I have above and then append an "Impl" after the interface name for the implementing class.
The third "faction" feels that both of these options are poor. Looking at literature such as the well-known "Growing object-oriented software, guided by tests" would lead one to believe that both of the before-mentioned options are poor and that the interface name should clearly define the contract and the implementing classes name should clearly specify how that contract has been implemented. We have found this quite difficult to do in the case I have mentioned above though.
I was hoping that someone out there has had a similar issue before and has some suggestions ito which option is the best and why. Also, if you think that the "I" and "Impl" options are both poor, then please suggest a specific alternative convention.
There's no "one" correct answer here. Naming is quite subjective but what matters the most is that it should be consistent throughout the code base. I would just like to add (to #fge's answer) some more options for you:
Making the Interfaces more generic.
EmployeeRepository implements Repository
DocumentMappingService implements MappingService
Calling your single implementations "defaults".
DefaultEmployeeRepository implements EmployeeRepository
DefaultDocumentMappingService implements DocumentMappingService
Calling your base implementations (if, sometimes extended) as "support".
EmployeeRepositorySupport implements EmployeeRepository
DocumentMappingServiceSupport implements DocumentMappingService
I come across these naming conventions a lot when using the Spring Framework.
Edit : In response to user nyxz's comment about the -Base or Base- convention.
Like I said before, naming is subjective and there's nothing wrong with using the Base nomenclature as such. But, personally, I don't prefer using it. Here's why:
If your implementations would mostly be used directly, then the code instantiating the classes leaves an impression of breaking the OOP hierarchy. That perhaps a specific derived class should have been instantiated.
If your implementations would mostly be extended from, then the word Base becomes redundant in a way. You're extending from it so, of course, it's a base class. Duh!
The 2nd point mostly applies to peripheral classes in your project. Extension points that you provide when you're publishing a framework or library to be used and extended in other projects.
On the other hand, a good use case for using the Base terminology would be for classes internal to your framework that factor common functionality out of other peripheral classes. Since, these classes aren't supposed to be instantiated directly, they are marked abstract, which is in line with the 1st point.
Here's the Adapter hierarchy from the Android framework as an example:
Interface hierarchy.
public interface Adapter
public interface ListAdapter extends Adapter
public interface SpinnerAdapter extends Adapter
The abstract Base class that factors out the common behaviour and interface implementations.
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter
Peripheral classes that are mostly instantiated but sometimes extended by an Android application.
public class SimpleAdapter extends BaseAdapter implements Filterable
public class ArrayAdapter<T> extends BaseAdapter implements Filterable
An answer to such a question can only reflect the tastes of the person who answers... So these are my tastes:
I hate the initial I. It brings nothing of value to the picture. It reminds me of the Hungarian notation where float variables were to be suffixed with _f or the like. No.
The Impl suffix is good enough. But on the other hand, it sounds weird.
I'd suggest two alternate proposals for a given interface Foo:
create a single implementation but not with the Impl suffix; find a more "appealing" name. For instance, TheOnlyOneFoo;
create a factory with an appended s: Foos. Then, a Foo instance would be a Foos.newInstance(whatever, args).
I prefer the second solution, for two reasons:
it can hide the fact that the real implementation has an ugly name;
it can be extended easily when you realize one day that "no, after all, there is more than one implementation for that": just add another static factory method; and if the only existing method in existence sounds too generic, you can just mark it as #Deprecated.
It could even be used in a manner so that all Foo implementations are package local, or even private to the factory. But stack traces would look worse...
No real solution there ;)
edit: as for mocking:
I'd recommend mockito. Really. It is very easy to use, and very powerful.
If those are "one-implementation classes" you are dealing with, maybe there is a better alternative in the JDK itself? What is it that you want to do exactly? The JDK has hidden treasures...
And as a final note... Have you considered the builder pattern?

Any good examples of inheriting from a concrete class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Background:
As a Java programmer, I extensively inherit (rather: implement) from interfaces, and sometimes I design abstract base classes. However, I have never really felt the need to subclass a concrete (non-abstract) class (in the cases where I did it, it later turned out that another solution, such as delegation would have been better).
So now I'm beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate. For one thing, the Liskov substitution principle (LSP) seems almost impossible to satisfy for non-trivial classes; also many other questions here seem to echo a similar opinion.
So my question:
In which situation (if any) does it actually make sense to inherit from a concrete class?
Can you give a concrete, real-world example of a class that inherits from another concrete class, where you feel this is the best design given the constraints? I'b be particularly interested in examples that satisfy the LSP (or examples where satisfying LSP seems unimportant).
I mainly have a Java background, but I'm interested in examples from any language.
You often have a skeletal implementations for an interface I. If you can offer extensibility without abstract methods (e.g. via hooks), it is preferable to have a non-abstract skeletal class because you can instantiate it.
An example would be a forwarding wrapper classes, to be able to forward to another object of a concrete class C implementing I, e.g. enabling decoration or simple code-reuse of C without having to inherit from C. You can find such an example in Effective Java item 16, favor composition over inheritance. (I do not want to post it here because of copyrights, but it is really simply forwarding all method calls of I to the wrapped implementation).
I think the following is a good example when it can be appropriate:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
Another good example is inheritance of exceptions:
public class IllegalFormatPrecisionException extends IllegalFormatException
public class IllegalFormatException extends IllegalArgumentException
public class IllegalArgumentException extends RuntimeException
public class RuntimeException extends Exception
public class Exception extends Throwable
One very common case I can think of is to derive from basic UI controls, such as forms, textboxes, comboboxes, etc. They are complete, concrete, and well able to stand on their own; however, most of them are also very basic, and sometimes their default behavior isn't what you want. Virtually nobody, for instance, would use an instance of an unadulterated Form, unless possibly they were creating an entirely dynamic UI layer.
For example, in a piece of software I wrote that recently reached relative maturity (meaning I ran out of time to focus primarily on developing it :) ), I found I needed to add "lazy loading" capability to ComboBoxes, so it wouldn't take 50 years (in computer years) for the first window to load. I also needed the ability to automatically filter the available options in one ComboBox based on what was shown in another, and lastly I needed a way to "mirror" one ComboBox's value in another editable control, and make a change in one control happen to the other as well. So, I extended the basic ComboBox to give it these extra features, and created two new types: LazyComboBox, and then further, MirroringComboBox. Both are based on the totally serviceable, concrete ComboBox control, just overriding some behaviors and adding a couple others. They're not very loosely-coupled and therefore not too SOLID, but the added functionality is generic enough that if I had to, I could rewrite either of these classes from scratch to do the same job, possibly better.
Generally speaking, the only time I derive from concrete classes is when they're in the framework. Deriving from Applet or JApplet being the trivial example.
This is an example of a current implementation that I'm undertaking.
In OAuth 2 environment, since the documentation is still in draft stage, the specification keeps changing (as of time of writing, we're in version 21).
Thus, I had to extend my concrete AccessToken class to accommodate the different access tokens.
In earlier draft, there was no token_type field set, so the actual access token is as follows:
public class AccessToken extends OAuthToken {
/**
*
*/
private static final long serialVersionUID = -4419729971477912556L;
private String accessToken;
private String refreshToken;
private Map<String, String> additionalParameters;
//Getters and setters are here
}
Now, with Access tokens that returns token_type, I have
public class TokenTypedAccessToken extends AccessToken {
private String tokenType;
//Getter and setter are here...
}
So, I can return both and the end user is none the wiser. :-)
In Summary: If you want a customized class that has the same functionality of your concrete class without changing the structure of the concrete class, I suggest extending the concrete class.
I mainly have a Java background, but I'm interested in examples from any language.
Like many frameworks, ASP.NET makes heavy use of inheritance to share behaviour between classes. For example, HtmlInputPassword has this inheritance hierarchy:
System.Object
System.Web.UI.Control
System.Web.UI.HtmlControls.HtmlControl // abstract
System.Web.UI.HtmlControls.HtmlInputControl // abstract
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlInputPassword
in which can be seen examples of concrete classes being derived from.
If you're building a framework - and you're sure you want to do that - you may well finding yourself wanting a nice big inheritance hierarchy.
Other use case would be the to override the default behavior:
Lets say there is a class which uses standard Jaxb parser for parsing
public class Util{
public void mainOperaiton(){..}
protected MyDataStructure parse(){
//standard Jaxb code
}
}
Now say I want to use some different binding (Say XMLBean) for the parsing operation,
public class MyUtil extends Util{
protected MyDataStructure parse(){
//XmlBean code code
}
}
Now I can use the new binding with code reuse of super class.
The decorator pattern, a handy way of adding additional behaviour to a class without making it too general, makes heavy use of inheritance of concrete classes. It was mentioned here already, but under somewhat a scientific name of "forwarding wrapper class".
Lot of answers but I though I'd add my own $0.02.
I override concreate classes infrequently but under some specific circumstances. At least 1 has already been mentioned when framework classes are designed to be extended. 2 additional ones come to mind with some examples:
1) If I want to tweak the behavior of a concrete class. Sometimes I want to change how the concrete class works or I want to know when a certain method is called so I can trigger something. Often concrete classes will define a hook method whose sole usage is for subclasses to override the method.
Example: We overrode MBeanExporter because we need to be able to unregister a JMX bean:
public class MBeanRegistrationSupport {
// the concrete class has a hook defined
protected void onRegister(ObjectName objectName) {
}
Our class:
public class UnregisterableMBeanExporter extends MBeanExporter {
#Override
protected void onUnregister(ObjectName name) {
// always a good idea
super.onRegister(name);
objectMap.remove(name);
}
Here's another good example. LinkedHashMap is designed to have its removeEldestEntry method overridden.
private static class LimitedLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
#Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return size() > 1000;
}
2) If a class shares a significant amount of overlap with the concrete class except for some tweaks to functionality.
Example: My ORMLite project handles persisting Long object fields and long primitive fields. Both have almost the identical definition. LongObjectType provides all of the methods that describe how the database deals with long fields.
public class LongObjectType {
// a whole bunch of methods
while LongType overrides LongObjectType and only tweaks a single method to say that handles primitives.
public class LongType extends LongObjectType {
...
#Override
public boolean isPrimitive() {
return true;
}
}
Hope this helps.
Inheriting concrete class is only option if you want to extend side-library functionality.
For example of real life usage you can look at hierarchy of DataInputStream, that implements DataInput interface for FilterInputStream.
I'm beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate.
This is one 'almost'. Try writing an applet without extending Applet or JApplet.
Here is an e.g. from the applet info. page.
/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='HelloWorld' width='200' height='100'></applet> */
import javax.swing.*;
/** An 'Hello World' Swing based applet.
To compile and launch:
prompt> javac HelloWorld.java
prompt> appletviewer HelloWorld.java */
public class HelloWorld extends JApplet {
public void init() {
// Swing operations need to be performed on the EDT.
// The Runnable/invokeLater() ensures that happens.
Runnable r = new Runnable() {
public void run() {
// the crux of this simple applet
getContentPane().add( new JLabel("Hello World!") );
}
};
SwingUtilities.invokeLater(r);
}
}
Another good example would be data storage types. To give a precise example: a red-black tree is a more specific binary tree, but retrieving data and other information like size can be handled identical. Of course, a good library should have that already implemented but sometimes you have to add specific data types for your problem.
I am currently developing an application which calculates matrices for the users. The user can provide settings to influence the calculation. There are several types of matrices that can be calculated, but there is a clear similarity, especially in the configurability: matrix A can use all the settings of matrix B but has additional parameters which can be used. In that case, I inherited from the ConfigObjectB for my ConfigObjectA and it works pretty good.
In general, it is better to inherit from an abstract class than from a concrete class. A concrete class must provide a definition for its data representation, and some subclasses will need a different representation. Since an abstract class does not have to provide a data representation, future subclasses can use any representation without fear of conflicting with the one that they inherited.
Even i never found a situation where i felt concrete inheritence is neccessary. But there could be some situations for concrete inheritence specially when you are providing backward compatibility to your software. In that case u might have specialized a class A but you want it to be concrete as your older application might be using it.
Your concerns are also echoed in the classic principle "favor composition over inheritance", for the reasons you stated. I can't remember the last time I inherited from a concrete class. Any common code that needs to be reused by child classes almost always needs to declare abstract interfaces for those classes. In this order I try to prefer the following strategies:
Composition (no inheritance)
Interface
Abstract Class
Inheriting from a concrete class really isn't ever a good idea.
[EDIT] I'll qualify this statement by saying I don't see a good use case for it when you have control over the architecture. Of course when using an API that expects it, whaddaya gonna do? But I don't understand the design choices made by those APIs. The calling class should always be able to declare and use an abstraction according to the Dependency Inversion Principle. If a child class has additional interfaces to be consumed you'd either have to violate DIP or do some ugly casting to get at those interfaces.
from the gdata project:
com.google.gdata.client.Service is designed to act as a base class that can be customized for specific types of GData services.
Service javadoc:
The Service class represents a client connection to a GData service. It encapsulates all protocol-level interactions with the GData server and acts as a helper class for higher level entities (feeds, entries, etc) that invoke operations on the server and process their results.
This class provides the base level common functionality required to access any GData service. It is also designed to act as a base class that can be customized for specific types of GData services. Examples of supported customizations include:
Authentication - implementing a custom authentication mechanism for services that require authentication and use something other than HTTP basic or digest authentication.
Extensions - define expected extensions for feed, entry, and other types associated with a the service.
Formats - define additional custom resource representations that might be consumed or produced by the service and client side parsers and generators to handle them.
I find the java collection classes as a very good example.
So you have an AbstractCollection with childs like AbstractList, AbstractSet, AbstractQueue...
I think this hierarchy has been well designed.. and just to ensure there's no explosion there's the Collections class with all its inner static classes.
You do that for instance in GUI libraries. It makes not much sense to inherit from a mere Component and delegate to a Panel. It is likely much easyer to inherit from the Panel directly.
Just a general thought. Abstract classes are missing something. It makes sense if this, what is missing, is different in each derived class. But you may have a case where you don't want to modify a class but just want to add something. To avoid duplication of code you would inherit. And if you need both classes it would be inheritance from a concrete class.
So my answer would be: In all cases where you really only want to add something. Maybe this just doesn't happen very often.

Interface naming in Java [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Most OO languages prefix their interface names with a capital I, why does Java not do this? What was the rationale for not following this convention?
To demonstrate what I mean, if I wanted to have a User interface and a User implementation I'd have two choices in Java:
Class = User, Interface = UserInterface
Class = UserImpl, Interface = User
Where in most languages:
Class = User, Interface = IUser
Now, you might argue that you could always pick a most descriptive name for the user implementation and the problem goes away, but Java's pushing a POJO approach to things and most IOC containers use DynamicProxies extensively. These two things together mean that you'll have lots of interfaces with a single POJO implementation.
So, I guess my question boils down to: "Is it worth following the broader Interface naming convention especially in light of where Java Frameworks seem to be heading?"
I prefer not to use a prefix on interfaces:
The prefix hurts readability.
Using interfaces in clients is the standard best way to program, so interfaces names should be as short and pleasant as possible. Implementing classes should be uglier to discourage their use.
When changing from an abstract class to an interface a coding convention with prefix I implies renaming all the occurrences of the class --- not good!
Is there really a difference between:
class User implements IUser
and
class UserImpl implements User
if all we're talking about is naming conventions?
Personally I prefer NOT preceding the interface with I as I want to be coding to the interface and I consider that to be more important in terms of the naming convention. If you call the interface IUser then every consumer of that class needs to know its an IUser. If you call the class UserImpl then only the class and your DI container know about the Impl part and the consumers just know they're working with a User.
Then again, the times I've been forced to use Impl because a better name doesn't present itself have been few and far between because the implementation gets named according to the implementation because that's where it's important, e.g.
class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO
There may be several reasons Java does not generally use the IUser convention.
Part of the Object-Oriented approach is that you should not have to know whether the client is using an interface or an implementation class. So, even List is an interface and String is an actual class, a method might be passed both of them - it doesn't make sense to visually distinguish the interfaces.
In general, we will actually prefer the use of interfaces in client code (prefer List to ArrayList, for instance). So it doesn't make sense to make the interfaces stand out as exceptions.
The Java naming convention prefers longer names with actual meanings to Hungarian-style prefixes. So that code will be as readable as possible: a List represents a list, and a User represents a user - not an IUser.
There is also another convention, used by many open source projects including Spring.
interface User {
}
class DefaultUser implements User {
}
class AnotherClassOfUser implements User {
}
I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.
As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:
class Number implements Comparable{...}
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}
Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.
Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?
I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.
Bob Lee said once in a presentation:
whats the point of an interface if you
have only one implementation.
so, you start off with one implementation i.e. without an interface.
later on you decide, well, there is a need for an interface here, so you convert your class to an interface.
then it becomes obvious: your original class was called User. your interface is now called User. maybe you have a UserProdImpl and a UserTestImpl. if you designed your application well, every class (except the ones that instantiate User) will be unchanged and will not notice that suddenly they get passed an interface.
so it gets clear -> Interface User implementation UserImpl.
In C# it is
public class AdminForumUser : UserBase, IUser
Java would say
public class AdminForumUser extends User implements ForumUserInterface
Because of that, I don't think conventions are nearly as important in java for interfaces, since there is an explicit difference between inheritance and interface implementation. I would say just choose any naming convention you would like, as long as you are consistant and use something to show people that these are interfaces. Haven't done java in a few years, but all interfaces would just be in their own directory, and that was the convention. Never really had any issues with it.
In my experience, the "I" convention applies to interfaces that are intended to provide a contract to a class, particularly when the interface itself is not an abstract notion of the class.
For example, in your case, I'd only expect to see IUser if the only user you ever intend to have is User. If you plan to have different types of users - NoviceUser, ExpertUser, etc. - I would expect to see a User interface (and, perhaps, an AbstractUser class that implements some common functionality, like get/setName()).
I would also expect interfaces that define capabilities - Comparable, Iterable, etc. - to be named like that, and not like IComparable or IIterable.
Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:
public void doSomething(Collection someStuff) {
...
}
than this:
public void doSomething(Vector someStuff) {
...
}
If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.
The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.
If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.
=v= The "I" prefix is also used in the Wicket framework, where I got used to it quickly. In general, I welcome any convention that shortens cumbersome Java classnames. It is a hassle, though, that everything is alphabetized under "I" in the directories and in the Javadoc.
Wicket coding practice is similar to Swing, in that many control/widget instances are constructed as anonymous inner classes with inline method declarations. Annoyingly, it differs 180° from Swing in that Swing uses a prefix ("J") for the implementing classes.
The "Impl" suffix is a mangly abbreviation and doesn't internationalize well. If only we'd at least gone with "Imp" it would be cuter (and shorter). "Impl" is used for IOC, especially Spring, so we're sort of stuck with it for now. It gets a bit schizo following 3 different conventions in three different parts of one codebase, though.
Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?
If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.

Categories