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

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);

Related

Which design pattern to use (if exists)?

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.

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

How to apply decoupling on these two coupled classes

I have two classes:
public class CourseModule {
// attributes...
List<Course> courses;
public void addCourse() { ... }
}
public class Course {
// attributes...
CourseModule module;
}
The attributes of Course do not suffice to identify an object uniquely, the course module is always required, also for addition information. A CourseModule consists of difference Courses.
What I don't like here is the circular dependency, it feels wrong. Now I was thinking about the following, instead of adding courses per method and setting the CourseModule reference by hand I could automate this procedure with the constructor:
public Course(...,...,...., CourseModule module) {
this.module = module;
module.courses.add(this);
}
But again, here is another huge problem: In Brian Goetz Java Concurrency in Practice it is said: Do not let the this reference escape the constructor
So what would be best practice here? I think its a really simple example, which might bear yield a sample solution.
Funnily enough, I had to do something similar. See my question here.
I found this post on the internet that is almost an exact duplicate of what you are trying to do, also with courses! I found that the solution specified there is not 100% right, the answers on my question need to be considered.
You're right, I would say that your current setup is an example of Code Smell.
Could you not make another object CourseInfo that manages the additional course information that you say cannot be contained within Course?
public class CourseModule {
List<Course> courses;
public void addCourse(Course course) { ... }
}
public class Course {
CourseInfo info;
}
public class CourseInfo {
CourseInfo info;
}

issue about LCOM4 with Weld/CDI?

I'm new for both Sonar and Weld/CDI. I would like your help to advise further about the LCOM4 analyzed result with Weld/CDI. Firstly I create a simple java class as the following: -
-------------Source---------------
interface MyInterface1 {
String getName();
void setName(String name);
}
interface MyInterface2 extends MyInterface1 {
String getPhone();
void setPhone();
}
public interface MyPublishedInterface extend MyInterface1, MyInterface2 {
//There is no any definition, it just a collected capabilities
//which will be published to other package. Some capabilities
//may be hidden and use internally.
}
abstract class MyBean1 implements MyInterface1 {
private String name;
#Override
public String getName() {
return this.name;
}
#Override
public void setName(String theName) {
this.name = theName;
}
}
abstract class MyBean2 extends MyBean1 implements MyInterface2 {
private String phone;
#Override
public String getPhone() {
return this.phone;
}
#Override
public void setPhone(String thePhone) {
this.phone= thePhone;
}
}
public class MyPublishedBean extends MyBean2 implements MyPublishedInterface {
//There is no any coding, it just a collected capabilities
//which will be published to other package. Some capabilities
//may be hidden and use internally.
}
#Named
#RequestScope
public class MyBackingBean {
#Inject
private MyPublishedInterface myPublishedInterface;
//-----the business method, setter and getter here.
}
-------------Source---------------
After I've analyzed with the Sonar, it reports that the MyPublishedBean has a LCOM4>1 as
getPhone()Ljava/lang/String;
setName(Ljava/lang/String;)V
setPhone(Ljava/lang/String;)V
getName()Ljava/lang/String;
Previously I used to mark all method to be a "final" method, there is no any mentions about the LCOM4. Anyhow the system shows me the exception about Unproxyable since my class contains a final method. I had removed the "final", I faced the LCOM4 issue.
I'm not sure if I'm confused about Sonar, Weld/CDI, the class/interface design or all of them. Could you please help to advise further?
The Sonar docs explain LCOM4 quite well. The results you see are completely correct given the example you gave here.
These interfaces look like they are merely data holders with no logic. A bean with just getters and setters for properties will fully expect to have an LCOM value equal to the number of properties in the bean. LCOM4 is a metric meant to measure the cohesion of logic in a class. The logic of a pure data bean is only that the data is in some way related to each other. LCOM4 is therefore in this case an incorrect and misleading metric to use.
LCOM4 should also be completely independent of whether your methods are final or not.
Please note that LCOM4 > 1 indicates a suspect class. It does not mean that the class is wrong and should not be used to flag the class as bad. Once you find that the suspect class is okay, it is best to remove that class in some way from the metric (to avoid you building up a long list of warnings that you know should be ignored).

In which scenarios do you use encapsulation?

I would like to know in what scenarios you use encapsulation. The purpose of this question is collaborative. So feel free to share your own experience when the subject is encapsulation.
Some scenarios:
Calculated property
public class Order {
private List<ListItem> listItems = new ArrayList<ListItem>();
public double getTotal() {
double total = 0;
for(ListItem listItem: listItems)
total += listItem.getQuantity() * listItem.getPropduct().getPrice();
return total;
}
}
Self-validating domain objects
public class Person {
private String name;
public void setName(String name) {
if(StringUtils.isBlank(name)) {
throw new NotEmptyException("name", name);
}
this.name = name;
}
}
Makes use of other kind of classes for some special behavior
public class Person {
private MutableInt id = new MutableInt();
/**
* Integer itself is immutable
*/
public Integer getId() {
retur id.intValue();
}
}
Conversion
public class Person {
public String enabled;
public boolean isEnabled() {
return "Y".equals(enabled);
}
}
Simply, I prefer to use strong encapsulation in all non-private APIs that I design/implement.
The only case where habitually don't use strong encapsulation is with private nested classes that are (and need to be) little more than ersatz struct declarations. My reasoning is that the private class is sufficiently encapsulated by being nested and private.
I am also prepared to relax encapsulation (a bit) if there are compelling performance reasons for doing this. This relaxation usually consists of leaking internal arrays / collections when the cost of copying them is prohibitive. And it always makes me feel uncomfortable doing this ...
I encapsulate when there is a scenario in which the user can screw it up. e.g., if I was writing a class that displayed text, I would not encapsulate the fact that I hold a string, because any string is valid for display.
Encapsulation exists for validation and interface change. If you have a parameter that needs no validation (and the interface is well-defined), there's no point in encapsulating it, especially if you use a language which doesn't come with any in-built tools for it, like Java (tools being, for example, C# properties).
Encapsulation is a tool like any other and should not be thrown all over everywhere just because you can.

Categories