I am trying to solve timetabling problem with OptaPlanner but I am facing with problem which may be connected to cloning issue. Why when my planning entity collection method looks like that
#PlanningEntityCollectionProperty
public List<Lesson> getLessons() {
return getProject().getLessons();
}
I am getting error
java.lang.IllegalStateException: The solutionProperty (lessons) was not cloned as expected. The FieldAccessingSolutionCloner failed to recognize that property's field, probably because its field name is different.
but, when the method looks like
#PlanningEntityCollectionProperty
public List<Lesson> getLessons() {
if (lessons == null) {
lessons = getProject().getLessons();
}
return lessons;
}
everything is ok. What could be a reason? Why I am getting this error? Thanks for any help.
The generic cloner (to planning clone the best solution so the working solution can degrade) can't currently handle that first piece of code unfortunately.
There are 2 workarounds:
Implement a custom planning cloner (this is not simple, but it's explained in the docs section "4.3.7.6. Cloning a Solution".
Make the canonical field for lessons on that planning solution instead of Project (or refactor Project to implement Solution).
I wouldn't do it with that lazy initialization trick, as you might not always be able to guarantee that the getter has been called at least once before a planning clone happened.
I'm not so sure the title is a good match for this question I want to put on the table.
I'm planning to create a web MVC framework as my graduation dissertation and in a previous conversation with my advisor trying to define some achivements, he convinced me that I should choose a modular design in this project.
I already had some things developed by then and stopped for a while to analyze how much modular it would be and I couldn't really do it because I don't know the real meaning of "modular".
Some things are not very cleary for me, like for example, just referencing another module blows up the modularity of my system?
Let's say I have a Database Access module and it OPTIONALY can use a Cache module for storing results of complex queries. As anyone can see, I at least will have a naming dependency for the cache module.
In my conception of "modular design", I can distribute each component separately and make it interact with others developed by other people. In this case I showed, if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
And so, I was wondering if this is really a modular design yet.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning. To extend functionalities, I could create some structure based on Decorators and Adapters.
To clarify things a little bit, here is an example (in PHP):
Before
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public doComplexOperation();
}
class DbAccess implements DbAccessInterface {
private $cacheManager;
public function __construct(..., CacheManager $cacheManager = null) {
// ...
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
if ($this->cacheManager !== null) {
// return from cache if valid
}
// complex operation
}
}
After
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public function doComplexOperation();
}
class DbAccess implements DbAccessInterface {
public function __construct(...) {
// ...
}
public function doComplexQuery() {
// complex operation
}
}
// And now the integration module
class CachedDbAcess implements DbAccessInterface {
private $dbAccess;
private $cacheManager;
public function __construct(DbAccessInterface $dbAccess, CacheManager $cacheManager) {
$this->dbAccess = $dbAccess;
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
$cache = $this->cacheManager->get("Foo")
if($cache->isValid()) {
return $cache->getValue();
}
// Do complex operation...
}
}
Now my question is:
Is this the best solution? I should do this for all the modules that do not have as a requirement work together, but can be more efficient doing so?
Anyone would do it in a different way?
I have some more further questions involving this, but I don't know if this is an acceptable question for stackoverflow.
P.S.: English is not my first language, maybe some parts can get a little bit confuse
Some resources (not theoretical):
Nuclex Plugin Architecture
Python Plugin Application
C++ Plugin Architecture (Use NoScript on that side, they have some weird login policies)
Other SO threads (design pattern for plugins in php)
Django Middleware concept
Just referencing another module blows up the modularity of my system?
Not necessarily. It's a dependency. Having a dependencies is perfectly normal. Without dependencies modules can't interact with each other (unless you're doing such interaction indirectly which in general is a bad practice since it hides dependencies and complicates the code). Modular desing implies managing of dependencies, not removing them.
One tool - is using interfaces. Referencing module via interface makes a so called soft dependency. Such module can accept any implementation of an interface as a dependency so it is more independant and as a result - more maintainable.
The other tool - designing modules (and their interfaces) that have only single responcibility. This also makes them more granular, independant and maintainable.
But there is a line which you should not cross - blindly applying these tools may leed to a too modular and too generic desing. Making things too granular makes the whole system more complex. You should not solve universe problems, making generic modules, that all developers can use (unless it is your goal). First of all your system should solve your domain tasks and make things generic enough, but not more than that.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning
It is great if you came up with this idea by yourself. The statement itself, is a key to modular programming.
Plugin architecture is the best in terms of extensibility, but imho it is hard to maintenance especially in intra application. And depending the complexity of plugin architecture, it can make your code more complex by adding plugin logics, etc.
Thus, for intra modular design, I choose the N-Tier, interface based architecture. Basically, the architecture relays on those tiers:
Domain / Entity
Interface [Depend on 1]
Services [Depend on 1 and 2]
Repository / DAL [Depend on 1 and 2]
Presentation Layer [Depend on 1,2,3,4]
Unfortunately, I don't think this is achieveable neatly in php projects as it need separated project / dll references in each tier. However, following the architecture can help to modularize the application.
For each modules, we need to do interface-based design. It can help to enhance the modularity of your code, because you can change the implementation later, but still keep the consumer the same.
I have provided an answer similiar to this interface-based design, at this stackoverflow question.
Lastly but not least, if you want to make your application modular to the UI, you can do Service Oriented Architecture. This is simply make your application as bunch of services, and then make the UI to consume the service. This design can help to separate your UI with your logic. You can later use different UI such as desktop app, but still use the same logic. Unfortunately, I don't have any reliable source for SOA.
EDIT:
I misunderstood the question. This is my point of view about modular framework. Unfortunately, I don't know much about Zend so I will give examples in C#:
It consist of modules, from the smallest to larger modules. Example in C# is you can using the Windows Form (larger) at your application, and also the Graphic (smaller) class to draw custom shapes in the screen.
It is extensible, or replaceable without making change to base class. In C# you can assign FormLoad event (extensible) to the Form class, inherit the Form or List class (extensible) or overridding form draw method to create a custom window graphic (replaceable).
(optional) it is easy to use. In normal DI interface design, we usually inject smaller modules into a larger (high level) module. This will require an IOC container. Refer to my question for detail.
Easy to configure, and does not involve any magical logic such as Service Locator Pattern. Search Service Locator is an Anti Pattern in google.
I don't know much about Zend, however I guess that the modularity in Zend can means that it can be extended without changing the core (replacing the code) inside framework.
If you said that:
if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
Then it is not modular. It is integrated, means that your Database Access module will not work without Cache. In reference of C# components, it choose to provide List<T> and BindingList<T> to provide different functionality. In your case, imho it is better to provide CachedDataAccess and DataAccess.
I am using the mvc mini profiler to profile a NUnit Test suite.
I am just curious whether it would be possible to use the mvc mini profiler's profiling mechanism as an aspect, i.e., rather than having those using statements could I not somehow just provide some attribute above the method I want to profile?
I know that this would kill the kind of granularity we get with the mini profiler but in some cases, it's just more appropriate to use the AOP approach.
Ideas? Suggestions?
Thanks a bunch.
You would need to weave in code, so you would have to look at either PostSharp, Roslyn or some other IL weaving mechanism.
Yes, it is totally possible. In my case I was using Autofac, which implements interception using Castle's DynamicProxy.
But a very basic interceptor for profiling would look something like this (in C#):
public class ProfilerInterceptor : IInterceptor
{
#region Implementation of IInterceptor
public void Intercept(IInvocation invocation)
{
using (MiniProfiler.Current.Step(invocation.TargetType.Name + "." + invocation.Method.Name))
{
invocation.Proceed();
}
}
#endregion
}
NOTE: I know your preference was weaving rather than interception through proxies, but I'm posting it in case anybody else finds it useful.
I want to use Unity as an IoC besides the UnitOfWork and Repository patterns. I read various related articles and questions but none of them satisfied me completely.
I have a problem with all approaches. An example would explain better my problem:
We want to work with two repositories at two separate classes (maybe the business services) but the overall works are in a unit.
Start point is the LocalService1.Method1 method.
public class LocalService1
{
public void Method1(int id)
{
var repository1 = Container.Current.Resolve<IRepository1>(); // Injects the IUnitOfWork for the repository.
var entity1 = repository1.GetEntity1(id);
var service2 = Container.Current.Resolve<LocalService2>(); // Maybe it’s better not to use IoC for business logic. This is not my issue.
service2.Method2(entity1)
}
}
...
public class LocalService2
{
public void Method2(Entity1 entity1)
{
var repository2 = Container.Current.Resolve<IRepository2>(); // Injects the IUnitOfWork for the repository.
var count = repository2.GetEntity2sCount(entity1.Id);
// Do some works with count and entity1
}
}
The main question is that “How can I share the UnitOfWork (here can be ObjectContext) between the IRepository1 and IRepsitory2 while calling the LocalService1.Method1?”.
More important thing is that “I want to be sure about UnitOfWork disposal”.
I guess the answers would focus on these issues:
IoC configuration
Life Time configuration
Disposal time (How and when?)
If you recommend using “HttpContext” please consider about non-web environments.
I know my question is almost about the “Life time management” but I’m looking for an exhaustive approach.
First: Don't use Unity as a ServiceLocator. This is considered an anti-pattern. Use constructor injection instead.
Unity's LifetimeManagers don't clean up after themselves. This feature is on the wish list for Unity vNext.
If you want your objects to be disposed you should create your own LifetimeManager and a related BuilderStrategy that do clean up.
There is a sample in the TecX project (inside TecX.Unity.Lifetime) which is taken from Mark Seemann's book Dependency Injection in .NET.
I've JPA entities and need to perform logic with them. Until now a huge static database class did the job. It's ugly because every public interface method had an private equivalent that used the EntityManager, to perform transactions. But I could solve that having a static em too!
However i'm wondering if that's an appropriate design, especially as the class is responsible for many things.
Not surprisingly, the code i found online of real projects was not easy to understand (i might then as well remeain with my code).
The code here is easy to understand, although maybe over generic? Anyway, on top of JDBC. Yet, insightful, why use factories and singletons for DAOs?
I've though of singletoning the em instance as follows:
private static final Map<String, EntityManager> ems = new HashMap<String, EntityManager>();
private final EntityManager em;
private final EntityManagerFactory emf;
public void beginTransaction() {
em.getTransaction().begin();
}
public void commitTransaction() {
em.getTransaction().commit();
}
public Database(final String persistenceUnitName) {
if(ems.containsKey(persistenceUnitName)){
em = ems.get(persistenceUnitName);
}else{
ems.put(persistenceUnitName, em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager());
}
emf = em.getEntityManagerFactory();
this.persistenceUnitName = persistenceUnitName;
}
This way creation of instances is standard, still maintaining a singleton Connection/EntityManager.
On the otherhand I wondered whether there was the need to singleton ems in the first place?
The advantage is with multiple ems I run into locking problems (not using em.lock()).
Any feedback? Any real-world or tutorial code that demonstrates DAO with JPA2 and eclipselink?
Personally, I don't see the added value of shielding the EntityManager (which is an implementation of the Domain Store pattern) with a DAO and I would use it directly from the services, unless switching from JPA is a likely event. But, quoting An interesting debate about JPA and the DAO:
Adam said that he met only very few cases in which a project switched the database vendor, and no cases in which the persistence moved to a different thing than a RDBMs. Why should you pay more for a thing that it's unlikely to happen? Sometimes, when it happens, a simpler solution might have paid for itself and it might turn out to be simpler to rewrite a component.
I totally share the above point of view.
Anyway, the question that remains open is the lifecycle of the EntityManager and the answer highly depends on the nature of your application (a web application, a desktop application).
Here are some links that might help to decide what would be appropriate in your case:
Re: JPA DAO in Desktop Application
Using the Java Persistence API in Desktop Applications
Eclipselink in J2SE RCP Applications
Developing Applications Using EclipseLink JPA (ELUG)
An interesting debate about JPA and the DAO
And if you really want to go the DAO way, you could:
use Spring JPA support,
use some generic DAO library like generic-dao, krank, DAO Fusion,
roll your own generic DAO.
You could consider using Spring 3. Just follow their documentation for a clean design.