I am reading Effective Java. In a section that talks about using function objects as strategies, the below paragraph is present.
Because the strategy interface serves as a type for all of its concrete strategy
instances, a concrete strategy class needn’t be made public to export a concrete
strategy. Instead, a “host class” can export a public static field (or static factory
method) whose type is the strategy interface, and the concrete strategy class can
be a private nested class of the host
// Exporting a concrete strategy
class Host {
private static class StrLenCmp
implements Comparator<String>, Serializable {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
// Returned comparator is serializable
public static final Comparator<String>
STRING_LENGTH_COMPARATOR = new StrLenCmp();
... // Bulk of class omitted
}
My question is , is there any particular advantage of using the above way? What is the problem with exporting the strategy by making concrete strategy public?
Yes, there is. This way you are returning the interface and not the concrete class, so if you change the concrete implementation of Comparator interface you don't have to modify client classes too (I think this is the most important reason of using interfaces).
For example:
//inside aClass
Comparator c = Host.STRING_LENGTH_COMPARATOR; //Programming against interfaces is different from:
StrLenCmp c = Host.STRING_LENGTH_COMPARATOR; //programming against concrete class
Suppose in the future you will change StrLenCmp with another implementation (let's call it NewStrLenCmp) than if you have programmed against interface Comparator you don't have to modify aClass.
Comparator c = Host.STRING_LENGTH_COMPARATOR; //still work because interface doesn't changed
NewStrLenCmp c = Host.STRING_LENGTH_COMPARATOR; // problem: you need to modify the client class in order to use the new concrete type: bad idea
It's the same problem as making anything public - encapsulation.
The narrowest possible scope for an object makes it much easier to reason about how that object is used, and can ease maintenance massively (you know a private object can only be used in the same source file you're looking at, but you can never truly know how many people are using a public object or in what ways).
Every Java program would work if you declared everything as public, sure. But it's a bit like Pandora's box - once you've opened up access to something, it's hard to take it back.
By not making the concrete strategy public, you prevent other classes/apps being able to use it for their own purposes, which means you don't have to worry about designing it as a fully-fledged, shiny, stable, public class with a well-defined interface. You can just write what works for you, right now, and know that you have the freedom to change it however you want later.
Public stuff is your API. If you ship your code and later need to change your strategy implementation, you have effectively broken your API for everyone you shipped code to.
So until otherwise required, everything should be in the narrowest scope possible.
We also put it into a static nested class because we aren't using this strategy elsewhere.
Related
Suppose, there are two java classes.
BaseA
public class BaseA extends ModuleBase{
public void doSomething{
//does something
}
}
BaseB
public class BaseB extends ModuleBase implements
SomeInterface {
public void doSomething{
//does something
}
}
SomeInterface
public interface SomeInterface {
public void doSomething();
}
so as you can see the only difference between BaseA & BaseB is that BaseB implements an interface. As far my understanding an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It cannot be instantiated.
Questions:
it seems BaseA & BaseA would be same as the methods & code in them is same. correct?
Interface seems like a contract that spells out how software APIs interact with each other & have no effect on class functions. only purpose of interface is to enforce that BaseB has mandatorily implement doSomething, where as with BaseA, its optional & won't generate compile errors. if not, then why?
What difference implementing an interface make? I know you have to implement all methods of that particular interface but if can also you do that without the keyword implements InterfaceName as seen in BaseB Vs BaseA where we implemented exact same doSomething(). what difference having the keyword implements InterfaceName in class declaration make?
No. Classes in Java are the same when they have the same fully qualified name and when they were loaded from the same classloader. Java makes no attempt to look into methods and it doesn't compare method signatures.
Or to put it differently: Java doesn't support duck typing.
Usually, interfaces are used to make a bunch of classes easily interchangeable. So you have something that needs a certain functionality. Instead of typing this to a single class, you can use an interface. People using that service can then feed it with different classes, according to their needs, making the service much more flexible (and somewhat harder to understand).
It means you can use BaseB in any place where InterfaceName is expected. That makes BaseB (and everything derived from it) much more useful/powerful.
Example:
If you want to check passwords, you can write a PasswordService class. But that means everyone has to use this class and live with the limitations.
If you offer a PasswordService interface, then users of your code can have different implementations: They can get passwords from a file, a database, LDAP, ... or for unit tests, they can write a service that says yes or no to every password.
what difference having the keyword implements InterfaceName in class declaration make?
You can then cast to that interface.
Java is not duck-typed.
Even if your class has a method void run() like a Runnable, you still won't be able to give it to places that want a Runnable without implementing the interface.
new Thread(instanceOfMyNotRunnableClass); // won't compile
Two classes are not same by their code. The code may be same but classes are still different. Two classes with same code may behave similar but will not be same.
To understand purpose of Interface, you should understand concepts of Abstraction and Encapsulation. Interface not only provides a contract, also provides an abstraction over underlying classes. You may write an API that takes object of type Interface without bothering about actual class implementing the Interface.
You can use BaseB in place where InterfaceName but you should not. This makes your code rigid for using only BaseB, whereas you may write an utility that takes any class that has implemented the interface.
Well, I assume that SomeInterface declares "doSomething", right?
If that's the case, the benefit for you is that you can treat BaseB as SomeInterface. Let's say you have another class BaseC, which also implements SomeInterface, then this code is valid:
SomeInterface inter = new BaseB();
inter = new BaseC();
while this is not valid:
SomeInterface interr = new BaseA();
Your advantage is, that you do not have to know, if inter is BaseB() or BaseC(), because you simple work on the interface declared methods, no matter how the implementation excatly looks like.
Interface is used to make skeleton of your API. Like java.util.ArrayList and java.util.LinkedList both are classes which implement interface java.util.List.
So if you have method like below
void doSomething(java.util.List list){
}
You can pass java.util.ArrayList or java.util.LinkedList as per your requirment with no harm.You don't have to create two diff. methods where one accept java.util.ArrayList and another accept java.util.LinkedList
I was thinking about programming to interfaces and not to concrete classes, but I had a doubt: should any interface method be able to hold references to concrete classes?
Suppose the following scenarios:
1)
public interface AbsType1 {
public boolean method1(int a); // it's ok, only primitive types here
}
2)
public interface AbsType2 {
public boolean method2(MyClass a); // I think I have some coupling here
}
Should I choose a different design here in order to avoid the latter? e.g.
public interface MyInterface {} // yes, this is empty
public classe MyClass implements MyInterface {
// basically identical to the previous "MyClass"
}
public interface AbsType2 {
public boolean method2(MyInterface a); // this is better (as long as the
// interface is really stable)
}
But there's still something that doesn't convince me... I feel uncomfortable with declaring an empty interface, though I saw someone else doing so.
Maybe and Abstract Class would work better here?
I am a little bit confused.
EDIT:
Ok, I'll try to be more specific by making an example. Let's say I'm desining a ShopCart and I want of course to add items to the cart:
public interface ShopCart {
public void addArticle(Article a);
}
Now, if Article were a concrete class, what if its implementation changes over time? This is why I could think of making it an Interface, but then again, it's probably not suitable at least at a semantic level because interfaces should specify behaviours and an Article has none (or almost none... I guess it's a sort of entity class).
So, probably I'm ending up right now to the conclusion that making Article an abstract class in this case would be the best thing... what do you think about it?
I would use interfaces because composition is much better than inheritance. "Should any interface method be able to hold references to concrete classes ?", why it shouldn't? Some classes within package are coupled, it's a fact and common use technique. When you marked this relation in interface then you see on which classes is dependent your implementation. Dependency or composition relations are not inheritance so a i would avoid abstract class.
In my opinion Interfaces are fine for all types where the implementation may vary. But if you define a module which introduces a new type, that isn't intended to have alternative implementations then there is no need to define it as an Interface in the first place. Often this would be over-design in my opinion. It depends on the problem domain and often on the way how support testing or AOP-weaving.
For example consider a 2D problem domain where you need to model a Location as a type. If it is clear that a Location is always represented by a x and y coordinate, you may provide it as a Class. But if you do not know which properties a Location could have (GPS data, x, y, z coordinates, etc.) but you rely on some behavior like distance(), you should model it as an Interface instead.
If there are no public methods which AbsType would access in MyClass then the empty interface is probably not a good way to go.
There is no interface declaration (contract) for static methods, which otherwise might make sense here.
So, if AbsType is not going to use any methods from MyClass/MyInterface, then I assume it's basically only storing the class object for some other purpose. In this case, consider using generics to make clear how you want AbsType to be used without coupling closely to the client's code, like
public class AbsType3<C extends Class<?>> {
public boolean method3(T classType) {...}
}
Then you can restrict the types of classes to allow if needed by exchanging the <C extends Class<?>> type parameter for something else which may also be an interface, like
<C extends Class<Collection<?>>>.
Empty interfaces are somewhat like boolean flags for classes: Either a class implements the interface (true) or it doesn't (false). If at all, these marker interfaces should be used to convey an significant statement about how a class is meant to be (or not to be) used, see Serializable for example.
I'm designing of a project I have to do. For that, I have thought to use decorator design pattern. However, I have to adjust my design to the existing implementation of the project. Then, I can't keep completely the decorator design pattern.
The project has an abstract base class (called A) and a set of sub-class (called A1, A2, A3, A4, etc.). I can't modify the code of these classes.
Then, I have to add extra funcionality to these classes. For that, I create an abstract class (called B) that use to class A (Decorator). I also create concrete decorators that use to classes A1,A2,A3,A4,...
NOTE: As you see, I don't use any interface because the class A doesn't use any interface and I can't modify this code.
But I see some issues in this design:
1) Classes B1,B2,B3,B4,... have to add all methods of classes A1,A2,A3,A4,... for calling to methods of classes A1,A2,A3,A4... For example, in class B1:
class B1 {
public A1 objectA1;
B1() {
objectA1 = new A1();
}
public void add(int value) {
objectA1.add(value);
// extra funcionality
}
}
It can be a problem because if other developers modify the code of classes A,A1,A2,A3,A4,... they also need to modify the code of B,B1,B2,B3,B4,...
I WANT TO PREVENT THAT.
2) Moreover, classes A,A1,A2,A3,A4 have protected methods that only can be accessed from the own class or sub-classes. As I need to access to these methods, I can't use the decorator design pattern.
SECOND ALTERNATIVE
I could extend the classes A1,A2,A3,A4 with B1,B2,B3,B4. For example:
class B1 extends A1 {
B1() {
objectA1 = new A1();
}
public void add(int value) {
super.add(value);
// extra funcionality
}
}
Of this way, I solve the second problem and avoid to override all methods of A1, overriding only necessary methods. Even so, each time a sub-class of A is created, it's necessary to create the corresponding class B.
I WANT TO PREVENT THAT because it only is necessary that class B (B1,B2,...) override a method of class A (A1,A2,...).
THIRD ALTERNATIVE
Then, I thought that I could consider to class B (B1,B2,...) as a wrapper of class A (A1,A2,...). Of this way, a instance of B will be created as next:
new BMaker.get(A1, params_of_constructor_A1)
new BMaker.get(A2, params_of_constructor_A2)
new BMaker.get(A3, params_of_constructor_A3)
new BMaker.get(A4, params_of_constructor_A4) or
...
new BMaker.get(AN, params_of_constructor_AN)
where BMaker.get is a static method.
public static <T extends A> A get (T objectA, params ) {
// return anonymous class (*1)
}
My question is if it's possible to implement an anonymous class that inherit of A1, A2, ...
Each call to BMaker.get() should be created a different anonymous class deppending on if the first parameter of BMaker.get() is A1,A2,A3,...
Really, I don't know if it's possible to do this or is there another better way.
Any help would be appreciated!
Answer to the first issue:
Either put an interface I on A so your decorators/delegates can implement same interface, or
Create an interface I (equivalent to A's api) and a wrapper class AW which wraps A and implements I by passing all calls straight onto it.
Convert your client code to use I rather than A, and you can then happily proceed to build decorators/ or delegates using the new interface having "wrapped up" the old crunk in AW.
The one notable issue that arises is that some styles of code using A (IdentityHashMaps, persistence) may want a reference to the "underlying" A. If that comes up, you can put a method in the interface getUnderlyingA(). Try and avoid using that too much, since it obviously bypasses all decoration.
Second issue: decorating subtypes.
The question here is whether the subtypes need to be exposed as different decorator types -- or whether one uniform decorator can be exposed, that (maybe, if necessary) is internally aware of the type-system of the A subtypes that it can wrap.
If the subtypes are well-known & stable, you can implement a "handle style" api in the interface. For example, for file-system entities, you would present a handle of a single type but offer isFile(), isDirectory(), isDevice(), isDrive(), isRaw() etc methods for interrogating the type. A listFiles() method could be available to use the directory subtype.
My question is why you need external access (from the decorator) to protected methods? If you do, those methods should be public and the original design is broken/insufficiently extensible.
Maybe you can create a static helper class in the same package (if not changing the A class itself) that will give you proper access to this legacy crunk from your decorator.
There's a certain point here, where doing your job properly does sometimes involve working with & potentially upgrading legacy code. If there isn't an efficient & maintainable design alternative, that shouldn't be a total sticking point. Doubling up the type-system (creating two parallel heirarchies) is definitely not what you should be doing.
If there isn't a good way to do this, you should work on something else (a different feature/requirement) rather than making the codebase even worse.
Why should we declare an interface inside a class in Java?
For example:
public class GenericModelLinker implements IModelLinker {
private static final Logger LOG =LoggerFactory.getLogger(GenericModelLinker.class);
private String joinAsPropertyField;
private boolean joinAsListEntry;
private boolean clearList;
private List<Link> joins;
//instead of a scalar property
private String uniqueProperty;
public interface Link {
Object getProperty(IAdaptable n);
void setProperty(IAdaptable n, Object value);
}
}
When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).
If you want to emphasize the fact that this cooperative class makes strictly no sense (has no use) outside the original object use, you could make it nested/inner.
Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.
In the JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...
And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.
If the interface definition is small and the interface will only be used by clients of the class it's defined in, it's a good way to organize the code. Otherwise, the interface should be defined in its own file.
This is inner interface. Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class.
Some people use this mechanism for creating a kind of namespace. IMHO this is abuse of the language feature (in most cases).
To encapsulate behavior in a generic and resuable way.
Apart from nice example of Map.Entry used by Map implementation classes another good example is implementation of Strategy Pattern, where a execution strategy is evaluated and applied internally.
class Test
{
..
interface Cipher {
doAction();
}
class RAMPCipher implements Cipher{}
class DiskCipher implements Cipher{}
..
}
Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one.
Only an interface inside a class can be declared private or protected. Sometimes, that makes sense, when the interface is only appropriate for use inside the outer class (or its subclasses).
I have used Java for quite a long time, but I never did find out, what makes factories so special. Can somebody please explain it to me? Is there any reason why I should want to implement my own factory (if it's even possible)?
Factory Patterns are fantastic for decoupling classes. For example, let's assume a common interface, Animal, and some classes that implement it. Dog, Cat.
If you do not know what the user will want to generate at run time, then you can not create a Dog pointer. It simply won't work!
What you can do though, is port that to a separate class, and at run time, pass a discriminator to the factory class. The class will then return the object. For example:
public Animal getInstance(String discriminator)
{
if(discriminator.equals("Dog")) {
return new Dog();
}
// etc.
}
And the calling class simply uses:
String type = "Dog";
Animal value = Factory.getInstance(type);
This makes code extremely readable, separates decision logic from the logic performed on the value and decouples the classes via some common interface. All in all, pretty nice pattern!
IMO the biggest benefits of Factory classes are configuration and data encapsulation. API design is perhaps the most common scenario where such classes come in really handy.
By offering developers Factory classes instead of direct access, I have a way to easily preventing from someone messing up with the internals of my API, for instance. Through Factory classes I also control how much you know about my infrastructure. If I don't want to tell you everything about how I provide a service internally, I will give you a Factory class instead.
For reliability and uniform design purposes, the most crucial internals should be enclosed in Factory classes.
They are a way to make sure that a random developer that comes along will not:
Break internals
Gain unwanted privileges
Break configuration formats
Another good example can be the following. Imagine that the user want to uses somes collections to performs actions (in this case choose the collections to create an inverted index). You can create an interface like :
interface CollectionsFactory {
<E> Set<E> newSet();
<K, V> Map<K, V> newMap();
}
Then you could create a class which take a collections factory as parameter.
public class ConcreteInvertedIndex implements InvertedIndex {
private final Map<String, Set<Document>> index;
private final Set<Document> emptyDocSet;
private final CollectionsFactory c;
public ConcreteInvertedIndex(CollectionsFactory c){
this.c = c;
this.index = c.newMap();
this.emptyDocSet = c.newSet();
}
//some methods
}
And finally it's to the user to decide which collections he wants to use to perform such actions :
CollectionsFactory c = new CollectionsFactory() {
#Override
public <E> Set<E> newSet() {
return new HashSet<E>(); //or you can return a TreeSet per example
}
#Override
public <K, V> Map<K, V> newMap() {
return new TreeMap<K, V>();//or you can return an HashMap per example
}
};
InvertedIndex ii = new ConcreteInvertedIndex(c);
Use the Factory Method pattern when
· a class can't anticipate the class of objects it must create.
· a class wants its subclasses to specify the objects it creates.
· classes delegate responsibility to one of several helper subclasses, and
you want to localize the knowledge of which helper subclass is the delegate.
Factories are widely used in JDK to support the concept of SPI (service provider interface) - API intended to be implemented or extended by a third party. E.g. DocumentBuilderFactory.newInstance() uses a complicated 4-step search algorithm to find the actual implementation.
I think programmers who develop not libraries but applications should favour "simple is best" approach in software design.
You use them in combination with private constructor to create singletons. It assures that the bean (probably, a service) can not be created as a non-singleton.
You can also forbid the creation of the class with the constructor by making it private, so that you could add some logic in the factory method and nobody could bypass it.
EDIT: I know a person who would replace a constructor in every bean by a method "create" with parameters (in order to centralize the bean population logic), but I am not a big fan of this approach.