Which design pattern to use (if exists)? - java

I have a question about OOP implementation and design patterns.
I have a fixed class model which I cannot change (because it is generated automatically each time the application starts). There are many classes there with equals fields like in example below: as you can see the fields city and streets are contained in the both classes.
public class A{
String city;
String street;
String name;
....//get methods
}
public class B{
String city;
String street;
String age;
....//get methods
}
I need to extract an address form the both types of classes and I want to implement it with one method (because it seems to be silly to write the same code twice). If the class model were changeable, I could add a new interface Addressable which A and B could implement.
public interface Addressable{
public String getStreet();
public String getCity();
}
//somewhere in code
public Address getAddress(Addressable addressable){
return new Address(addressable.getCity(), addressable.getStreet());
}
What is the most elegant way to implement the same without interface and without coding the same for different classes?

If you are not able to change A or B, you would have necessarily a degraded solution.
A simple and good designed solution would rely of course on a interface defining an Address retrieval method (Address getAddress()) that A and B would implement.
You could also define a wrapper class :
public class WrapperA implements Addressable {
private final A a;
public WrapperA(A a) {
this.a = a;
}
#Override
public Address getAddress(){
return new Address(a.getCity(), a.getStreet(), etc...);
}
}
But it may be rather clumsy if you have to duplicate this kind code for many classes.
Besides the client will not manipulate any longer a A but a WrapperA class.
It may break the actual client code.
So also here, an interface is required if you want to implement a real adapter.
As said, without redesigning a minimum A or B, a really good solution is complicated.
As workaround, you may define an Address class that provides factory methods to create Address from a A or a B instance.
public class Address{
...
String city;
String street;
...
private Address(){
}
public static Address of(A a){
return new Address(a.getStreet(), a.getCity(), ....);
}
public static Address of(B b){
return new Address(b.getStreet(), b.getCity(), ...);
}
}
Then use these methods to create the Address on the demand as you need it.

You could write adapters to provide a common interface.
public class AdpaterA implements Addressable {
private final A a;
public AdapterA(A a) {
this.a = a;
}
#Override public String getStreet() {
return this.a.street;
}
// other method is omitted as homework ;-)
}
Then you would use the adapter classes for further processing.

I had a similar situation, where classes are generated during the build process. (In my case, the build process would inspect the database, and generate one class per database table, with all the fields.)
You state that the classes are generated when your application starts. In case they are generated during the build process, you can add an extra element to the build process which alters the genreated files. In my case our build servers were only Linux, so I added a sed line to our ant script.

Related

How can Extract Class Eclipse IDE refactoring functionality be useful?

I came across a refactoring functionality that looks to be useful as I learn eclipse and java. But I'm not sure how this could be useful. Is there a pattern that would benefit from this kind of refactoring? This refactoring option basically extracted out all variables into another class whose name was changed to append Data at the end.
Any examples of WHAT/WHY this kind of refactoring gives us would be really helpful.
Thank you in advance.
Extract Class is mostly used when a class has too many responsibilities; it is trying to do too much. It splits out the class into two individual classes and then transfers some functionality into the other class - obviously there will be a relationship between the classes because you still want all of the code to interact.
You can combine Extract Class with other refactoring patterns such as Move Method and Move Field that will move methods and fields to the other class in such a way that all of the code still works as intended.
This link has a good example of Extract Class: http://sourcemaking.com/refactoring/extract-class
If you had too many fields in your class and you see that this must be a extra class, you can use it.
Example:
public class Person {
private int age;
private String name;
private String street;
private int streetnumber;
}
to:
public class Person {
private int age;
private String name;
private Adress data = new Adress();
}
public class Address {
public String street;
public int streetnumber;
public Address() {}
}

Inherited enum redefinition

It is more complex than it sounds, but I think I am obliged to try something like it. I want to make an abstract parent class with a prototyping of an enum (I want to declare the enum with only one value probably that will be the default unitialized one and also declaring a couple of methods that I will be using from the subclass), then I want to class that will extend the abstract parent to actually intialize the very same enum (I know that this practically hides the parent enum) so that the kid class will define a set of items inside the enum, but keep the methods probably.
I do not know much about this level of abstraction so I will now describe the nature of my problem, in case there is a more practical solution:
I have a bunch of files that contain classes that implement a lot of commands based on enums. (e.g. class1 implements Observer has an update method that uses an enum-based switch to decide what command was picked, same applies for the other classes) I now want to abstract this whole thing in a way that I have an enum variable with the exact same name in all classes (e.g. CommandSet) so that I can have a generic method inside the parent that will be able to print a help list to my system using the inside methods of the enum. Now I know I can rewrite the exact same method in every class, but I want to abstract it so that others can keep on extending the library I am making!
Hopefully I am not too confusing or too confused and somone can help me! :)
Edit: Here is an idea of the code (Probably not right):
public abstract class Commands{
enum CommandSet{
// empty command, placeholder
null_command ("command name", "command description");
// the Strings used for name and description
private final String name;
private final String description;
// constructor
CommandSet(String name, String description){
this.name=name;
this.description=description;
}
// get parameters
public String getName(){
return name;
}
public String getDescription(){
return description;
}
}
public void showHelp(){
for (CommandSet i : CommandSet.values()) {
printf(i.getName(),":",i.getDescription());
}
}
}
public class StandardCommads extends Commands implements Observer{
// I want to change the enum here, just changing the values so that null_command ("command name", "command description") will get removed and I will add a dozen other values, but keep the methods that the parent had
// update inherited from Observer
#Override
public void update(Observable observable, Object object) {
// I want the commands inside the switch cases defined inside this class's enum
switch(CommandSet.valueOf(String.valueOf(object)){
case command1: doStuff1();break;
case command2: doStuff2();break;
...
case commandN: doStuffN();break;
}
// other methods
void doStuff1(){
...
}
...
void doStuffN(){
...
}
}
public class NonStandardCommads extends Commands implements Observer{
// Another set of commands here for the enum keeping the same methods it had in the parent
// update inherited from Observer
#Override
public void update(Observable observable, Object object) {
// Other set of commands inside this class used in the switch statement
switch(CommandSet.valueOf(String.valueOf(object)){
case Zcommand1: doStuffz1();break;
case Zcommand2: doStuffz2();break;
...
case ZcommandN: doStuffzN();break;
}
// other methods
void doStuffz1(){
...
}
...
void doStuffzN(){
...
}
}
Impossible: Java enums can neither extend another class nor be extended themselves.
They can however implement interfaces. Perhaps you can use that to your advantage.
There is something else about enums that may help you: enums are not immutable. You could change field values of the enums, however that would change them for the whole JVM.
Another approach maybe to pass your subclass instances into a method of the enum and have the enum use your subclass as a call back to get different functionality out of an enum for a different user of the enum.
Nope, you can't do that.
Java Enums run out of gas very quickly & definitely, when you want to add/extend more definitions or instantiate the enum instances, at a later time. (eg load them from database, configure them in an instance method, not just statically.)
Behaviour/ or logic in Java enums is kinda limited too -- you can define & set properties, but only what's statically initializable, and logic seems basic (you end up mainly just comparing references or ordinals, with the other defined enum constants).
What you can do:
You can implement an ancestor Command or AbstractCommand class, with a integer Code, and then subclass it to define concrete values/ additional codes/ load or configure instances, etc.
For further benefit, you get efficient switch & despatch (by Code) plus the ability to define further details/properties, instantiate commands as-needed, etc.
Essentially, this is how you used to define an Enum before Java supported them. Though you may be using them as value objects, rather than strictly static.
My expertise:
I've done extensive compiler & type-system work, tried enums for file-types and associated data/behaviour.. explored the outer limits, and reached the definite boundaries.
I also like being able to instantiate & return a new UnknownFileType("") as an answer, too. Enums can't do that.
Example:
(We'll despatch by String, not int -- since your code appears to be using Java 7. This makes command resolution easier, than requiring both a syntactical "name" and an internal integer "code".)
public static class Command {
protected String code;
protected String desc;
public String getCode() {return code;}
public String getDesc() {return desc;}
public Command (String code, String desc) {
this.code = code;
this.desc = desc;
}
public String toString() {return code;}
}
public class StandardCommands {
public static Command READ = new Command("READ", "read a record");
public static Command CREATE = new Command("WRITE", "create a record");
public static Command EDIT = new Command("WRITE", "modify a record");
}
public class FurtherCommands extends StandardCommands {
public static Command LIST = new Command("LIST", "list all records");
}
public class QueryCommands extends FurtherCommands {
public static class QueryCmd extends Command {
protected String search;
public String getSearch() {return search;}
// constructor..
}
public static QueryCmd QUERY_EXAMPLE = new QueryCmd("QUERY", "example", "query for specified string");
public static QueryCmd createQuery (String search) {
return new QueryCmd( "QUERY", search, "query for specified string");
}
}

Java: force implementor of an interface to have an immutable name field?

Requirement: I'd like all implementations of an interface to have a well-defined name.
Initially, I thought:
interface Fruit {
public String getName();
}
But this allows the user to have a field that is modified at run-time. I want to have an immutable name that is defined before compile/build time.
I've been toying with a couple of other ways to do it, but each has a limitation.
1) Give the name a type, which has slightly more control than free-form strings:
interface Fruit {
public FruitName getName();
}
abstract class FruitName {
public final String NAME;
public FruitName(name) {
this.NAME = name;
}
}
A user of this class will look like this:
class AppleFruitName extends FruitName {
public AppleFruitName() {
super("apple");
}
}
class Apple implements Fruit {
public FruitName getName() {
return new AppleFruitName();
}
}
2) Force an implementor of Fruit to annotate the name with something:
class Apple implements Fruit {
#FruitName
public static final NAME = "apple";
...
}
Clearly this implementation is far cleaner than (1), but I'm not sure if this is possible in Java? How do you get compile/build to fail if #FruitName is not present?
An easy way to do this - without aop, compile time weaving, runtime annotations, scanning at runtime.. etc is to encapsulate this behaviour in an abstract class:
interface Fruit {
public String getName();
}
abstract class FruitImpl {
private final String name;
public FruitImpl(name) {
this.name = name;
}
public final String getFruitName(){
return name;
}
}
So at construction time each implementation will be forced to pass in its name and it will not be able to alter it (unless the user is being intentionally malicious). This meets the what the wording of the question suggests.
There is a difference though because some the suggestions seem to assume that all implementations of the interface will have the same name - though the question doesn't state that. Is the idea that these implementations will be singletons?
Alternatively, you could use the decorator pattern to wrap the implementation and retrieve the field value once and then always return that value later, like this:
class FruitWrapper implements Fruit{
private final String name;
public FruitWrapper(Fruit fruit) {
this.name = fruit.getFruitName();
}
public final String getFruitName(){
return name;
}
}
So you can use it everywhere you would use fruit and it will guarantee to always get the same value.
This way you move the immutability into a class you control.
There are several options to enforce this.
At build time you could write tests for each of the Fruit classes that look for a field that satisfies your requirements.
At build time you could write a single test that goes through your entire classpath and verifies that each Fruit classes satisfies your requirements. A library like Reflections could help you to achieve this.
At compile time you could process an Annotation. I am not sure how you would make sure that each of your classes had an Annotation (as opposed that each class that contains an Annotation is one of the classes in your set.)
At implementation time, as a slight variation on your request, you could use an abstract class instead of an interface and require all implementors to hand you the fixed data in the constructor. That way, you have absolute control over the behaviour.
At runtime, while the application launches, you could check that all implementing classes satify your requirements in the same way an integration test would do it. In a scenario where third parties contribute to your API, this might be the last-stop option if you absolutely have to check it.
I think it is best to use tests for this. You'll have all the certainty you need with far better feedback and much less effort.
If tests are not an option, because you can't control the implementers, I'd go for the abstract class with enforcement during launch as a last resort.
Aren't you confusing static and final?
abstract class FruitName {
private final String name;
public FruitName(String name) {
this.name = name;
}
}
This is the best you can get in terms of interfaces/classes. You can also use custom annotation, but in slightly different way:
#FruitName("apple")
class Apple implements Fruit
And also consider using simple class name:
Fruit fruit = new Apple();
fruit.getClass().getSimpleName(); //"Apple"
But if you depend on class names somewhere, simple refactoring will ruin other parts of the code. So I would consider annotation more stable.
Bonus: your problem is easily solvable in scala:
trait Fruit {
val name: String //abstract AND final
}
class Apple extends Fruit {
val name = "apple" //you MUST implement this
}
If you don't "implement" val name (actually it is an immutable field), compiler will insist on marking Apple abstract.
you should be able to do it with aspectj and compile time waving

What would be the best way to implement a constant object?

First of all I should probably say that the term 'constant object' is probably not quite right and might already mean something completely different from what I am thinking of, but it is the best term I can think of to describe what I am talking about.
So basically I am designing an application and I have come across something that seems like there is probably an existing design pattern for but I don't know what it is or what to search for, so I am going to describe what it is I am trying to do and I am looking for suggestions as to the best way to implement it.
Lets say you have a class:
public class MyClass {
private String name;
private String description;
private int value;
public MyClass(String name, String description, int value) {
this.name = name;
this.description = description;
this.value = value;
}
// And I guess some getters and setters here.
}
Now lets say that you know in advance that there will only ever be say 3 instances of this class, and the data is also known in advance (or at least will be read from a file at runtime, and the exact filename is known in advance). Basically what I am getting at is that the data is not going to be changed during runtime (once it has been set).
At first I thought that I should declare some static constants somewhere, e.g.
public static final String INSTANCE_1_DATA_FILE = "path/to/instance1/file";
public static final String INSTANCE_2_DATA_FILE = "path/to/instance2/file";
public static final String INSTANCE_3_DATA_FILE = "path/to/instance3/file";
public static final MyClass INSTANCE_1 = new MyClass(getNameFromFile(INSTANCE_1_DATA_FILE), getDescriptionFromFile(INSTANCE_1_DATA_FILE), getValueFromFile(INSTANCE_1_DATA_FILE));
public static final MyClass INSTANCE_2 = new MyClass(getNameFromFile(INSTANCE_2_DATA_FILE), getDescriptionFromFile(INSTANCE_2_DATA_FILE), getValueFromFile(INSTANCE_2_DATA_FILE));
public static final MyClass INSTANCE_3 = new MyClass(getNameFromFile(INSTANCE_3_DATA_FILE), getDescriptionFromFile(INSTANCE_3_DATA_FILE), getValueFromFile(INSTANCE_3_DATA_FILE));
Obvisouly now, whenever I want to use one of the 3 instances I can just refer directly to the constants.
But I started thinking that there might be a cleaner way to handle this and the next thing I thought about was doing something like:
public MyClassInstance1 extends MyClass {
private static final String FILE_NAME = "path/to/instance1/file";
public String getName() {
if (name == null) {
name = getNameFromFile(FILE_NAME);
}
return name;
}
// etc.
}
Now whenever I want to use the instances of MyClass I can just use the one I want e.g.
private MyClass myInstance = new MyClassInstance2();
Or probably even better would be to make them singletons and just do:
private MyClass myInstance = MyClassInstance3.getInstance();
But I can't help but think that this is also not the right way to handle this situation. Am I overthinking the problem? Should I just have a switch statement somewhere e.g.
public class MyClass {
public enum Instance { ONE, TWO, THREE }
public static String getName(Instance instance) {
switch(instance) {
case ONE:
return getNameFromFile(INSTANCE_1_DATA_FILE);
break;
case TWO:
etc.
}
}
}
Can anyone tell me the best way to implement this? Note that I have written the sample code in Java because that is my strongest language, but I will probably be implementing the application in C++, so at the moment I am more looking for language independent design patterns (or just for someone to tell me to go with one of the simple solutions I have already mentioned).
If you want the values to be constant, then you will not need setters, otherwise code can simply change the values in your constants, making them not very constant. In C++, you can just declare the instances const, although I'd still get rid of the setters, since someone could always cast away the const.
The pattern looks ok, although the fact that you are creating a new instance each time one is requested, is not usual for constants.
In java, you can create enums that are "smart" e.g.
public enum MyClass {
ONE(INSTANCE_1_DATA_FILE),
TWO(INSTANCE_2_DATA_FILE),
//etc...
private MyClass(String dataFile)
{
this(getNameFromDataFile(dataFile), other values...)
}
private MyClass(String name, String data, etc...)
{
this.name = name;
// etc..
}
public String getName()
{
return name;
}
}
In C++, you would create your MyClass, with a private constructor that takes the filename and whatever else it needs to initialize, and create static const members in MyClass for each instance, with the values assigned a new instance of MyClass created using the private constructor.
EDIT: But now I see the scenario I don't think this is a good idea having static values. If the types of ActivityLevel are fundamental to your application, then you can enumerate the different type of activity level as constants, e.g. a java or string enum, but they are just placeholders. The actual ActivityDescription instances should come from a data access layer or provider of some kind.
e.g.
enum ActivityLevel { LOW, MED, HIGH }
class ActivityDescription
{
String name;
String otherDetails;
String description; // etc..
// perhaps also
// ActivityLevel activityLevel;
// constructor and getters
// this is an immutable value object
}
interface ActivityDescriptionProvider
{
ActivityDescription getDescription(ActivityLevel activityLevel);
}
You can implement the provider using statics if you want, or an enum of ActivityDescription instnaces, or better still a Map of ActivityLevel to ActivityDescription that you load from a file, fetch from spring config etc. The main point is that using an interface to fetch the actual description for a given ActivityLevel decouples your application code from the mechanics of how those descriptions are produced in the system. It also makes it possible to mock the implementation of the interface when testing the UI. You can stress the UI with a mock implementation in ways that is not possible with a fixed static data set.
Now lets say that you know in advance that there will only ever be say 3 instances of this class, and the data is also known in advance (or at least will be read from a file at runtime, and the exact filename is known in advance). Basically what I am getting at is that the data is not going to be changed during runtime (once it has been set).
I'd use an enum. And then rather in this flavor:
public enum MyEnum {
ONE("path/to/instance1/file"),
TWO("path/to/instance2/file"),
THREE("path/to/instance3/file");
private String name;
private MyEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Which can be used as follows:
MyEnum one = MyEnum.ONE;
String name = one.getName();
(I'm too slow once again, you already accepted an answer, but here it is anyway...)
You want to (a) prevent changes to the data held in objects of MyClass, and (b) allow only a fixed set of MyClass objects to exist, implying that runtime code should not be able to create new instances of MyClass.
Your initial example has a public constructor, which violates (b)
I'd use a Factory approach so the Factory is the only thing that can create instances, and the class doesn't provide any setters so it's immutable.
Depending on how much flexibility you want for the future, you could put the factory and the class in the same package and limit scope that way, or you could make MyClass an inner class within the factory. You may also consider making MyClass an interface separate from its implementation.
A properties file could be used to configure the factory itself.
The properties file (e.g. "foo.properties") could look something like
one=/path/to/datafile1
two=/another/path/to/datafile2
three=/path/to/datafile3
I use "Foo" instead of "MyClass" in the (Java) examples below.
public class FooFactory
{
/** A place to hold the only existing instances of the class */
private final Map<String, Foo> instances = new HashMap<String, Foo>();
/** Creates a factory to manufacture Foo objects */
// I'm using 'configFile' as the name of a properties file,
// but this could use a Properties object, or a File object.
public FooFactory(String configfile)
{
Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream();
p.load(in); // ignoring the fact that IOExceptions can be thrown
// Create all the objects as specified in the factory properties
for (String key : p.keys())
{
String datafile = p.getProperty(key);
Foo obj = new Foo(datafile);
instances.put(key, obj);
}
}
public Foo getFoo(String which)
{
return instances.get(which);
}
/** The objects handed out by the factory - your "MyClass" */
public class Foo
{
private String name;
private String description;
private int value;
private Foo(String datafile)
{
// read the datafile to set name, description, and value
}
}
}
You're set to allow only your predefined instances, which can't be changed at runtime, but you can set it all up differently for another run at a later time.
Your first method seems to me like the best and the least prone to code rot. I'm not impressed by the idea of subclassing an object just to change the file name that contains the data that will be used to build it.
Of course, you could maybe improve on your original idea by wrapping these all in an outer class that provides some sort of enumeration access. A collection of MyClass's in other words. But I think you should discard this subclassing idea.
First, you really should be limiting where you use these instances in the code. Use them in as few places as possible. Given these are file names, I expect you want three class instances which accesses the files. How many classes are required depends on what your want to do with them? Look at the Singleton pattern for these classes.
Now you don't need the constants, but could have a helper class which will read the file containing the file names and supply them to the reader class. The code to find then name could also be a method called by the static initializer of the Singleton.
The common approach is to use a map:
private static final Map<String, YouClass> mapIt =
new HashMap<String, YouClass>(){{
put("one", new YourClass("/name", "desc", 1 )),
put("two", new YourClass("/name/two", "desc2", 2 )),
put("three", new YourClass("/name/three", "desc", 3 ))
}}
public static YourClass getInstance( String named ) {
return mapIt.get( named );
}
Next time you need it:
YouClass toUse = YourClass.getInstance("one");
Probably using strings as keys is not the best option but you get the idea.

Does the code-to-interface principle apply to entity classes?

I'm trying to follow code-to-interface on a project. Should I be creating an interface first then implementing that interface for entity classes? I'm thinking this might be taking the interface first approach too far and entities should be ignored. This is what I mean...
public interface Address {
public String getStreet();
public void setStreet(String street);
}
#Entity
public class AddressImpl implements Address {
private String street;
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
}
#Entity
public class OfficeImpl /* implements Office */ {
private Address location;
public Address getLocation(){
return this.location;
}
public void setLocation(Address location){
this.location = location;
}
}
public class Driver {
public static void main(String[] args) {
Office work = new OfficeImpl();
Address workAddress = new AddressImpl();
workAddress.setStreet("Main St.");
work.setLocation(workAddress);
}
}
I think creating Interfaces for Entities is probably not necessary.
The purpose of creating Interfaces (or at least, one of the purposes) is to make it easier to swap out one concrete implementation in favour of another. This is obviously a good thing for your DAOs, Business Logic etc.
But unless you have plans for the implementation of your entities to change as well, I would avoid it!
In your example, you are probably taking it too far, but once you add methods, write test cases and possibly use dependency injection, it will make more sense.
For simple projects like this, it is overkill, but once you get into a 'real' application, then it is often a good idea. Just be careful not to overdo it, everything doesn't need to implement an interface, just where it makes sense.
the interface for Entities should be the behaviors and properties that are common to all Entities!
public interface IEntity
{
int EntityId { get; set; }
bool FindById(int id);
bool Create(object [] values);
bool Delete(int id);
//etc.
}
sorry for the C# example, but the language doesn't matter. Interfaces are for 'plug compatability'.
I think when you're talking about entities, it's probably overkill.
Interfaces are useful when you're working with entities that have a common usage, but aren't necessarily the same. Can't think of a good way to explain it, but here's an example:
interface IFlaggable {
bool IsFlagged ...
string Reason ...
}
class ForumPost implements IFlaggable { }
class PrivateMessage implements IFlaggable { }
Hope that helps!
I generally don't make interfaces for data holding beans, that is I don't make interfaces for classes with primitive type values and getters/setters for them. Haven't really ever hit a moment where I would've needed interfaces for anything I usually use them for (polymorphism and mocking, mostly) so I haven't bothered doing that.
I guess I should point out that most of the time when I use databeans I also reflect the values from those same objects with custom classes which work like this:
Reflector r = new Reflector(new DataBean( [ values given through constructor ] ));
long someNumber = r.get("method", Long.class);

Categories