How not to expose a public interface in Java - java

In my project jOOQ, I model SQL queries with a complex data structure. All components of a query implement
public interface QueryPart {
int bind(java.sql.PreparedStatement stmt);
int bind(java.sql.PreparedStatement stmt, int initialIndex);
SQLDialect getDialect();
String toSQLDeclaration();
String toSQLDeclaration(boolean inlineParameters);
String toSQLReference();
String toSQLReference(boolean inlineParameters);
}
This interface's methods are used internally by all packages of the library to construct and execute SQL. They should not be invoked directly from client code. For that purpose, I have added
public interface QueryPartProvider {
QueryPart getQueryPart();
}
Which is the only publicly exposed interface. An example of an actual query part is:
public interface Table extends QueryPartProvider {}
class TableImpl implements QueryPart, Table {}
As you can see, the QueryPart methods can only be accessed via Table.getQueryPart().toSQLDeclaration(), etc.
My design helps discouraging direct access to QueryPart methods, but cannot completely hide it. My question is: Can anyone tell me a good design pattern to achieve this goal?
Note: The simplest but not very nice solution would be to cast all objects to QueryPart, e.g. ((QueryPart) table).toSQLDeclaration()

All methods of an interface are always public, so there is no way for you to have access to something which is not accessible to your library clients as well.
Maybe you could achieve what you want using an abstract class for Table, and the getQueryPart() method as package protected. I'm not sure however that I would want to do that, instead of a cast from Table to TableImpl.

After implementing something similar to what sfussenegger suggested, I came up with an even better solution involving the Adapter design pattern. This is the general outline:
/**
* Objects providing an internal API implement this interface
*/
public interface Adapter {
/**
* Dynamically expose an (publicly unknown) internal API.
*/
<T> T internalAPI(Class<T> internalType) throws ClassCastException;
}
This adapter type is the only fact exposed to the public about anything internal. Only package private implementation methods know about the possible arguments to this method (and those hackers that really want to actually use the internal API for workarounds, extensions, etc).
/**
* This type contains the public API for a QueryPart
*/
public interface QueryPart extends Adapter {
// [...]
}
/**
* This type contains the internal API for a QueryPart
*/
public interface QueryPartInternal extends QueryPart {
// [...]
}
The above QueryPart and QueryPartInternal are related. This fact is known to public but no public class / type extends QueryPartInternal. Only the following package-private class and its gazillion subclasses do:
/**
* This class is the base class for all QueryParts.
* It is package private and thus doesn't expose anything
*/
abstract class AbstractQueryPart implements QueryPartInternal {
// [...]
/**
* For other package private implementation methods
*/
#Override
public final <T> internalAPI(Class<T> internalType) {
return internalType.cast(this);
}
/**
* Convenience method for subclasses heavily using the
* internal API
*/
protected final QueryPartInternal internal(QueryPart part) {
return part.internalAPI(QueryPartInternal.class);
}
// [...]
}

Could you please explain why you'd like to do that? The only reason I can see is to make it impossible to implement the interface for a user of your library.
I don't think that's a good approach. Simply add some Javadoc and explain why it doesn't make sense to implement it. But finally, leave it to the user whether there's a valid reason to create a custom implementation. It's always difficult to foresee each and every use case.
If somebody gots stuck with his approach it's certainly not your fault - he can't say he hasn't been warned :)
To give an example, that's what you can find all over Apache Wicket's source code:
/**
* THIS IS WICKET INTERNAL ONLY. DO NOT USE IT.
*
* Traverses all behaviors and calls ...
*/
EDIT:
just another though: you could try this, although I'd still discourage it - don't say you haven't been warned ;)
public interface ExposedInterface {
void foo();
}
// only default visibility
interface InternalInterface extends ExposedInterface {
// nothing here
}
// and here some methods
ExposedInterface get(); // user can use it
void set(InternalInterface obj); // user is out of luck here

Related

Java - Send a method as parameter and decide if there is need to call it

I am currently making an app and I am implementing cache in it. The thing is the DAOs are implemented in another service.
The idea that I had, to avoid code repeating, is having a generic cache in my service. Then, acording to the method called it verifies the respective cache and, in case it doesn't exist, calls the DAO associated with the method passed as parameter. Is there any way to do this?
NOTE: I am using java 1.6 in my application
I suppose you need an Adapter pattern. Naive realisation could be
class AdapterA implements Adapter<A> {
private A;
#Override
public void getValue() { return getA();}
}
and then when you get instance of A, B or C you wrap it in appropriate Adapter. Later you could call just getValue regardless specific type under hood.
Another approach. I would be grateful if someone say what the pattern is (possibly Proxy?):
class ProxyImpl implements Proxy {
#Override
public void doAction(<? extends DAO> dao) {
if (dao instance of A) { ((A)dao).getA()
} else if (dao instance of B) { ((B)dao).getB()

Is Factory method more suitable for frameworks and Abstract facory for Library?

Both Abstract Factory and Factory method patterns are creational design patterns which solves the object creation issues in different scenarios.
As per GOF Factory Method pattern
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
My Understanding :
Motive of the Client is to get a method present in the base Factory class get executed which is dependent upon an object whose concrete class is not known now (In such a case, either during providing the software to client, it will be defined, or it will be the client himself writing the concrete implementation, most likely in case of Framework). The not known (or likely to change) Product is provided an abstract type : IProduct, and setting a contract that in future any implementation for Product must implement this interface.
IProduct interface
package com.companyx;
public interface IProduct {
public void serve();
}
Factory class with 'a method' which needs to be executed
package com.companyx;
public abstract class Factory {
public abstract IProduct createProduct();
private void performCriticalJob(){
IProduct product = createProduct();
product.serve();
}
public void executeJob(){
//some code
performCriticalJob();
//some more code
}
}
Some concrete Product
package com.companyx;
class AppAProductFeatureX implements IProduct{
#Override
public void serve() {
//some code
}
}
Factory of the concrete Product
package com.companyx;
public class AppAFeatureXProductFactory extends Factory{
#Override
public IProduct createProduct() {
return new AppAProductFeatureX();
}
}
Client code
package com.clientcompany;
import com.companyx.AppAFeatureXProductFactory;
import com.companyx.Factory;
public class Client {
public static void main(String[] args) {
Factory fact = new AppAFeatureXProductFactory();
fact.executeJob();
}
}
As per GOF Abstract Factory pattern
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
My Understanding
The client is interested in the products, here this pattern helps in providing the product by hiding the concrete product classes behind factory classes.
Product type wanted by the client
package com.companyb;
public interface IProductA {
public void performAJob();
}
Implementation of the product
package com.companyb;
//can be named better, but lets go with this name for this time
public class ProductAVersion1 implements IProductA{
#Override
public void performAJob() {
// some code
}
}
Factory interface, (It can be also an abstract class)
package com.companyb;
public interface IFactory {
public IProductA createProduct();
}
Concrete implementation of Factory o create ProductA
package com.companyb;
public class FactoryA implements IFactory{
#Override
public IProductA createProduct() {
return new ProductAVersion1(); // concrete class of product is hidden
}
}
Client Code
package com.clientcompany.productprovider;
import com.companyb.IFactory;
import com.companyb.IProductA;
public class SomeClientClass {
private IFactory factory;
private IProductA product;
public void doSomeJobWithProductA() {
// some code
product.performAJob();
//someCode();
}
public void setFactory(IFactory factory) {
this.factory = factory;
this.product = factory.createProduct();
}
}
package com.clientcompany.productprovider;
import com.companyb.FactoryA;
public class SomeOtherClientCode {
public static void main(String[] args) {
SomeClientClass someClientClass = new SomeClientClass();
someClientClass.setFactory(new FactoryA());
someClientClass.doSomeJobWithProductA();
}
}
Q1 : Is the family of related product necessary in Abstract Factory patter , won't this pattern still be relevant if only one kind of product (like above) is there with various sub types but not various related types?
Q2 Is my understanding above correct ?
Q3 Above brings another doubt in my mind : Is Factory method more suitable for frameworks (where client can give the implementation of products) and just like template method pattern, factory invokes the createProduct() concrete implementation form the user provided Concrete Factory implementation ?
Also similarly is Abstract factory more fits for Library development, where concrete product classes (likely to vary) are hidden behind more stable Factory classes ?
I am having real difficulty in getting into your shoes. But I am quite interested in this subject so I will give a try. Involved here are concepts like library, framework, factory method, abstract factory and product family etc.
First, the library vs framework has really nothing to do with factory, abstract factory or any pattern for that matter. Library vs framework debate is not from implementational perspective where the patterns play. For example JUnit is a framework which comes with a rich assertion library. So should junit prefer one pattern over other for its internal implementation? Java itself is a framework which comes with a JCL library. Dot Net which is similar to java even calls itself a framework, and contains BCL library. So no more framework vs library debate in implementational context.
So the question boils down to which pattern should you use? It is not about the difference, which is clear, but about which one to use in which scenario. In this context, the Client Code is all code which may call the one which you are typing right now. It does not matter whether some code is written by you or someone else, in same or different jar, from same or different organization. From perspective of one code fragment, any other code (even in different method of the same class) is client code if that code has a potential to call the code which you are typing right now.
While typing any code (irrespective of framework or library status) sometimes we need to obtain instances of some object. May be we need a BufferedReader. If at compile time we are absolute sure about the concrete class of the object, KISS it and go with newing.
We may not know the concrete class of an instance. Now question aries whether the client code has this information? If the client code knows about the actual concrete class, but I do not know then we use the FactoryMethod pattern. The code I am typing will ask for an instance of a factory object in (say) its argument list. The client code knowing the actual concrete class, will supply a factory object which will do the creation. Example of this case is seen in JDBC like we want to process an sql statement. At compile time we do not know whether we should instantiate a mysql.JDBC4PreparedStatement or a microsoft.SQLServerStatement. It depends on connection string and that depends on end user. So we get hold of a Connection instance and ask it to createStatement(). See, we are delegating the construction of an object of type sql.Statement to a subclass of sql.Connection. Here the conn instance is the factory object. How we get hold of the factory is immaterial, just that we got it from client code.
If we need an instance of a Process object and at compile time we do not know whether it will be a Win32Process or a UnixProcess, we delegate the responsibility of its creation to ProcessBuilder which is builder pattern related to factory pattern. Same goes for jdbc ConnectionManager.
In case when there are many different classes not related by inheritance but by family we may use AbstractFactory. For example take jdbc's dot net counterpart DbProviderFactory. My code needs instances of Connection, Command, DataReader etc which are not related by inheritance but by family of MySql or SqlServer. So we get hold of an instance of a subclass of DbProviderFactory. May be it is a MySqlProviderFactory or a SqlProviderFactory that depends on runtime and client code. Once we have that factory, we can do CreateCommand(), CreateConnection() etc.
Hope this helps you choose between factory pattern and abstract factory pattern.
In my understanding:
A1: The family of product does not need to be necessarily related, as shown on an example diagram, only a Client is needed that has knowledge of the type of products. The relation is mostly natural as you probably don't want the same Client to create 2 unrelated objects, e.g., it would look strange if you have an "AbstractPizzaFactory" that creates Pizza and Cars, no?
A2: Technically you can provide a default factory method in the Factory pattern, so that you can still create (defaults) new Objects without always subclassing it.
A3: I would agree with you on this point, although creating a Library or a Framework is never black and white.
Abstract Factory can be seen as collection of the Factory Methods.
For better understanding examples from real life can help:
Factory Method - plasticine/mold
Abstract Factory - cards factory

Best Practice for JavaDocs - Interface,Implementation, or Both?

I have a DAO interface and implementation of the DAO. The JavaDocs in the interface are what Netbeans displays to the client implementing the DAO methods.
Obviously I will need to maintain the JavaDocs in the interface. But what about the implementation of it? On one hand, it is convenient to have them there, but on the other hand, it is duplication, and requires them to be maintained in two places.
Just wondering what other Java developers do.
If the implementing method doesn't provide its own Javadoc, there will still be a link to the interface method's docs. I never understood why Eclipse inserts /* (non-Javadoc) #see ... */ as the Javadocs will automatically reference the interface's docs.
Example:
public interface Named {
/** Returns the name. */
public String getName();
}
public class Thing implements Named {
// note no Javadocs here
public String getName() {
return "thing";
}
}
After running javadoc, Thing.getName's Javadocs are:
getName
public java.lang.String getName()
Description copied from interface: Named
Returns the name.
Specified by:
getName in interface Named
The interface should have all the information about the contract, basically what the method does, the description of parameters, return values and so on.
Unless there's some extra information that isn't clear from the interface description (there rarely is), the implementation documentation should then simply link to the interface method.
This is the format that I've found the most useable from both the implementor and the client side of the fence.
In my project, Eclipse automatically creates documentation as below :
/* (non-Javadoc)
* #see com.comp.SomeInterface#method(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
#Override
public void method(HttpServletRequest arg0, HttpServletResponse arg1)
throws Exception {
// TODO Auto-generated method stub
}
We have created javadoc using Ant task, so it creates link to the interface.

Using "Adapter" pattern

How I understand, the Goal of the Adapter pattern is to call some class methods using some interface (which opened to clients). To make adapter pattern we need to implement some interface (which uses by client), and also we need to extend some class, which methods client need to call when calling interface methods.
class Adapter extends NeedClass implements PublicInterface{}
But what if we haven't interface, but have only 2 classes? For example we have some class(not interface!) which methods uses clients. Now we need to call methods of other class by making adapter class, but we cant to do this, because we cant make multiple Inheritance on the adapter class.
class Adapter extends NeedClass, PublicInterface
above code doesnt work.
What we can do in this case?
You can has an instance of NeedClass in Adapter and call it, when you need. So you extend only from PublicInterface.
public class Adapter extends PublicInterface {
private NeedClass needClass;
#Override
public void doSomething() {
needClass.doSomethingElse("someParameter");
}
}
You can use a composition instead of inheritance. Add a field to Adapter class of type NeedClass:
public class Adapter extends PublicInterface {
private NeedClass needClass;
}
Then inside Adapter methods delegate execution to needClass field.
From what i have understood the Adapter Pattern.
it is helpful when dealing with the third part codes such as API which is/ are subject to changes any time and my likely to break your code if implemented direct.
For example : Using Paypal in your site for payment online.let's assume the Paypal uses the method payMoney() for payment. and after sometime they decide to change the method to something else let's say sendMoney(). This is likely to break your code if implemented directly, with the use of Adapter Design pattern this can be solves as follow
the third part code => Paypal
class Paypal {
public function __construct(){
// their codes
}
public function payMoney($amount){
// the logic of validating
// the $amount variables and do the payment
}
}
so implement it directly in the code as below will break the code
$pay = new Paypal();
$pay->payMoney(200);
using adapter will save numbers of hours and a complex work of updating the code from payMoney() to sendMoney() in every where that the API scripts has been implemented. Adapter enable update in one place and that's it.
Let see it.
class paypalAdapter {
private $paypal;
// Paypal object into construct and check if it's pa
// Paypal object via type hint
public function __construct(PayPal $paypal) {
$this->paypal = $paypal;
}
// call the Paypal method in your own
//custom method that is to be
// implemented directly into your code
public function pay($amount) {
$this->paypal->payMoney($amount);
}
}
so it is like that and there you can go and use the PaypalAdater directly into the code as follow;
$pay = new PaypalAdapter(new Paypal);
$pay->pay(200);
So in future when the Vendor(Paypal) decide to use sendMoney instead of payMoney what to be done is to open the PaypalAdapter class and do the following in the pay($amount) method:
// SEE THIS METHOD ABOVE TO OBSERVE CHANGES
// FROM $this->paypal->payMoney($amount);
// TO $this->paypal->senMoney($amount);
public function pay($amount) {
$this->paypal->sendMoney($amount);
}
After this minor change in one place, everything works well as before.

Force Singleton Pattern on a Class implementing an Interface

I better explain the question with an example.
I have an Interface Model which can be used to access data.
There can be different implementations of Model which can represent the data in various format say XMl , txt format etc. Model is not concerned with the formats.
Lets say one such implementation is myxmlModel.
Now i want to force myxmlModel and every other implementation of Model to follow Singleton Pattern.The usual way is to make myxmlModels constructor private and provide a static factory method to return an instance of myModel class.But the problem is interface cannot have static method definitions and a result i cannot enforce a particular Factory method definition on all implementation of Model. So one implementation may end with providing getObject() and other may have getNewModel()..
One work around is to allow package access to myxmlModel's constructor and create a Factory class which creates the myxmlModel object and cache it for further use.
I was wondering if there is a better way to achieve the same functionality .
Make a factory that returns
instances of your interface, Model.
Make all concrete implementations of the model package-private classes
in the same package as your factory.
If your model is to be a singleton, and you are using java
5+, use enum instead of traditional
singleton, as it is safer.
public enum MyXMLModel{
INSTANCE();
//rest of class
};
EDIT:
Another possibility is to create delegate classes that do all the work and then use an enum to provide all of the Model Options.
for instance:
class MyXMLModelDelegate implements Model {
public void foo() { /*does foo*/}
...
}
class MyJSONModelDelegate implements Model {
public void foo() { /*does foo*/ }
...
}
public enum Models {
XML(new MyXMLModelDelgate()),
JSON(new MyJSONModelDelegate());
private Model delegate;
public Models(Model delegate) { this.delegate=delegate; }
public void foo() { delegate.foo(); }
}
You can use reflection. Something like this:
public interface Model {
class Singleton {
public static Model instance(Class<? extends Model> modelClass) {
try {
return (Model)modelClass.getField("instance").get(null);
} catch (blah-blah) {
blah-blah
}
}
}
public class XmlModel implements Model {
private static final Model instance = new XmlModel();
private XmlModel() {
}
}
usage:
Model.Singleton.instance(XmlModel.class)
Actually, I don't like this code much :). First, it uses reflection - very slow, second - there are possibilities of runtime errors in case of wrong definitions of classes.
Can you refactor the interface to be an abstract class? This will allow you to force a particular factory method down to all implementing classes.
I used to ask myself the same question. And I proposed the same answer ;-)
Now I normally drop the "forcing" behavior, I rely on documentation.
I found no case where the Singleton aspect was so compelling that it needed to be enforced by all means.
It is just a "best-practice" for the project.
I usually use Spring to instanciate such an object,
and it is the Spring configuration that makes it a Singleton.
Safe, and so easy ... plus additionnal Spring advantages (such as Proxying, substituing a different object once to make some tests etc...)
This is more an answer to your comment/clarification to kts's answer. Is it so, that the real problem is not using the Singleton pattern but instead defining an eclipse (equinox) extension point schema that allows contributing a singleton?
I think, this can't be done, because everytime you call IConfigurationElement.createExecutableExtension you create a new instance. This is quite incompatible with your singleton requirement. And therefore you need the public default constructor so that everybody can create instances.
Unless you can change the extension point definition so that plugins contribute a ModelFactory rather than a model, like
public interface ModelFactory {
public Model getModelInstance();
}
So the extension user will instantiate a ModelFactory and use it to obtain the singleton.
If I guessed wrong, leave a comment and I delete the answer ;)

Categories