How to only expose certain classes and methods? - java

I am tasked to create a reusable piece of software as a library/API. Right now I have every class as public in multiple packages and the methods within them are mostly private.
Since this is supposed to be an API, I wish to hide all the classes except for exposing a few classes and methods.
I can't use the private modifier for the classes as I refer to them in other packages within the project. I also do not want to inherit the classes unnecessarily in order to access the methods within.
What should I do to expose certain classes and methods while maintaining the ability to access them within my project?

I really suggest that you chart down the following on a piece of paper before you start designing your API.
Pre Work
Have you identified all the types of interacting entities. Each entity can be formed into an object.
At what layer (Controller/Facade/DAO etc ) you wish to use each of these.
Are any of the Objects expected to be transferred over a network.
What data will your entire API be exposing.
Designing
You would normally want to do the following:-
If your entities (in part 1) are related and may contain common info, create 1 entity ( Example Common) to keep the common data (like timestamps of the request, device info etc) and make others that can contain this info, inherit this entity. ensure to have the properties of the common entity as protected.
Common will look something like
public class Common{
protected _deviceId;
protected _reqTimeStamp;
protected _osVersion;
//Getters and Setters.
}
For example, if you API is using the JSON request data received from Mobile Apps, you can have Common to contain the data given above in point 1. You can create another Object as follows
public class UserInfo extends Common{
private String _userName;
private String _userMailId;
//getters and setters
}
Try to keep minimum entities for your Data Transfer between the layers. If the service layers that your API serves, are situated on different servers, then you may want to keep it Serializable and ensure that such DTOs do not contain chunks of huge information.
Similarly, when you segregate, the functionality of your API, try to see what functionalities are similar and commonly required. Move them to abstract classes and make the implementations to the interfaces that classify other behavior extend the abstract classes.
See this example below.
public abstract class CommonBehaviour {
protected String _commonId;
public void commonBehaviourOne()
{
//Behaviour common to implementations
}
abstract public void overrideThisBehaviour();
//getters and setters
}
So now if you have two types of behaviours in implementations that have a common functionality between them.
public interface Designable {
}
public class DesignerImpl extends CommonBehaviour implements Designable {
#Override
public void overrideThisBehaviour() {
// TODO Auto-generated method stub
}
}
The decision to make the classes public, private or default will be easy once you have the pre-requisites clear. You have to brainstorm, discuss amongst the stakeholders and brainstorm again. You will definitely come up with a good API
References for your help
There is plenty of information available on the internet for people who enter designing.
As far as books are concerned, I referred, "Head First Design Patterns" and Design Patterns by Gamma . Although i found Gamma more comprehensive, former is good for newbies.
Let me know if this helps you.

On an API, you should only expose interfaces and business objects. Normally, these are on different maven artifacts than the implementation of the interfaces.
In short: Make a maven project for domain objects, another for API interfaces, and another for API implementation. Then distribute to your clients only the first two.
Concerning the dependencies: Implementation project should depend on both API and business objects projects. API project should depend only on business objects project. Business object project should depend on neither of both.

Make your classes as public, if you have methods to expose.
The method which is used locally in its class has to be private
The method which should to be exposed, takes public
The method which should to be visible inside your API, and not out, takes protected or default.

Related

Abstraction in OOPs

I have come across few definitions over the years, and have never able to clearly understand what abstraction is.
I have understood the 3 main concepts of Oops but have had difficulties with this particular concept which is engraved within these other concepts.
Till now i have come to 2 conclusions, but not sure.
It is the ability to hide the implementation details of a method(Behavior), and provide the user with just the interface.
It is ability to define a method signatures(ie. only to declare them) without actually implementing them.
Which is the correct definition of abstraction with context to Object oriented programming, and if not one of the above, then what is it?
Would appreciate if supporting code is also provided :)
It is the ability to hide the implementation details of a method(Behavior), and provide the user with just the interface.
Sort of, but that's "encapsulation". They're related in the sense that "encapsulation" is a key concept of object oriented design whereas "abstraction" is a potential result of that concept.
It is ability to define a method signatures(ie. only to declare them) without actually implementing them.
That's an implementation detail, not the conceptual notion of abstraction itself.
In a simple inheritance model, "abstraction" can be thought of as referring to an object by one of its ancestor (or more abstract) types. For example, consider a hierarchy:
Lifeform
Animal
Canine
Golden Retriever
If you're performing an operation specific only to a Golden Retriever, then you can't perform that operation on any Animal. It has to be a specific Animal. So you need that specific implementation.
However, if you're performing an operation that's generic to all Lifeforms then it doesn't matter what specific implementation you receive. That operation is abstracted so that it can accept any Lifeform object, regardless of the more specific implementation.
Interfaces provide another implementation mechanism which can achieve abstractions. Object composition is still another mechanism. For example, consider this non-inheritance scenario:
public class MyObject {
private ThirdPartyObject dependency;
public MyObject() {
// initialize the dependency
}
public boolean getValue() {
return this.dependency.getValue();
}
public void setValue(boolean value) {
this.dependency.setValue(value);
}
}
This doesn't use inheritance or interfaces for anything, but it does create an abstraction. Consuming code doesn't know anything about the ThirdPartyObject or the details of its implementation. Following the Law Of Demeter the details of that implementation have been abstracted behind a custom object which you control. This can be very useful for de-coupling your code from implementation details you don't control.
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.
For example, when you login to your Amazon account online, you enter
your user_id and password and press login, what happens when you press
login, how the input data sent to amazon server, how it gets verified
is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined
object, which is composed of several other smaller objects like a
gearing system, steering mechanism, engine, which are again have their
own subsystems. But for humans car is a one single object, which can be managed by the help of its subsystems, even if their inner details
are unknown.
Also to be noted that abstraction hides the implementation details but implementation can be shown even i.e. member functions with definitions can also be present, unlike Interface which provides total Abstraction.
Source: BeginnersBook.com
My summary is "hiding the details"; in the case of programming, abstraction is more like your first definition.
For supporting code, you don't really need to look too far. Abstraction is all around. Consider the common data structure string.
A string within a computer is actually bytes converted to a specific character set strung together. (no pun intended)
Therefore, when you put "hello, world" to you, it's a phrase in quotes. When the computer run it, it creates a data structure string which itself contains the bytes and various state to represent the given string. You don't (usually) care how the string object is working. It does and you move on with your goal. That is as basic of an example of abstraction as I can get.
Abstraction is the process by which data and programs are defined with a representation similar in form to its meaning, while hiding away the implementation details.Abstraction involves the facility to define objects that represent abstract “actors” that can perform work, report on and change their state, and “communicate” with other objects in the system.
Abstraction can be seen in two ways:
Data Abstraction - Data abstraction is the way to create complex data types and exposing only meaningful operations to interact with data type, where as hiding all the implementation details from outside works.
Control Abstraction - Abstraction of behavior. Provides an easier, higher level API to hide client from unnecessary execution details.
Abstraction is a way to promise that a class implementing a given abstraction will have a given behaviour. Thus, abstract classes cannot be directly instantiated, they first need to implement the abstraction.
Abstract classes are thus meant to be implemented by a concrete class that declares and defines a method matching the abstract contract. An abstraction can however provide some concrete behaviours along with abstract ones.
Abstraction is done in Java through abstract classes and through interface. In C++, abstraction is achieved through the usage of virtual methods inside a class. Note that Java interfaces were only created as (unlike C++) multiple inheritance is not allowed in this language.
In simple terms
Abstraction: Showing what is necessary and hiding unnecessary details. Ex if your class has 10 functions but only 2 should be useful by the consumer of the class that you make those functions as public and other are private, so what is visible to the consumer is what is needed, instead of showing it all.
Encapsulation: Hiding the complexity to the consumer of the class. Ex. if your class needs two variables to store min and max, you encapsulate them under getter and setter and implement all the validations and checks in the getter and setter. this way you hide the complexities.
Well I will explain abstraction with a real world example. Say in your house you do have an electric plug and many devices can connect to the same plug but plug will never have an idea which device it is connected to, in other words the details of the devices is abstracted (hidden) to the plug.
Think what if we connect a device directly to electric wire without a plug? Say connect a bulb directly to a wire, then wire knows which device it is connected to and when ever we need to replace the bulb then we have to remove the wire connection from the bulb, which means bulb is tightly coupled with the wire. In other words bulb and wire knows the details where it is connected to, means not abstracted.
In object oriented world abstraction works exactly same. The class which consume other classes function/property doesn't need to know which classes function/property it is consuming and everything should be abstracted with an interface / abstract class.
Let me code the same example. Here I have a class "ElectricPlug", which is running a device. But the class "ElectricPlug" doesn't have any idea which device it is running. It can be any class implementing the interface "IDevice", which means the implementation of "RunDevice" is abstracted from "ElectricPlug". Here is the full sample code,
class Program
{
static void Main(string[] args)
{
ElectricPlug electricPlug = new ElectricPlug(new Bulb());
}
}
public class ElectricPlug
{
private readonly IDevice _device;
public ElectricPlug(IDevice device)
{
_device = device;
}
public void Run()
{
_device.Rundevice();
}
}
public interface IDevice
{
void Rundevice();
}
public class Bulb : IDevice
{
public void Rundevice()
{
Console.WriteLine("Switched on bulb");
}
}
public class ElectricPlug
{
private readonly IDevice _device;
public ElectricPlug(IDevice device)
{
_device = device;
}
public void Run()
{
_device.Rundevice();
}
}
There are two parts of object in oops
state ( properties )
behavior ( methods )
so to hiding the implementation of behavior of any object is known as abstraction
let's take a example -->
there is a cook at my home which makes delicious food . some body comes at my home and take dinner . after dinner they asked me that who made this food . i answered
i have a cook whose name is tttt , his address is tttt and his number is 0000 ( these all are the properties of cook object )
they again asked how he made this then i answered
i don't know how he made . i only know that he can make food
so abstraction means we are telling that what task our object can do instead of how my object can do a task .

Sharing Singleton logic between projects, with modifications for each project

I am developing two Android applications with similar -- but not identical -- logic, and I want to share code between them. Currently, I have a project for each application, and an additional project for shared classes. The shared-classes project is a library, and the application projects are linked to this library.
The problem I have is with a class that's responsible for getting data from the server and caching that data. The class is called DataSingleton. Fetching the data has some logic which is the same for both applications, and some which is different. My question is how to design the class to support this.
There are some limitations here:
The data Singleton should be a singleton, as implied by its name.
Some of the shared logic in the shared project uses the DataSingleton, so the DataSingleton must also be in the shared-classes project (otherwise I get a build error).
I don't want to put the application-specific logic in the shared project.
If this was C++, I would have 2 different classes name DataSingleton -- one in each application -- and then have the linker connect the correct class. Both classes could inherit from some common base class, to handle the code sharing for shared logic. Can I do something similar in Java?
If it helps, I can "initialize" the DataSingleton at the start of the application with some argument that will determine its behavior. I thought about passing a class to it, but then that class doesn't have access to the DataSingleton's private members.
What is the "right" way to do this?
Think about singleton. It is a class that does 3 thigs:
1. it has a business logic
2. it creates instance of itself
4. it holds this single instance and provides access to it.
You want to hold more than one implementations of your class. This means that you need interface and/or abstract base class and several concrete classes. But in this case the best solution is to separate #1 from #2 and #3: create hierarchy of DataFetchers (I am sorry, I changed your name DataSingleton because it does not describe the reality any more) and DataFetcherAccessor:
interface DataFetcher {}
class DataFetcher1 implements DataFetcher{}
class DataFetcher2 implements DataFetcher{}
class DataFetcherAccessor<A extends DataFetcher> {
private static A accessor;
public static void setImpl(Class<A> c) {
accessor = c.newInstance();
}
public static A getAccessor() [
return accessor;
}
}
There are obviously a lot of other solutions. For example you can use SPI to locate available implementation of your interface. You can also scan your classpath yourself and discover available implementation of interface DataFetcher or use Reflections for this.
Strip the DataSingleton in the shared project of the parts that will need to change in the different projects, define it as an abstract class and change its name to AbstractDataSingleton or something like that, then just create 2 separate classes in each product called DataSingleton or whatever and make them extend the AbstractDataSingleton in the shared project.

Is there a way to create Model here without duplicating the code?

I need to use two similar libraries one for one specific session of MVC. Means, they (their methods) won't be used simultaneously (I'll use If...Else around that specific session to choose methods of only one library at a time). The problem is:
For both libraries to work, its mandatory for my Entities (Model) to extend their classes (wished I was with C++).
They don't provide any Interface. So, I can't do multi-inheritance.
The only choice I have left: Create two different Models each for both libraries & use specific Model based on session (or being used libraries).
But, it'll duplicate the codes in Models. At this time there's no need to sync data between them due to use of persistent storage between MVC sessions. But still, duplicate code is a big headache to manage. Is there a way to avoid this?
You could create Adapters for each specific libraray. This would keep your own code clean from the other libraries.
Also you should consider using the Strategy Pattern for switching between both libraries. This becomes handy when the code becomes more complex and you can mock the libraries in tests.
You can't get around including both libraries if that's what you're asking. You could have a few options just depends on how you want things to work.
From what I understand, you could create two classes, each extending a different library, these classes implement an Interface, override any methods you need to.
Pseudo code:
private class Lib1Adapter extends Lib1 implements LibAdapter {
// wrapper methods call lib1 methods
}
private class Lib2Adapter extends Lib2 implements LibAdapter {
// wrapper methods call lib2 methods
}
public interface LibAdapter {
// method signatures for publicly accessible methods
}
public class YourModel {
public LibAdapter la = < boolean statement > ? new Lib1Adapter() : new Lib2Adapter();
}

Design Phase - Many references to same object

I am designing an application where a class named Rights is used. This class contains information about what the user can /can't do and also contains other classes like DocumentFilters.
The issue here is that I have a lot of different parts of the application getting an instance of that class through their constructor or get method, in order to be able to verify a user action before allowing it. It seems like this is bad practice (I might be wrong). Are there ways to improve this?
The way it works is having the main class of the application creating the Rights class and then creating different components and passing it to those. The components don't have instance of the main class ether.
Example code. This is repeated over several Modules.
public class ModuleA{
private Rights rights;
public ModuleA(Rights rights){
this.rights=rights;
}
private boolean verifyRights(ActionEvent e){
if(e.getSource("copyButton"){
if(rights.allowedToCopy){
return true;
}
return false;
}
}
That is a valid design and it is called Inversion of control and more specificly Dependency Injection. You can try to use an IoC container for java if you don't want to inject your dependencies manually.
It is also possible to separate the security code into aspects by using AOP. This is a more advanced option, but doing so you can separate the code that checks the security from the real business code.
If the method you showed is duplicated exactly in your Module classes, you should extract the method into a base class. This base class should then be used for all your Module classes.
public class ModuleBase
{
private Rights rights;
public ModuleA(Rights rights)
{
this.rights=rights;
}
public boolean verifyRights(ActionEvent e)
{
/// implementation
}
}
public class ModuleA : extends Bicycle
{
public ModuleA(Rights rights)
{
super(rights);
}
}
First of all I would suggest to isolate all the rights checking code into some special layer. Usually, the Facade patten is helpful here - it can check rights and then forward requests to the underlying business logic.
But this is not always possible. In this case you still have to provide classes with references to Rights instance. There are several patterns here:
Pass it to constructor/method (like you do) - still works.
Introduce Context which will store the Rights instance and make it available for necessary classes. But context is really helpful when it stores many reusable instances, not only one.
Use any dependency injection framework.
Hope this helps.

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.

Categories