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).
Related
I have a huge (parent) POJO which is being used in some component. The POJO has individual fields as well as nested POJOs as well. Is it possible to determine what all fields/ nested fields from this POJO are being accessed in that component?
I was thinking about JUnits/ aspects but not sure if either would work. I've tried looking through SF/ and Google but could not find any relevant thread for this thing.
Say following is a sample POJO:
public class Student {
private String name;
private Date date;
private Subject subject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
It has three fields name, date and subject, not all of which would be in use in my component. So I need to determine which are actually being used.
Edit:
Thanks Sharon for pointing out that the getter/setters were protected. I had just generated the class on the fly for the purpose of question and didn't notice the issue. Corrected now.
How the class is initialised: For the purpose of the component, objects will be created from Json/XML data and would have only getters being called.
As for static vs runtime analysis, I'd prefer to achieve it through static code analysis if that's possible otherwise runtime also is fine with me if that's easier.
As for using Decorator pattern, do we have anything without requiring existing code change? That's why I was thinking if JUnits could do this.
First of all, it is odd to see getter/setter methods that are protected. seems to me they need to be public?
Anyway, I would utilize the Decorator design pattern.
From the linked article:
The decorator design pattern allows us to dynamically add
functionality and behavior to an object without affecting the behavior
of other existing objects in the same class.
So, our decorated Student should inherit from the target class. All methods can log their usage and call super to invoke target operation. You didn't say how Student
is initialized, but anyway, you will want to modify that to create instances of LogUsageStudent
public class LogUsageStudent extends Student {
protected String getName() {
// log usage of getName()
return super.getName();
}
// etc
}
I created a CGLib dynamic proxy of a class, but when I try to access any field declared in the original class, I obtain java.lang.NoSuchFieldException. I need to obtain the field in order to change its value.
By the way, this is the class the proxy is based on:
public class Person {
private String name;
....
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
}
And this is the code snippet (inside the "intercept" method of the "MethodInterceptor") that is raising the mentioned exception (more specifically the first line):
public Object intercept(Object instance, Method jdkMethod, Object[] args, MethodProxy method) throws Throwable {
...
Field field = instance.getClass().getField("name");
field.setAccessible(true);
field.set(instance, "foo");
....
Do you know any other way to access the needed field or change its value?
Thanks.
Apparently, a CGLib proxy is a subclass of the original class. So, the following code worked well:
Field field = instance.getClass().getSuperclass().getDeclaredField("name");
Try:
Field field = instance.getClass().getDeclaredField("name");
As mentioned in this SO answer, getField only works for public fields, but applies to the entire class hierarchy. You can think of it as inspecting the public interface of the class. getDeclaredField works for private fields, and will not inspect the class hierarchy; you can think of it as resolving the implementation of the class.
Even though you already figured out how to fix your problem, here is a short explanation of how cglib works and what is causing you problems. Considering your Person class, cglib creates another class at runtime which is representing your proxy. This class would approximately look like the following in Java source code, however, many of the instances used are cached which is why cglib adds several other fields. Furthermore, the MethodInterceptor is injected by using different static fields:
public class Person$EnhancedByCglib extends Person {
private static class GetNameMethodProxy extends MethodProxy {
#Override
public Object invokeSuper(Object instance,
Object[] arguments) {
return ((Person$EnhancedByCglib) instance).getNameSuper();
}
// ...
}
// ...
private static MethodInterceptor methodInterceptor;
#Override
public String getName() {
return (String) methodInterceptor.intercept(this,
getClass().getDeclaredMethod("getName"),
new Object[0],
new GetNameMethodProxy());
}
private String getNameSuper() {
return super.getName();
}
#Override
public void setName(String name) {
methodInterceptor.intercept(this,
getClass().getDeclaredMethod("setName", String.class),
new Object[] {name},
new SetNameMethodProxy());
}
private void setNameSuper(String name) {
super.setName(name);
}
// ...
}
As you can see, the interception is implemented by overriding any method. This way, your MethodInterceptor is invoked instead of the original method which is still invokable by using the MethodProxy. Due to the interception, calling getMethod or getDeclaredMethod works as expected when using cglib. Fields are however not inherited which is why you need to browse the class hierarchy one class up. This is why:
instance.getClass().getSuperclass().getDeclaredField("name");
works. Note that cglib is not longer maintained. Have a look at my library Byte Buddy in case that you are looking for an alternative. Note however that I am releasing a fully stable version sometime next week. The current v0.1 release contains some premature features.
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");
}
}
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
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);