How can I write a fully declarative configuration in Optaplanner if some with<X> methods are missing (there are set<X> methods) - optaplanner

I use Optaplanner as an optimisation library. I am trying to move away from XML configuration but I noticed that some of the *MoveSelectorConfig and *EntitySelectorConfig classes have set<X> methods instead of with<X> methods (e.g. setEntityClass(), setId(), setCacheType(), setSelectionOrder()). This makes it not possible to write a fully declarative configuration. Is this intended? What is the rationale? Are there plans to change this?

It is most definitely not intended, rather an oversight. If you want to report which builder methods are missing, we will eventually fix that. That said, since the setters are always there, this is not critical.

Related

TDD in Objective-c: property/constructor injection or method swizzling?

Since I've started using TDD I've been firmly convinced that it's a great way to write good correct pattern compliant code, without forcing my design decisions.
And I found this true in 80% scenarios, but I have problems when it comes to test certain tipe of objects which, for some reason, wrap and hide an object inside the implementation.
To give you an example let's think of a MyLocationManager objects which gives a common interface to my objects to be used, and wraps inside an NSLocationManager.
When I want to test such an object I have to supply a mock NSLocationManager of course.
I have of course the property/constructor injection method, but this means adding a property, or a constructor parameter, with an objects that I simply want to hide from the other objects: I've created MyLocationManager to wrap and hide NSLocationManager, why should I be exposing a property just to test it?
A method I've found which is pretty straightforward is to method swizzle NSLocationManager's methods, so I can exchange the actual implementation of a method with a mock one, but this seems pretty unclean and I don't know how safe it is.
As far as I can understand, there might be a Demeter Law's violation in not exposing a property constructor, but on the other hand, I think that in objective-c some flexibility on this pattern is accepted.
So my question is, there should be any way I'm not clearly seeing to adopt property/constructor injection, or method swizzling is a commonly used practice?
Are there any other techniques for this scenario adopted that I should better use?
On a footnote:
This problem is true even with objects that wraps networking code and classes like NSUrlSession.
Well, at one point the testing set-up can be more complicated than the code to test, so one might remember, what testing was invented for.
I think a pragmatic way is, to expose the property you need only in a separate header containing a separate class continuation.
After a long time of Test Driven Development experience, I find this old question of mine pretty simple to answer.
For some reason I was thinking that property injection and dependency injection where to avoid to mask something.
I simply don't think this anymore.
In the previous scenario of my original question the right answer from present-me is:
You have to expose the dependency of NSLocationManager, maybe providing a constructor injector method, and a convenience constructor method, to initialise the location manager with NSLocationManager.
There is no real need to hide the dependency even if it is a wrapper class, because in the exact moment you find yourself with the need to swizzle some methods, you're hacking the "internals" of your object and tweaking it without testing the interface, modifying the runtime behaviour in an uncontrolled manner.
If you wanna swizzle, swizzle ahead, but it's not the right choice.

Alternatives to Singleton when global access is wanted

I have spent the last couple of hours reading about the singleton pattern and why not to use it, amongst others those really good sites:
Singleton I love you, but you're bringing me down
How to Think About the "new" Operator with Respect to Unit Testing
Where have all the Singletons Gone?
I guess quite a lot of you know these already.
Looking at my code after reading that, I clearly am one of the maybe 95% of programmers that misunderstood and misused the singleton pattern.
For some cases, I can clearly remove the pattern, but there are cases where I am unsure what to do:
I know singletons for logging are accepted, one reason for that being that information only flows into them but not back into the application (just into the log file or console etc of course).
What about other classes which do not meet that criteria but are required by a lot of classes?
For example, I have a settings object which is required by a lot of classes. By a lot, I mean more than 200.
I have read into some other SO questions like "Singletons: good design or a crutch?", and all of them pointed out why using singletons is discouraged.
I understand the reasons for that, but I still have one major question:
How do I design a class which needs a single instance, accessible from everywhere, if not using the Singleton pattern?
The options I can think of would be:
Use a static class instead (though I don't see how this would be any better, looking at OOP and unit testing).
Have it created in an ApplicationFactory and perform dependency injection on every single class that needs it (keep in mind it's 200+ for some cases).
Use a singleton anyway, as the global access bonus outweighs the disadvantages for that case.
Something completely different.
It will depend on exactly what you mean by a settings object.
Do all 200 classes need all the settings; if not why do they have access to the unused settings?
Where do the settings come from and is there a good reason why each class can't load its settings as and when required?
Most importantly though, don't make changes to working code just because the code uses a pattern which is frowned upon. I've only used the singleton pattern once but I'd use it again.
EDIT:
I don't know your constraints but I wouldn't worry about multiple access from a file until it had been shown to be an issue. I would split up the configuration into different files for different classes/ groups of classes or, preferably, use a DB instead of files with different tables providing data for each class.
As an aside I've noticed that once you put the data in a db people seem to stop worrying about accessing it multiple times even though you're still going to the file system in the end.
PS: If other options aren't suitable I'd use a singleton... you want data to be globally available, you're not willing to use dependency injection, you only want the file to be read once; you've limited your options and a singleton isn't that bad.
Isn't this already discussed extensively and exhaustingly?
There is no misuse of the pattern. If your software works as expected (inlcuding maintainability and testablility) you are right with singletons.
The thing about people complain is that the singleton pattern has more impact than only restrict a class to have a single instance.
you introduce a global variable
you cannot build a subclass
you cannot reset the instance
If all this is not a problem for you: Use singletons all over the place. The pattern discussion is academic and hairsplitting.
And - to answer your question - checkout the monostate vs singleton thread: Monostate vs. Singleton

struts 2 - where should I set global application variables?

I'm using struts 2 and I'd like to read some custom-defined parameters (global variables), preferably from web.xml or some custom ".properties" file (i.e. not hardcoded in the Java sources). This problem has been driving me mad for the past half hour as I can't google any reasonable solution.
What is the best way to do this? I find it strange that it is so difficult ...
all the best
Nicola Montecchio
There are a few ways to do this.
Constants can be set in struts.xml
(http://struts.apache.org/2.x/docs/constant-configuration.html).
If you're using Spring along with
Struts 2 you should be able to set
some parameters in your
applicationContext.xml.
You might also consider using JNDI
properties, in a configuration file
specific to each application server
deployment
(http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html)
Ask yourself first: are those constants really pertinent to Struts2 or just to your application ?
If the later, this is not really a Struts2 question, and you -trust me- dont' want tie you "constants" management to Struts2 (or web.xml), they should be accesible from your application code outside the webapp (for example, from some testing code).
I understand that you feel bad about "harcoding" constants in some (say) Constants class (with static final fields), but be aware that this might not be so bad practice -if they are really constants, unlikely to be changed independently of your java code. Worth a thought.
If not, you might need some ConstantsManager class, which might be a singleton stateless object (or some kind of 'Service' object), which knows how to load the constants, for example from some property file in the classpath. How do the objects of your application (including perhaps some Struts2 action) get a reference to that ConstantsManager instance? In the simplest (and dirtiest) implementation, you'd have a Singleton pattern implementation with a static getInstance() method. More flexible and fashionable is the DI/IOC way, perhaps with some beans container, as Spring; and Struts2 is well suited to play with that. And if you're not familiar with this concepts, they will surely pop up soon, for issues similiar (but less trivial) that accessing some constants.
I don't know if this works but http://struts.apache.org/2.0.6/struts2-core/apidocs/com/opensymphony/xwork2/ActionContext.html#get%28java.lang.Object%29
ActionContext.getContext().get(...) might work.

When do you need to create abstractions in the form of interfaces?

When do you encourage programming against an interface and not directly to a concrete class?
A guideline that I follow is to create abstractions whenever code requires to cross a logical/physical boundary, most especially when infrastructure-related concerns are involved.
Another checkpoint would be if a dependency will likely change in the future, due to possible additional concerns code (such as caching, transactional awareness, invoking a webservice instead of in-process execution) or if such dependencies have direct references to infrastructure integration points.
If code depends on something that does not require control to cross a logical/physical boundary, I more or less don't create abstractions to interact with those.
Am I missing anything?
Also, use interfaces when
Multiple objects will need to be acted upon in a particular fashion, but are not fundamentally related. Perhaps many of your business objects access a particular utility object, and when they do they need to give a reference of themselves to that utility object so the utility object can call a particular method. Have that method in an interface and pass that interface to that utility object.
Passing around interfaces as parameters can be very helpful in unit testing. Even if you have just one type of object that sports a particular interface, and hence don't really need a defined interface, you might define/implement an interface solely to "fake" that object in unit tests.
related to the first 2 bullets, check out the Observer pattern and the Dependency Injection. I'm not saying to implement these patterns, but they illustrate types of places where interfaces are really helpful.
Another twist on this is for implementing a couple of the SOLID Principals, Open Closed principal and the Interface Segregation principle. Like the previous bullet, don't get stressed about strictly implementing these principals everywhere (right away at least), but use these concepts to help move your thinking away from just what objects go where to thinking more about contracts and dependency
In the end, let's not make it too complicated: we're in a strongly typed world in .NET. If you need to call a method or set a property but the object you're passing/using could be fundamentally different, use an interface.
I would add that if your code is not going to be referenced by another library (for a while at least), then the decision of whether to use an interface in a particular situation is one that you can responsibly put off. The "extract interface" refactoring is easy to do these days. In my current project, I've got an object being passed around that I'm thinking maybe I should switch to an interface; I'm not stressing about it.
Interfaces abstraction are convenient when doing unit test. It helps for mocking test objects. It very useful in TDD for developing without actually using data from your database.
If you don't need any features of the class that aren't found in the Interface...then why not always prefer the Interface implementation?
It will make your code easier to modify in the future and easier to test (mocking).
you have the right idea, already. i would only add a couple of notes to this...
first, abstraction does not mean 'interface'. for example, a "connection string" is an abstraction, even though it's just a string... it's not about the 'type' of the thing in question, it's about the intention of use for that thing.
and secondly, if you are doing test automation of any kind, look for the pain and friction that are exposed by writing the tests. if you find yourself having to set up too many external conditions for a test, it's a sign that you need a better abstraction between the thing your testing and the things it interacts with.
I think you've said it pretty well. Much of this will be a stylistic thing. There are open source projects I've looked at where everything has an interface and an implementation, and it's kind of frustrating, but it might make iterative development a little easier, since any objects implementation can break but dummies will still work. But honestly, I can dummy any class that doesn't overuse the final keyword by inheritance.
I would add to your list this: anything which can be thought of as a black box should be abstracted. This includes some of the things you've mentioned, but it also includes hairy algorithms, which are likely to have multiple useful implementations with different advantages for different situation.
Additionally, interfaces come in handy very often with composite objects. That's the only way something like java's swing library gets anything done, but it can also be useful for more mundane objects. (I personally like having an interface like ValidityChecker with ways to and-compose or or-compose subordinate ValidityCheckers.)
Most of the useful things that come with the Interface passing have been already said. However I would add:
implementing an interface to an object, or later multiple objects, FORCES all the implementers to follow an IDENTICAL pattern to implement contract with the object. This can be useful in case you have not so OOP-experienced-programmers actually writing the implementation code.
in some languages you can add attributes on the interface itself, which can be different from the actual object implementation attribute as sense and intent

What is the best way to solve an Objective-C namespace collision?

Objective-C has no namespaces; it's much like C, everything is within one global namespace. Common practice is to prefix classes with initials, e.g. if you are working at IBM, you could prefix them with "IBM"; if you work for Microsoft, you could use "MS"; and so on. Sometimes the initials refer to the project, e.g. Adium prefixes classes with "AI" (as there is no company behind it of that you could take the initials). Apple prefixes classes with NS and says this prefix is reserved for Apple only.
So far so well. But appending 2 to 4 letters to a class name in front is a very, very limited namespace. E.g. MS or AI could have an entirely different meanings (AI could be Artificial Intelligence for example) and some other developer might decide to use them and create an equally named class. Bang, namespace collision.
Okay, if this is a collision between one of your own classes and one of an external framework you are using, you can easily change the naming of your class, no big deal. But what if you use two external frameworks, both frameworks that you don't have the source to and that you can't change? Your application links with both of them and you get name conflicts. How would you go about solving these? What is the best way to work around them in such a way that you can still use both classes?
In C you can work around these by not linking directly to the library, instead you load the library at runtime, using dlopen(), then find the symbol you are looking for using dlsym() and assign it to a global symbol (that you can name any way you like) and then access it through this global symbol. E.g. if you have a conflict because some C library has a function named open(), you could define a variable named myOpen and have it point to the open() function of the library, thus when you want to use the system open(), you just use open() and when you want to use the other one, you access it via the myOpen identifier.
Is something similar possible in Objective-C and if not, is there any other clever, tricky solution you can use resolve namespace conflicts? Any ideas?
Update:
Just to clarify this: answers that suggest how to avoid namespace collisions in advance or how to create a better namespace are certainly welcome; however, I will not accept them as the answer since they don't solve my problem. I have two libraries and their class names collide. I can't change them; I don't have the source of either one. The collision is already there and tips on how it could have been avoided in advance won't help anymore. I can forward them to the developers of these frameworks and hope they choose a better namespace in the future, but for the time being I'm searching a solution to work with the frameworks right now within a single application. Any solutions to make this possible?
Prefixing your classes with a unique prefix is fundamentally the only option but there are several ways to make this less onerous and ugly. There is a long discussion of options here. My favorite is the #compatibility_alias Objective-C compiler directive (described here). You can use #compatibility_alias to "rename" a class, allowing you to name your class using FQDN or some such prefix:
#interface COM_WHATEVER_ClassName : NSObject
#end
#compatibility_alias ClassName COM_WHATEVER_ClassName
// now ClassName is an alias for COM_WHATEVER_ClassName
#implementation ClassName //OK
//blah
#end
ClassName *myClass; //OK
As part of a complete strategy, you could prefix all your classes with a unique prefix such as the FQDN and then create a header with all the #compatibility_alias (I would imagine you could auto-generate said header).
The downside of prefixing like this is that you have to enter the true class name (e.g. COM_WHATEVER_ClassName above) in anything that needs the class name from a string besides the compiler. Notably, #compatibility_alias is a compiler directive, not a runtime function so NSClassFromString(ClassName) will fail (return nil)--you'll have to use NSClassFromString(COM_WHATERVER_ClassName). You can use ibtool via build phase to modify class names in an Interface Builder nib/xib so that you don't have to write the full COM_WHATEVER_... in Interface Builder.
Final caveat: because this is a compiler directive (and an obscure one at that), it may not be portable across compilers. In particular, I don't know if it works with the Clang frontend from the LLVM project, though it should work with LLVM-GCC (LLVM using the GCC frontend).
If you do not need to use classes from both frameworks at the same time, and you are targeting platforms which support NSBundle unloading (OS X 10.4 or later, no GNUStep support), and performance really isn't an issue for you, I believe that you could load one framework every time you need to use a class from it, and then unload it and load the other one when you need to use the other framework.
My initial idea was to use NSBundle to load one of the frameworks, then copy or rename the classes inside that framework, and then load the other framework. There are two problems with this. First, I couldn't find a function to copy the data pointed to rename or copy a class, and any other classes in that first framework which reference the renamed class would now reference the class from the other framework.
You wouldn't need to copy or rename a class if there were a way to copy the data pointed to by an IMP. You could create a new class and then copy over ivars, methods, properties and categories. Much more work, but it is possible. However, you would still have a problem with the other classes in the framework referencing the wrong class.
EDIT: The fundamental difference between the C and Objective-C runtimes is, as I understand it, when libraries are loaded, the functions in those libraries contain pointers to any symbols they reference, whereas in Objective-C, they contain string representations of the names of thsoe symbols. Thus, in your example, you can use dlsym to get the symbol's address in memory and attach it to another symbol. The other code in the library still works because you're not changing the address of the original symbol. Objective-C uses a lookup table to map class names to addresses, and it's a 1-1 mapping, so you can't have two classes with the same name. Thus, to load both classes, one of them must have their name changed. However, when other classes need to access one of the classes with that name, they will ask the lookup table for its address, and the lookup table will never return the address of the renamed class given the original class's name.
Several people have already shared some tricky and clever code that might help solve the problem. Some of the suggestions may work, but all of them are less than ideal, and some of them are downright nasty to implement. (Sometimes ugly hacks are unavoidable, but I try to avoid them whenever I can.) From a practical standpoint, here are my suggestions.
In any case, inform the developers of both frameworks of the conflict, and make it clear that their failure to avoid and/or deal with it is causing you real business problems, which could translate into lost business revenue if unresolved. Emphasize that while resolving existing conflicts on a per-class basis is a less intrusive fix, changing their prefix entirely (or using one if they're not currently, and shame on them!) is the best way to ensure that they won't see the same problem again.
If the naming conflicts are limited to a reasonably small set of classes, see if you can work around just those classes, especially if one of the conflicting classes isn't being used by your code, directly or indirectly. If so, see whether the vendor will provide a custom version of the framework that doesn't include the conflicting classes. If not, be frank about the fact that their inflexibility is reducing your ROI from using their framework. Don't feel bad about being pushy within reason — the customer is always right. ;-)
If one framework is more "dispensable", you might consider replacing it with another framework (or combination of code), either third-party or homebrew. (The latter is the undesirable worst-case, since it will certainly incur additional business costs, both for development and maintenance.) If you do, inform the vendor of that framework exactly why you decided to not use their framework.
If both frameworks are deemed equally indispensable to your application, explore ways to factor out usage of one of them to one or more separate processes, perhaps communicating via DO as Louis Gerbarg suggested. Depending on the degree of communication, this may not be as bad as you might expect. Several programs (including QuickTime, I believe) use this approach to provide more granular security provided by using Seatbelt sandbox profiles in Leopard, such that only a specific subset of your code is permitted to perform critical or sensitive operations. Performance will be a tradeoff, but may be your only option
I'm guessing that licensing fees, terms, and durations may prevent instant action on any of these points. Hopefully you'll be able to resolve the conflict as soon as possible. Good luck!
This is gross, but you could use distributed objects in order to keep one of the classes only in a subordinate programs address and RPC to it. That will get messy if you are passing a ton of stuff back and forth (and may not be possible if both class are directly manipulating views, etc).
There are other potential solutions, but a lot of them depend on the exact situation. In particular, are you using the modern or legacy runtimes, are you fat or single architecture, 32 or 64 bit, what OS releases are you targeting, are you dynamically linking, statically linking, or do you have a choice, and is it potentially okay to do something that might require maintenance for new software updates.
If you are really desperate, what you could do is:
Not link against one of the libraries directly
Implement an alternate version of the objc runtime routines that changes the name at load time (checkout the objc4 project, what exactly you need to do depends on a number of the questions I asked above, but it should be possible no matter what the answers are).
Use something like mach_override to inject your new implementation
Load the new library using normal methods, it will go through the patched linker routine and get its className changed
The above is going to be pretty labor intensive, and if you need to implement it against multiple archs and different runtime versions it will be very unpleasant, but it can definitely be made to work.
Have you considered using the runtime functions (/usr/include/objc/runtime.h) to clone one of the conflicting classes to a non-colliding class, and then loading the colliding class framework? (this would require the colliding frameworks to be loaded at different times to work.)
You can inspect the classes ivars, methods (with names and implementation addresses) and names with the runtime, and create your own as well dynamically to have the same ivar layout, methods names/implementation addresses, and only differ by name (to avoid the collision)
Desperate situations call for desperate measures. Have you considered hacking the object code (or library file) of one of the libraries, changing the colliding symbol to an alternative name - of the same length but a different spelling (but, recommendation, the same length of name)? Inherently nasty.
It isn't clear if your code is directly calling the two functions with the same name but different implementations or whether the conflict is indirect (nor is it clear whether it makes any difference). However, there's at least an outside chance that renaming would work. It might be an idea, too, to minimize the difference in the spellings, so that if the symbols are in a sorted order in a table, the renaming doesn't move things out of order. Things like binary search get upset if the array they're searching isn't in sorted order as expected.
#compatibility_alias will be able to solve class namespace conflicts, e.g.
#compatibility_alias NewAliasClass OriginalClass;
However, this will not resolve any of the enums, typedefs, or protocol namespace collisions. Furthermore, it does not play well with #class forward decls of the original class. Since most frameworks will come with these non-class things like typedefs, you would likely not be able to fix the namespacing problem with just compatibility_alias.
I looked at a similar problem to yours, but I had access to source and was building the frameworks.
The best solution I found for this was using #compatibility_alias conditionally with #defines to support the enums/typedefs/protocols/etc. You can do this conditionally on the compile unit for the header in question to minimize risk of expanding stuff in the other colliding framework.
It seems that the issue is that you can't reference headers files from both systems in the same translation unit (source file). If you create objective-c wrappers around the libraries (making them more usable in the process), and only #include the headers for each library in the implementation of the wrapper classes, that would effectively separate name collisions.
I don't have enough experience with this in objective-c (just getting started), but I believe that is what I would do in C.
Prefixing the files is the simplest solution I am aware of.
Cocoadev has a namespace page which is a community effort to avoid namespace collisions.
Feel free to add your own to this list, I believe that is what it is for.
http://www.cocoadev.com/index.pl?ChooseYourOwnPrefix
If you have a collision, I would suggest you think hard about how you might refactor one of the frameworks out of your application. Having a collision suggests that the two are doing similar things as it is, and you likely could get around using an extra framework simply by refactoring your application. Not only would this solve your namespace problem, but it would make your code more robust, easier to maintain, and more efficient.
Over a more technical solution, if I were in your position this would be my choice.
If the collision is only at the static link level then you can choose which library is used to resolve symbols:
cc foo.o -ldog bar.o -lcat
If foo.o and bar.o both reference the symbol rat then libdog will resolve foo.o's rat and libcat will resolve bar.o's rat.
Just a thought.. not tested or proven and could be way of the mark but in have you considered writing an adapter for the class's you use from the simpler of the frameworks.. or at least their interfaces?
If you were to write a wrapper around the simpler of the frameworks (or the one who's interfaces you access the least) would it not be possible to compile that wrapper into a library. Given the library is precompiled and only its headers need be distributed, You'd be effectively hiding the underlying framework and would be free to combine it with the second framework with clashing.
I appreciate of course that there are likely to be times when you need to use class's from both frameworks at the same time however, you could provide factories for further class adapters of that framework. On the back of that point I guess you'd need a bit of refactoring to extract out the interfaces you are using from both frameworks which should provide a nice starting point for you to build your wrapper.
You could build upon the library as you and when you need further functionality from the wrapped library, and simply recompile when you it changes.
Again, in no way proven but felt like adding a perspective. hope it helps :)
If you have two frameworks that have the same function name, you could try dynamically loading the frameworks. It'll be inelegant, but possible. How to do it with Objective-C classes, I don't know. I'm guessing the NSBundle class will have methods that'll load a specific class.