Consider this interface
public interface IDoSomething {
void DoAAA();
void DoBBB();
void DoCCC();
}
and these two implementations
public class MyObject1 implements IDoSomething {
public MyObject(int a, xObjx x)
..
}
public class MyObject2 implements IDoSomething {
public MyObject(int a, xObjx x)
..
}
How can I not expose the implementation classes to other developers? Specifically how can I prevent the following?
IDoSomething C = new MyObject2();
Is using a factory class the best practice?
public class DoSomethingFactory {
static IDoSomething getDoSomething(int a, xObjx x) {
...
}
}
How can I extend this pattern to include implementations that have different constructors?
If you're always going to be constructing the MyObject1/2 instances in your own code, you might be able to make them package private (default permissions). A "builder" pattern might make sense too.
Can you maybe elaborate on how / why it matters if the constructors of the objects are exposed? Interfaces just define functionality requirements, not construction requirements.
Good software is written on a need to know basis. The more ignorant a component is about how its companion classes get the job done the better. That is purpose that interfaces serve. They allow willfully ignorant programmers to write code on a need to know basis.
One problem is a programmer that wants to know can almost always know. Even if you could prevent the assignment which you can't, they can cast the obfuscated object into its implementation, inspect its properties and methods with reflection, or pipe the jar into a hex editor. This isn't really something you can stop.
What you can do is write code that makes the lives of need to know programmers easier, clearly communicates the intention of your design, and reduces the temptation for programmers to cheat(using dirty implementation details as a crutch). The best way accomplish this is to use Creational Patterns.
In reference to your point about constructors being different this is handled nicely by all the basic creational patterns. Because they provide an abstraction over the constructor. You get to decide how much or how little detail to expose. Maybe you have a constructor like the one below:
public ColorThing(int r ,int g, int b)
that accepts numeric color values. In your implementation of a creational pattern you might decide to simplify this by making the constructor private and only allowing access to a static factory method.
private ColorThing(int r , int g, int b){
...
}
public static ColorThing buildRedColorThing(){
return new ColorThing(100,0,0);
}
This would limit consumers of your ColorThing class to only being able to construct red things.
Listed below are several basic creational patterns that sort of do what you want. They provide varying degrees of obfuscation building up to the Abstract Factory Pattern which yields the highest degree of encapsulation but also requires the most boiler plate.
Static Factory Method
This is the guy from the ColorThing example above. This simply provides a public static method on the class that protects the nitty gritty details of the constructor. Great for simplifying access to a constructor with lots of parameters. In this case, you can make your constructor private and provide as many static factory methods as you need.
public class MyObject1 implements IDoSomething {
private int prop a;
public static IDoSomething getAnObject(int a){
return new MyObject(a, new xObjx());
}
private MyObject(int a, xObjx x)
...
}
The Builder Pattern
The builder pattern has an accompanying class responsible for creating your class. It uses java's scope rules to ensure that the constructor is accessed in a secure fashion. This is also very useful if you want to have a lot of telescoping constructor args because you can rely on dot chaining of the methods of the builder class (new MyObject1.MyObjectBuilder().setA(2).build())
public class MyObject1 implements IDoSomething {
private int prop a;
private MyObject1(int a, xObjx x)
...
public class MyObjectBuilder {
private int a;
public MyObjectBuilder setA(int a){
this.a = a;
return this;
}
public IDoSomething build(){
return new MyObject1(a, new xObjx);
}
}
}
Abstract Factory
The Abstract Factory Pattern allows you to completely encapsulate the construction of a class. This will only every expose the interface, but it also has the most boiler plate because you have to create a Factory and a set of Product implementations and interfaces for each family of classes you want to manufacture. Here is a text book example of how the classes in this pattern relate. This pattern is highly extensible and you will see it used to great effect in lots of library code. This is because the designers of these libraries commonly don't know the full set of implementations their framework code will need to support. By using an Abstract Factory Pattern they can let future developers build on their code while limiting the restrictions imposed by their assumptions.
Which one you pick will be entirely contingent on your circumstances, but you should start with the simplest one that satisfies your needs and work your way to the more complex ones.
Related
Are there any hard and fast rules on the use of this pattern or is it solely intended as a way to achieve additional functionality within method calls without using inheritance?
I have amended the example below that I took from a SO post to demonstrate what I am considering.
public interface Coffee {
public double getCost();
public String getIngredients();
}
public class SimpleCoffee implements Coffee {
#Override
public double getCost() {
return 1;
}
#Override
public String getIngredients() {
return "Coffee";
}
}
public class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
public CoffeeDecorator(Coffee c) {
this.decoratedCoffee = c;
}
#Override
public double getCost() {
//you can add extra functionality here.
return decoratedCoffee.getCost();
}
#Override
public String getIngredients() {
//you can add extra functionality here.
return decoratedCoffee.getIngredients();
}
public boolean methodNotDefinedInInterface() {
//do something else
return true;
}
}
So with the example above in mind, is it viable to:
a) use the simple Coffee whenever you see fit without decorating it
b) Add additional functionality that is not defined in the Coffee interface to decorator objects such as the methodNotDefinedInInterface()
Could someone also explain where the composition comes into this pattern as the SimpleCoffee is something that can exist in its own right, but it seems to be the decorator that actually 'owns' any object.
Although without the SimpleCoffee class (or some concrete implementation of Coffee) the decorator doesnt have any purpose, so aggregation doesnt seem to be what is occurring here.
The description of the pattern includes intent which makes it pretty clear what the pattern is for:
The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time.
As for "hard and fast rules" - I generally don't think that there are "hard and fast rules" in patterns at all. Like, if you don't implement it exactly as GoF described, there will be no "pattern police" punishing you. The only point is that if you follow the classic guidelines, other developers will have less problems recognizing patterns in your code.
Your example is quite OK from my point of view.
SimpleCoffee is not a decorator, so no composition there. CoffeeDecorator has decoratedCoffee as a component (here you have your composition)
a) use the simple Coffee whenever you see fit without decorating it
Yes, of course.
b) Add additional functionality that is not defined in the Coffee
interface to decorator objects such as the
methodNotDefinedInInterface()
You can add more methods just like adding new methods to SimpleCoffee class, but note that you would need to use those additional methods somewhere in the decorator class.
Personally, I find this pattern useful when someone gives you an instance of Coffee (i.e. you didn't instantiate it). If you need to change its behavior at runtime, the only way is to wrap it inside another object of Coffee type. This is when you can throw it into the decorator class. The decorator can expose some of the original behavior while providing some new behaviors.
I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.
For instance, processing.org has an interface called PConstants.java, and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums where it makes sense, or a static class?
I find it strange to use an interface to allow for some sort of pseudo 'global variables'.
public interface PConstants {
// LOTS OF static fields...
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
// and on and on
}
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
I do not pretend the right to be right, but lets see this small example:
public interface CarConstants {
static final String ENGINE = "mechanical";
static final String WHEEL = "round";
// ...
}
public interface ToyotaCar extends CarConstants //, ICar, ... {
void produce();
}
public interface FordCar extends CarConstants //, ICar, ... {
void produce();
}
// and this is implementation #1
public class CamryCar implements ToyotaCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
// and this is implementation #2
public class MustangCar implements FordCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...
Constants should not be changed, because the wheel is round and egine is mechanical, but...
In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface
public interface InnovativeCarConstants {
static final String ENGINE = "electronic";
static final String WHEEL = "flat";
// ...
}
and now we can change our abstraction:
public interface ToyotaCar extends CarConstants
to
public interface ToyotaCar extends InnovativeCarConstants
And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations
Its NOT SAFE, I know,
but I still want to know that do you think about this
There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:
The concepts are part of the public interface of several
classes.
Their values might change in future releases.
Its critical that all implementations use the same values.
For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.
So you write a public interface with the static constant:
public interface SyntaxExtensions {
// query type
String NEAR_TO_QUERY = "nearTo";
// params for query
String POINT = "coordinate";
String DISTANCE_KM = "distanceInKm";
}
Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.
PS: The inspiration for this example is drawn from the Neo4j spatial code.
Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.
Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.
If a client wants to compare cars prior to buying he can have a method like this:
public List<Decision> compareCars(List<I_Somecar> pCars);
An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.
This came from a time before Java 1.5 exists and bring enums to us. Prior to that, there was no good way to define a set of constants or constrained values.
This is still used, most of the time either for backward compatibility or due to the amount of refactoring needed to get rid off, in a lot of project.
I am considering to encapule certain "not very often accessed" attributes and functionalities into their own "config" and "extended" - Objects within the data structure, so that I can offer to user defined callback functions an object of a type that only gives access to the most commonly used functions and attributes and offering a "getExtended" method that returns the same object with another type that offers uncommonly used functions.
This idea is mostly based around having a slim list of auto-completion friendly functions so that development with IDEs like Eclipse flows more smoothly when writing code using the most commonly used methods of the offered object, and not having to filter out the methods that are mostly used to do one-time configuration at a very specific place in the code.
Am I falling here into an obvious anti-pattern trap or is this actually a good way to lay out the structure of an easy to use lib?
One way to do this is to use interfaces. Interfaces can be extended through inheritance just like classes. Your collection could reference a base interface, say ISimple like below. Your getExtended() could return the IAdvanced interface. Both could be implemented by the same object (if they share identity and purpose), or by different objects. The decision of whether to implement together or not should really be based on the Single Responsibility Principle. Here is some sample code:
interface ISimple {
IAdvanced getAdvanced();
int getLength();
String getName();
}
interface IAdvanced extends ISimple {
void verifyAllTheThings();
}
class Implementation implements IAdvanced {
public IAdvanced getAdvanced() { return this; }
// ISimple
public int getLength() { return 2; }
public String getName() { return "something"; }
// IAdvanced
public void verifyAllTheThings() { /* do stuff */ }
}
I think you really are asking if this is a bad pattern or not. In and of itself it is not a bad pattern (IMHO), but there is different design problem implied by your question. If your motivation of being friendly with IDE's is because there are are a huge number of methods on each object, then that is possibly a questionable design. Again, the Single Responsibility Principle is a good guide to tell you if your object is doing too much, and should be split apart into separate concerns. If so, then doing a simple/extended split is a possibly weak way to divide up the set of all methods, and instead you might want to consider breaking up the object along more conceptual lines.
Duane already get to the point, but sadly missed the mark with using the interface. An interface can be inherited but not always need to. And yes, using interface to limit the method accessibility is the right way to do it.
As example, actually you can:
interface ITwoDimensional {
int getWidth();
int getLength();
}
interface IThreeDimensional extends ITwoDimensional {
int getHeight();
}
interface ISpherical{
int getRadius();
}
class Consumer{
int calculateArea(ITwoDimensional a){
// you can only access getLength() and getWidth();
}
int calculateArea(ISpherical a){
// you can only access getRadius();
}
int calculateArea(IThreeDimensional a){
// you can access getLength(), getWidth() and getHeight();
}
}
That is only the basic example. There are many more design available with interface access.
When laying out a class hierarchy, I often find myself frustrated at the gap between being able to encapsulate functionality while also sharing code. Part of the problem, of course, is lack of multiple inheritance, but interfaces help somewhat. The inability to define protected methods on interfaces seems to me to be the bigger issue.
The standard solution seems to be to have a public interface that is implemented by a protected abstract base class. The problem is when we have the following
public interface Foo {
public String getName();
}
abstract protected BaseFoo implements Foo {
abstract protected int getId();
private String name;
protected BaseFoo(String name) {
this.name = name;
}
#Override
public String getName() {
return this.name;
}
}
public class ConcreteFoo extends BaseFoo {
public ConcreteFoo (String name) {
super(name);
}
#Override
protected int getId() {
return 4; // chosen by fair dice roll.
// guaranteed to be random.
}
}
// in the foo package with the classes above
public class FooCollection {
private static Map<Integer, Foo> foos = new HashMap();
public static void add(Foo foo) {
synchronized(foos) {
foos.put(foo.getId(), foo); // can't call foo.getId()
}
}
}
// client code, not in the foo package
FooCollection.add(new ConcreteFoo("hello world"));
That is, we return one of our nicely-encapsulated objects to caller, but then any method which gets that object back needs to be able to rely on some internal functionality. That internal functionality cannot be part of the interface (that would break encapsulation), but to make it part of an abstract base class requires us to use casting.
We cannot make Foo an abstract class because other interfaces need to extend it to add optional, orthogonal functionality to a more complex hierarchy than is display here.
What are the standard approaches to this problem? Do you add getId to the Foo interface, even though clients shouldn't use it? Do you perform an unsafe cast to BaseFoo in FooCollection.add? If you check before casting, what do you do when the types don't match, even though they always should for all intents and purposes?
Any information you have on best practices in this sort of situation would be very helpful.
Edit: In case it's not clear, this example is intentionally oversimplified. The key point is that sometimes you return an "interface view" of an object. When that "interface view" is passed back in to a package-specific class, the method it is passed to will likely need to use internal functionality in its implementation. How does one manage that mismatch between internal and public functionality?
Okay, here's a couple of points:
Contrary to popular opinion, inheritance really isn't about sharing code. What you create in an inheritance hierarchy is an organization of things that share some common set of abstract behaviors; it just works out sometimes to have the effect of reusing some code.
The fashion has changed quite a bit in the last few years, so that deep and complicated inheritance hierarchies are no longer considered good form. In general in Java. you should
use aggregation before implementing an interface
use interfaces to express "mix-in" contracts
use inheritance only if the classes describe something that has natural inheritance.
If you really want the effect of multiple inheritance, build implementation classes for your interfaces, and aggregate them.
In particular, by defining your classes with interfaces and implementation classes, you make building tests much easier; if your interface is separate, it's almost trivial to build a mock for that interface.
I don't know about "best" practices, but here are a couple of ideas.
Interfaces are supposed to separate "what is to be done" from "how something is to be done". I don't think getters and setters belong in interfaces. I try to give them more meaningful signatures.
In your case, I see nothing wrong with two interfaces:
public interface Nameable {
String getName();
}
public interface Identifiable {
int getId();
}
Separate the two; force clients to implement only the ones they need. Your decision to make id part of the abstract class is arbitrary. Separating it out and making it explicit can be helpful.
Casting loses all benefit of polymorphism. I don't think that it should be abandoned lightly. If you must move getId() up to the interface, do so. If you can avoid it by different choices, do so.
"Best" depends on your context. Your simple example might not be true in all cases.
I am trying to incorporate more functional programming idioms into my java development. One pattern that I like the most and avoids side effects is building classes that have behavior but they don't necessarily have any state. The behavior is locked into the methods but they only act on the parameters passed in.
The code below is code I am trying to avoid:
public class BadObject {
private Map<String, String> data = new HashMap<String, String>();
public BadObject() {
data.put("data", "data");
}
/**
* Act on the data class. But this is bad because we can't
* rely on the integrity of the object's state.
*/
public void execute() {
data.get("data").toString();
}
}
The code below is nothing special but I am acting on the parameters and state is contained within that class. We still may run into issues with this class but that is an issue with the method and the state of the data, we can address issues in the routine as opposed to not trusting the entire object.
Is this some form of idiom? Is this similar to any pattern that you use?
public class SemiStatefulOOP {
/**
* Private class implies that I can access the members of the <code>Data</code> class
* within the <code>SemiStatefulOOP</code> class and I can also access
* the getData method from some other class.
*
* #see Test1
*
*/
class Data {
private int counter = 0;
public int getData() {
return counter;
}
public String toString() { return Integer.toString(counter); }
}
/**
* Act on the data class.
*/
public void execute(final Data data) {
data.counter++;
}
/**
* Act on the data class.
*/
public void updateStateWithCallToService(final Data data) {
data.counter++;
}
/**
* Similar to CLOS (Common Lisp Object System) make instance.
*/
public Data makeInstance() {
return new Data();
}
} // End of Class //
Issues with the code above:
I wanted to declare the Data class private, but then I can't really reference it outside of the class:
I can't override the SemiStateful class and access the private members.
Usage:
final SemiStatefulOOP someObject = new SemiStatefulOOP();
final SemiStatefulOOP.Data data = someObject.makeInstance();
someObject.execute(data);
someObject.updateStateWithCallToService(data);
Edit-1: This is a good comment. My response: "As soon as you make the Data class accessible outside the main class you are exposing implementation details, " -- comment.
My Response: The Data class is a simple POJO and will work like other pojos with setters and getters. What I was doing in the class above was trying to only manipulate the Data class from the behavior class, SemiStatefulOOP. I do intend to have stateless classes but I wanted to have a clear separation from the state classes and the behavior classes.
Related:
Stateless Design Pattern
http://guides.brucejmack.biz/Pattern%20Documents/Stateless%20Design%20Pattern.htm
There's an interesting OO architectural style that aims to separate the data and the behavior of a system, so that they can evolve independently: the DCI Architecture.
In practice, you create data objects for your domain concepts (possibly only with simple behavior related to the data itself); and behavior objects that work with the data objects and that realize the use cases of the system. These behavior objects are seen as roles that the domain objects can play, and are materialized with the OO concept of a trait (pdf).
Scala has traits, but Java doesn't. You can try to use the Qi4J framework in Java for that.
One of the key points of OO programming is that you hide implementation details. Your approach doesn't seem to be doing that - as soon as you make the Data class accessible outside the main class you are exposing implemntation details, and effectively exposing data representation.
It is of course impossible to make all classes stateless - something has to hold the state, and it's not clear to me why holding it in Data is preferable to holding it in the main class.
Finally a principle of OO programming is to keep data and functionality related to it in the same place, i.e. the same class. In short, while your proposal is interesting, I think the problems it creates are worse than the problems it solves.
building classes that have behavior
but they don't necessarily have any
state
See wiki
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
I'm not sure I understand quite what you're asking here. As an alternative to BadObject's statefulness, could you not simply declare the method as
public void execute(Map<String, String> data) {
...
}
or similar?
In general, when I think of functional and/or stateless idioms, the overwhelming code pattern that crops up is to have methods take parameters for everything they depend on (instead of getting them from fields or static methods or train wrecks (getFoo().getCustomer().getAddress().getHouseName())). That and return the result, rather than modifying the state of other objects.
At this point, all the data classes can be immutable since there's nothing to modify, which makes the code much easier to understand and reason about.
This wouldn't be one of the original GoF patterns, but I believe Josh Bloch has a paragraph on this in Effective Java entitled something like "Prefer immutability", which is catchy enough.
I think that the best solution to incorporate more functional programming into your projects is to use a functional programming language, like Scala. Scala is fully interoperable with Java and compatible with JVM. Scala classes is Java classes and vise versa. Why not to try it... :)
Java is full OOP language and my opinion is that functional paradigms just doesn`t fit nicely into it.
It looks like you have utility classes.
public class Data {
private static final Map<String, String> data = new HashMap<String, String>();
static {
data.put("data", "data");
}
private Data() { }
/**
* Act on the data class.
*/
public static void execute() {
data.get("data").toString();
}
}
You don't need to create an object.
Data.execute();