Writing hashcode for JPA entities - jpa-2.0

I am a little confused about the rule while making hashcodes for my JPA2 entities.
I have an embedded entity comprising audit columns (lastModifiedDate, createdDate) etc. Should this object pe part of the hashcode for my entity ?
#Entity(name = "CaseStatusEnum")
public class CaseStatus implements java.io.Serializable {
private static final long serialVersionUID = -5936623582710348810L;
#Id
#Column(unique=true,nullable=false,length=30)
private String caseStatus;
#Column(nullable=false,length=100)
private String caseStatusDesc;
#Embedded
private AuditTrail auditTrail;

I suggest you this link to overview concepts around the equals and hashcode function, specially its use within the diferents implementations of Hash and Collections.
overriding equals and hashcode
Then you maybe need to adjust the implementation of equals and hashcode functions depending on the JPA2 implementation you are using. Whatever be, I recommend you to take a look at this article about Hibernate - equals and hashcode to a better understanding of how could your app could be affected overriding this functions.
Regards

Related

Design pattern to use when the application wants to know which concrete class it got

I have a class structure like the on below.
class Technology;
class BasicTechnology : public Technology;
class BasicChildTechnology : public BasicTechnology;
class ConcreteChildTechnology1 : public BasicChildTechnology;//concretechildtech1
class ConcreteChildTechnology2 : public BasicChildTechnology;//concretechildtech2
class ConcreteChildTechnology3 : public BasicChildTechnology;//concretechildtech3
...
class ConcreteChildTechnologyN : public BasicChildTechnology;//concretechildtechN
The ConcreteChildTechnologyN/3/2/1 has an isValid(String selector) method, which is as shown below,
public isValid(String selector){
return "concretechildtech1".Equals(selector);
}
Now in the client code is,
Technology tech = getTechnologyObject("concretechildtech1"); //tech becomes an instance of ConcreteChildTechnology1
How should I implement getTechnologyObject() in this case?.
Thought of using the abstract factory pattern, but doubtful of that. or even create a Facade and create the concrete child based on the input argument?
The problem is, only the ConcreteChildTechnology1 knows whether the input string (concretechildtech1) belongs to him or not; via isValid() method.
Again if I start to create N objects every time to check the validity, that will cause and overhead, because 1)the system is running in a very low memory environment like mobile and tablets, 2)the number of instance creation is high, 10-100 per minute.
May be make the isValid() a static inline method and create object based on the reply from child objects?
My understanding is that getTechnologyObject("string") is returning a smart reference/pointer like std::shared_ptr<BasicChildTechnology> based on a string. Inside that function there is a list of these tech objects and only that tech object knows if it is associated with that string.
The first problem is that string. Is it possible to convert it to an enumeration or some more precise data type earlier than now? That alone will make your system more reliable, and faster.
The second problem is the ownership of the match criteria. I imagine when the system was being designed that this felt natural. I would point out that this object does not have a single responsibility. It is both required to do whatever the Tech is, and required to match itself from some serialisation format. It may still make sense to leave the string inside that object (it might be a name) but the matching needs to be elevated out of the object, and into the search function getTechnologyObject("string").
Now regardless of if you have a string/numeric, the tech objects need a function virtual label_t label() (name it as you feel fit) that returns this identifier.
Thirdly your creating a new object each time. That is the factory pattern, but there are two choice on how to implement that. One is giving the power of cloning to each implementation and treat each instance as a prototype. The other is to create a related hierarchy of factories that build those tech objects.
If you go the prototype path also define a virtual std::shared_ptr<BasicChildTechnology> clone() const =0; in the Tech classes. Otherwise create a related TechnologyFactory class tree, or a Factory<T> template. The factory will need something like a label_t label() and a std::shared_ptr<BasicChildTechnology> build().
I'm going to pick prototype here.
Construct the lookup like:
std::map<label_t, std::shared_ptr<BasicChildTechnology>> lookup;
lookup.add(tech1->label(), tech1);
lookup.add(tech2->label(), tech2);
lookup.add(tech3->label(), tech3);
Then:
std::shared_ptr<BasicChildTechnology> getTechnologyObject(const label_t& label)
{
return lookup[label]->clone();
}
And a Factory template here.
Construct the lookup like:
std::map<label_t, Factory<std::shared_ptr<BasicChildTechnology>>> lookup;
lookup.add(factory1->label(), factory1);
lookup.add(factory2->label(), factory2);
lookup.add(factory3->label(), factory3);
Then:
std::shared_ptr<BasicChildTechnology> getTechnologyObject(const label_t& label)
{
return lookup[label]->build();
}
The lookup will execute in log(N) time, for both cases.
What you are trying to do has different solutions based on your exact implementation and what the child types actually do.
If the isValid() method never relies on non-static member variables, isValid() could be made static. Your getTechnologyObject() function could be written as:
Technology* getTechnologyObject(const std::string& _string)
{
if(ConcreteChildTechnology1::isValid(_string)){
return new ConcreteChildTechnology1(/* arguments go here */);
}
/* follow with the rest */
}
As per user4581301's comment you can return a pointer to prevent object slicing.
It seems that your type hierarchy is blowing out in size. To reduce complexity and perhaps make the creation of objects easier, you could explore some form of composition instead of inheritance. This way a factory pattern would make more sense. Perhaps you could create a Technology object based off what is it supposed to do using a decorator pattern.

Is it possible to gen-class with a private final field?

How to create a Java class with a private final field in Clojure?
ClojureDocs for gen-class say that state field will be public
:state name
If supplied, a public final instance field with the given name will be
created.
So, in other words, do we have a way to create a class and after this a java object with the encapsulated state?
#alexmiller answered on this question recently here
In short, no. As you mention in the docs, gen-class state fields will
be public final fields. However, that field can be (for example), an
atom that is statefully modified by the implementation methods. In
general, we do not give much weight to encapsulation in Clojure -
instead preferring to make things visible, but "safe" (via
immutability). To quote Rich from
https://clojure.org/reference/datatypes, "encapsulation is folly".
gen-class is not a general purpose DSL for generating all possible
Java classes. It is a tool to generate classes in a certain style in
line with Clojure's aesthetics.
Another path however to something along these lines is to use a
deftype, which can have private mutable fields, exposed by
implementing interfaces or protocols inline. The deftype fields can
have meta of either ^:volatile-mutable or ^:unsynchronized-mutable,
both of which will become private fields.

How to inject an abstract factory into an entity's method?

I have an Order entity with a refund() method that uses an abstract factory refundStrategyFactory to create the appropriate refund strategy at run-time:
public class Order extends Entity{
public void refund(Employee emp, Quantity qty, IRefundStrategyFactory refundStartegyFactory){
//use the abstract factory to determine the appropriate strategy at run-time.
}
}
I'm trying to use dependency injection and have IRefundStrategyFactory injected automatically into the refund() method, but I couldn't find a way to achieve this.
I'm not using the constructor injection because Order is an entity and we shouldn't inject services into entities unless it's going to be used temporarily as in the refund method. This is better explained by Misko Hevery's blog post To “new” or not to “new”…:
It is OK for Newable to know about Injectable. What is not OK is for
the Newable to have a field reference to Injectable.
A similar answer by Mark Seemann to a related question also advocates the same idea.
Bonus point, Aren't I exposing the internals of the refund() method by exposing its dependency on IRefundStrategyFactory? Should I sacrifice unit testing in isolation and create the factory inside the method itself?
Well ideally your domain model should be free infrastructure concerns and IOC is a infrastructure concern, it is recommended that the domain model be simple POJO's. So I would not inject beans into my domain model.
In this case i think you should have a application service which gets injected the factory class and it then just passes the factory class as a parameter to your Order class.
Does the factory class use some information from the Order class to decide which kind of strategy class to instantiate ?
Bonus point, Aren't I exposing the internals of the refund() method by
exposing its dependency on IRefundStrategyFactory?
I am not sure if there is such a thing as exposing the internals of a method, This concept fits more naturally with "exposing internals of a class", A method does some action and to do so it might need some information from the outside world, we could debate on how to pass in that information and whether that one method is doing too much or not ? ... But i cannot reason on whether a method "exposes its implementation", maybe you should elaborate on what you meant by that point
I'd solve this by starting a refund process with eventual consistency, where you trigger a Refund action. The listeners to this action and it's events would then do their own tasks, i.e. refund the cost of the goods, restock the items, etc. Alternatively you could just do this atomically in an application service that triggers several domain services, one after another, passing in the Order item:
FinancialService.RefundOrderGoods(myOrder);
StockService.RestockOrderItems(myOrder);
...
I'd avoid adding any services or repositories into your entities.
Your main problem is that you can't "injected automatically into the refund() method", but IMO that isn't a problem at all, since you can simply pass on the dependency onto the method but still use constructor injection in the service that calls this method:
public class ApplyRefundHandler : ICommandHandler<ApplyRefund>
{
private readonly IRefundStrategyFactory refundStartegyFactory;
private readonly IRepository<Order> orderRepository;
private readonly IRepository<Employee> employeeRepository;
public ApplyRefundHandler(IRefundStrategyFactory refundStartegyFactory,
IRepository<Order> orderRepository,
IRepository<Employee> employeeRepository)
{
this.refundStartegyFactory = refundStartegyFactory;
this.orderRepository = orderRepository;
this.employeeRepository = employeeRepository;
}
public void Handle(ApplyRefund command)
{
Order order = this.orderRepository.GetById(command.OrderId);
Employee employee = this.employeeRepository.GetById(command.EmployeeId);
order.refund(employee, command.Quantity, this.refundStartegyFactory);
}
}
Aren't I exposing the internals of the refund() method by exposing its
dependency on IRefundStrategyFactory? Should I sacrifice unit testing
in isolation and create the factory inside the method itself?
Yes you are, but in the same time you are probably violating the Single Responsibility Principle by adding a lot of business logic in the Order class. If you hide the abstractions, it means you need to inject them into the constructor and you will probably find out quickly that your Order class gets a lot of dependencies. So instead you can view the Order's methods as a Single Responsibility (a class in disguise) that has little to no relationships with the other methods in that class, and in that case it makes sense to pass in its dependencies into that method.
As a side node, please be aware that factory abstractions, like your IRefundStrategyFactory are usually not good abstractions. You should consider removing it, as described in detail here.

How to unit-test private code without refactoring to separate class?

Assume i have a private routine that performs some calculation:
private function TCar.Speed: float
{
Result = m_furlogs * 23;
}
But now i want to begin testing this calculation more thoroughly, so i refactor it out to a separate function:
public function TCar.Speed: float
{
Result = CalculateSpeed(m_furlogs);
}
private function TCar.CalculateSpeed(single furlogs): float
{
Result = furlogs * 23;
}
Now i can perform all kinds of tests on CalculateSpeed:
Check( CalculateSpeed(0) = 0);
Check( CalculateSpeed(1) = 23);
Check( CalculateSpeed(2) = 46);
Check( CalculateSpeed(88) = -1);
Except that i can't perform these tests, because CalculateSpeed is private to TCar. An abstract tennant of unit-testing is that you never test private code - only public interfaces. As a practical matter, *x*Unit is not normally structured to be able to access private methods of the separate class being tested.
The issue is that none of the rest of the class is setup to handle unit-tests. This is the very first routine that will have testing of any kind. And it is very difficult to configure the host class a set of initial conditions that will allow me to test calling CalculateSpeed with every set of inputs that i would like.
The only alternative i can see, is moving this private calculation out into it's own TCarCalculateSpeed class:
public class TCarCalculateSpeed
{
public function CalculateSpeed(float furlogs)
{
Result = furlogs * 23;
}
}
A whole class, dedicated to exposing one method, that's supposed to be private, just so i can test it?
Class explosion.
Plus it's private. If i wanted it to be public, i'd rather promote it to public visibility - at least that way i save a separate class being created.
i'd like to add some unit-testing; but it can only be done in small pieces, as code changes. i can't completely redesign functioning 12 year old software, possibly breaking everything, because i wanted to test one internal calculation.
My current, best, thinking is to add a Test method to my Car class, and just call that:
TCar Car = new TCar();
Car.RunTests;
public procedure TCar.RunTests
{
Check( CalculateSpeed(0) = 0);
Check( CalculateSpeed(1) = 23);
Check( CalculateSpeed(2) = 46);
Check( CalculateSpeed(88) = -1);
}
But now i have to figure out how to have TCar.RunTests get trigged by the external TestRunner, which is only designed to use TestCase classes.
Note: i've tried my damnest to mix syntax from a bunch of languages. In other words: language agnostic.
This can't really be quite language-agnostic, as the protection mechanisms and the tactics to bypass them vary quite widely with language.
But most languages do provide bypasses in some form, and as others have noted, there are sometimes protections midway between private and public that make testing easier.
In Java, for example, reflection can be used to private stuff if you really need to, and things can be made protected or package-private so that you don't need reflection.
Generally speaking, if something is complex enough to require testing it should not be buried as a private method or class in something else. It is doing something that warrants its own class.
Rather than worrying about the number of classes, worry about their size and complexity. Many small classes adhering to the Single Responsibility Principle are better than a small number of classes doing complex things internally.
If a method is complicated (and risky) enough to test on its own, it's worth creating a class for it or making it a public member of the existing class - whichever is more suitable, given the characteristics of the existing class.
Can you create multiple instances of the TCar class with different initial values of m_furlogs? Do you have a getter on speed anywhere? You could validate against that if so.
If it's only internally used, and you really want to test it, you could create a utilities class that holds the logic for the simple calculations. I know it's refactoring, but it's not the class explosion you might be envisioning.
In some languages, there is middle ground between private and public. You can expose a logically private method to a unit test without exposing it to the world.
In method documentation, you can document that the method is intended private, but accessible for the purpose of unit-testing.
In Java, for example, you could make the private method package protected, and place the unit test in the same package. In C#, if I recall correctly, you could make it internal. In C++, the unit-test could be a friend.
If your language supports compiler defines, you could use these to your advantage.
(Example code in Delphi)
In your unit test project, set a compiler conditional define, either using the project options or in an include file that you include in each and every unit in that project.
{$DEFINE UNIT_TESTS}
In your class code, check the conditional define and switch between public or protected and private accordingly:
{$IFDEF UNIT_TESTS}
public // or protected
{$ELSE}
private
{$ENDIF}
function CalculateSpeed: float;
This means your unit tests will have the access they need to your method, while in production code it will still be private.

Unit-testing private methods: Facade pattern

Lots of developers think that testing private methods is a bad idea. However, all examples I've found were based on the idea that private methods are private because calling them could break internal object's state. But that's not only reason to hide methods.
Let's consider Facade pattern. My class users need the 2 public methods. They would be too large. In my example, they need to load some complex structure from the database's BLOB, parse it, fill some temporary COM objects, run user's macro to validate and modify these objects, and serialize modified objects to XML. Quite large functionality for the single metod :-) Most of these actions are required for both public methods. So, I've created about 10 private methods, and 2 public methods do call them. Actually, my private methods should not necessarily be private; they'll not break the internal state of instance. But, when I don't wont to test private methods, I have the following problems:
Publishing them means complexity for users (they have a choice they don't need)
I cannot imagine TDD style for such a large public methods, when you're to write 500+ lines of code just to return something (even not real result).
Data for these methods is retrieved from database, and testing DB-related functionality is much more difficult.
When I'm testing private methods:
I don't publish details that would confuse users. Public interface includes 2 methods.
I can work in TDD style (write small methods step-by-step).
I can cover most of class's functionality using test data, without database connection.
Could somebody describe, what am I doing wrong? What design should I use to obtain the same bonuses and do not test private methods?
UPDATE: It seems to me I've extracted everything I was able to another classes. So, I cannot imagine what could I extract additionally. Loading from database is performed by ORM layer, parsing stream, serializing to XML, running macro - everything is done by standalone classes. This class contains quite complex data structure, routines to search and conversion, and calls for all mentioned utilities. So, I don't think something else could be extracted; otherwise, its responsibility (knowledge about the data structure) would be divided between classes.
So, the best method to solve I see now is dividing into 2 objects (Facade itself and real object, with private methods become public) and move real object to somewhere nobody would try to find it. In my case (Delphi) it would be a standalone unit, in other languages it could be a separate name space. Other similar option is 2 interfaces, thanks for idea.
I think you are putting too many responsibilities (implementations) into the facade. I would normally consider this to be a front-end for actual implementations that are in other classes.
So the private methods in your facade are likely to be public methods in one or more other classes. Then you can test them there.
Could somebody describe, what am I
doing wrong?
Maybe nothing?
If I want to test a method I make it default (package) scope and test it.
You already mentioned another good solution: create an interface with your two methods. You clients access those two methods and the visibility of the other methods don't matter.
Private methods are used to encapsulate some behavior that has no meaning outside of the class you are trying to test. You should never have to test private methods because only the public or protected methods of the same class will ever call private methods.
It may just be that your class is very complex and it will take significant effort to test it. However, I would suggest you look for abstractions that you can break out into their own classes. These classes will have a smaller scope of items and complexity to test.
I am not familiar with your requirements & design but it seems that your design is procedural rather than object oriented. i.e. you have 2 public methods and many private methods. If you break your class to objects where every object has its role it would be easier to test each of the "small" classes. In addition you can set the "helpers" objects access level to package (the default in Java, I know there is a similar access level in C#) this way you are not exposing them in the API but you can unit test them independently (as they are units).
Maybe if you take time and look the
Clean Code Tech talks from Miško. He is very insightfull of how code should be written in order to be tested.
This is a bit controversial topic... Most TDDers hold opinion that refactoring your methods for easier unit testing actually makes your design better. I think that this is often true, but specific case of private methods for public APIs is definitely an exception. So, yes, you should test private method, and no, you shouldn't make it public.
If you're working in Java, here's a utility method I wrote that will help you test static private methods in a class:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import junit.framework.Assert;
public static Object invokeStaticPrivateMethod(Class<?> clazz, String methodName, Object... params) {
Assert.assertNotNull(clazz);
Assert.assertNotNull(methodName);
Assert.assertNotNull(params);
// find requested method
final Method methods[] = clazz.getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
if (methodName.equals(methods[i].getName())) {
try {
// this line makes testing private methods possible :)
methods[i].setAccessible(true);
return methods[i].invoke(clazz, params);
} catch (IllegalArgumentException ex) {
// maybe method is overloaded - try finding another method with the same name
continue;
} catch (IllegalAccessException ex) {
Assert.fail("IllegalAccessException accessing method '" + methodName + "'");
} catch (InvocationTargetException ex) {
// this makes finding out where test failed a bit easier by
// purging unnecessary stack trace
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
} else {
throw new InvocationException(ex.getCause());
}
}
}
}
Assert.fail("method '" + methodName + "' not found");
return null;
}
This could probably be rewritten for non-static methods as well, but those pesky private methods usually are private so I never needed that. :)
suppose you have 8 private methods and 2 public ones. If you can execute a private method independently, i.e. without calling any of the other methods, and without state-corrupting side-effects, then unit testing just that method makes sense. But then in that case there is no need for the method to be private!
in C# i would make such methods protected instead of private, and expose them as public in a subclass for testing
given your scenario, it might make more sense for the testable methods to be public and let the user have a true facade with only the 2 public methods that they need for their interface