Must an InverseRelationShadowVariable necessarily belong to a planningEntity? - java

I have been trying to implement a shadow variable so that one of my problem facts can keep track of which planning entity is relevant to it, the end goal being to simplify/speed up my rules.
I am looking at the optaplanner doc about shadow variables, particularly the cloudBalancing example. In the "normal" cloudBalancing, the class CloudComputer is not a planningEntity. But in the example below, it is annotated as a planningEntity.
Are we to understand that the class "hosting" the shadow variable should be a planning entity? I thought a planningEntity had to have a planningVariable, but CloudComputer does not. If the answer is yes, I suggest being more explicit about it in the documentation. If the answer is no, then there is a mistake in this example (the #PlanningEntity annotation should be removed from CloudComputer).
The following example is from the doc:
For a non-chained planning variable, the bi-directional relationship must be a many to one relationship. To map a bi-directional relationship between two planning variables, annotate the master side (which is the genuine side) as a normal planning variable:
#PlanningEntity
public class CloudProcess {
#PlanningVariable(...)
public CloudComputer getComputer() {
return computer;
}
public void setComputer(CloudComputer computer) {...}
}
And:
#PlanningEntity
public class CloudComputer {
#InverseRelationShadowVariable(sourceVariableName = "computer")
public List<CloudProcess> getProcessList() {
return processList;
}
}
Also, is this really all that is needed so that processList is kept up to date even when CloudProcess is cloned during solving?

There are 2 kinds of planning variables: genuine (#PlanningVariable) and shadow variables. Any class that has either or combination thereof needs to be annotated as a #PlanningEntity (and added to the solver config unless you're using scanAnnotatedClasses).
Yes, this is because of the planning cloning. With the shadow variable, CloudComputer doesn't change during the planning so it doesn't need to be planning cloned. With the shadow variable, it changes during planning, so it needs to be cloned. If it wouldn't be planning cloned, the best solution would get corrupted when the internal working solution changes. That in turn would affect score calculation (if it uses the inverse list) and any consumer of best solution events or the best solution result returned by solve().

Related

Most efficient way to remove duplicated code from multiple strategies

We have 3 types of attributes in our project: CategoryAttribute, ProductAttribute and ProductTypeAttribute. These are outside of our control as they come from autogenerated classes and may contain attribute values of different types e.g. text, number or image. Now, each attribute has its own strategy to retrieve attributeValue. For simplicity, let's assume that all 3 of them have TextStrategy, NumberStrategy and ImageStrategy.
Example strategy:
#Component
public class CategoryImageAttributeStrategy implements CategoryAttributeStrategy {
#Override
public boolean isApplicable(CategoryAttribute attribute) {
return attribute.getImage() != null;
}
#Override
public Object getAttributeValue(CategoryAttribute attribute) {
//return attribute value here
//may be different or may be the same
//for ProductImageAttributeStrategy and ProductTypeImageAttributeStrategy
}
}
While getting image value may be different for all of them, getting text value is the same and we end up with 3 classes of almost the same code and I really really really don't like duplicating code.
I thought about creating an abstract class/default interface for each strategy type e.g. DefaultTextStrategy that all 3 text strategies would inherit from and either use default code provided higher or override it with own implementation, however I'm not really satisfied with this approach as it requires to create even more classes for such a simple task.
Maybe is it even possible to combine strategies of the same type (e.g. image) into one?
I would really like to hear what more experienced folks have to say in this matter as I would like to learn and improve.
Thanks in advance for your time.
There should be only 3 strategies. TextStrategy, NumberStrategy and ImageStrategy which extend the base strategy. Mixing attributes and strategy will make it confusing as both are actually independent and have many to many relationship with one another.
Let the 3 attributes extend a single Attribute class : CategoryAttribute, ProductAttribute and ProductTypeAttribute.
Let the strategies decide on what needs to be done based on the Attribute class object being passed to it. For Text strategy there would be single implementation. For Image strategy, you may require special handling for the one class.
Here's what I did:
First, I created an interface for all types of strategies named "AttributeValueStrategy". Then added 3 callbacks (type specific, e.g. NumberValueCallback etc.). Now, each strategy implements callback interface of its type and AttributeValueStrategy interface. Then there's DefaultStrategyMethods class that contains default "getAtrribute" for each type and the actual strategy call the defaultStrategyMethods (like below) or just implements its own code.
#Override
public Object getAttributeValue(Object attribute) {
return defaultStrategyMethods.getNumberValue(attribute, this);
}
Callbacks are created because only the actual strategy knows which class should it cast to (and has a method to do that), and DefaultStrategyMethods needs to use it so that's why I pass "this" as second argument (which is the callback itself).
No more duplicates, everything is clear and clean.

JUnit testing static counter of objects

I am quite a beginner at unit testing and I got some failures that I do not know how to solve. I was trying to test my simple class Employee where I have static counter of created objects, so new employees can get consecutive numbers and default names like "Name1", "Name2" etc. Here is my default initiaiton block:
{
currentNr = ++count;
setName("Name"+currentNr);
setSurname("Surname"+currentNr);
}
I wrote one JUnit class with few methods. They are working fine but methods concerning counter are working only when I run them separately (they were also working when I saved them as separate tests, but it seemed messy having so many files).
When I run the class with all the testing methods, counter is adding more object and I do not know why/when/where as test are independent. In testing methods I am creating an object and checking the counter with assertEqual. Looking for solutions I tried to work with #Before, #After, etc. but it was the same or maybe I do not know how to use it properly.
My question is what could I do to have all the test methods working or what should I write in #Before method (I tried adding and deleting objects to ArrayList and/or setting to null). I guess it is not acceptable to have test working only when run separately.
Any help will be appreciated. Thanks!
Don't use static field as counter of employees. Use instance field instead:
public class Manager {
private int employeesCount;
public Employee addEmployee() {
employeesCount++;
Employee employee = new Employee();
employee.setName("John " + employeesCount);
employee.setLastName("Smith " + employeesCount);
return employee;
}
}
There are lots of good reasons not to use static fields (read: why static variables are bad) to maintain state and one of them is that this makes your code not-testable. If you maintain your state within object (in instance fields), then there is no problem to instantiate your object and just test it as is.
Instead, make sure that there is just one instance of Manager in your program and everyone works with it (this is called singleton). Well, there is singleton pattern. And many good reasons not to use it (read: why singletons are bad). So it ends up with the fact that when you write real app, you typically use some dependency injection framework (like spring or guice) and they have ability to instantiate singleton for you when you want it.
Well, it was a bit of humor here but I'm sure you get idea that global state is considered poor practice and difficulty to test it is one of ways how it manifests itself.
The answer frenzykryger is giving a lot of valuable insight, but there is a bit more to it.
You should always look at your work with SOLID in mind. In your example, the "Single responsibility principle" can guide to a better solution. You see, good OO programming is about creating helpful abstractions. And some of the abstractions that you put into Employee simply don't belong there.
For example, one can create a class Employee to model a human being working for some company. So, employees are human beings, so probably they have names; and as they are part of an organization, yes, they might have an ID.
But: an employee gets an ID assigned! When you start at a new company, people don't come up and ask you: "please tell us your new numeric ID". Instead, somebody comes to you and tells you "this is your numeric ID, don't forget it".
So, having that in mind, some advise:
An employee does not have setters for core attributes. So, properties like "ID" or "name" that are not meant to be changed should be passed as arguments to the constructor. You simply do not create an employee object and allow later on to change the name or the id of that entity!
So, as the other answer correctly pointed out: some external class, like a "Manager" has to keep track of all "known" employees; and if a new one is added, that Manager somehow computes a new, unique ID.
Finally: is is really true: static is an abnormality in good OO design. One should have really good reasons to turn to static fields (except maybe constants) and methods. static always leads to tightly coupled code - and that something to avoid!

What to do when a type has implementation that's no longer valid?

Current Situation..
I have a Car interface:
interface Car {
void startWith(Key key);
void switchGearTo(GearMode mode);
//..
static Car newCar() { // factory
return new CarImpl();
}
}
(factory exists in separate class, nested to shorten this example)
This interface has an implementation:
class CarImpl implements Car {
private Ignition ignition;
private GearShift gearShift;
public void startWith(Key key) {
// use ignition
}
public void switchGearTo(GearMode mode) {
// use gear shift
}
}
At this point in time, Car is specific enough for the application's needs, so this structure is fine. It was created based on the YAGNI principle, since further abstractions weren't needed and our requirements were met.
The problem..
The application's requirements have changed, and Car is no longer specific enough. We need different types of cars, such as SportsCar; another level of abstraction is needed.
The problem is, Car already has a direct implementation, when it should now simply be a level of abstraction without an implementation.
I cannot remove the static factory, or it'll break code. But developers should no longer be possible to create instances of Car, since it is no longer specific enough for my application's needs.
My attempted solution..
It seems the only way to fix such a problem is to do a major redeployment. The philosophy of the application has changed, meaning a "fresh start" is needed, and there is no other way to solve this problem. (I'm really hoping this isn't the case)
I could specify a default car, I'd still need to create a new (descriptive) method for the default car, resulting in 2 methods in the same class doing the exact same thing (telescoped without change). This adds clutter and possible confusion, which doesn't help with scaling.
My question..
Is this a problem that could be solved without a major redeployment? If not, how could one structure their code to avoid this problem? Is it possible to account for such a change in requirements while still abiding by YAGNI?
If a type implementation is no longer valid, usually a fresh start is recommended and sometimes it's the only solution. If an interface has been defined, you can't just stop other classes from implementing it.
Though with your problem, as I got it, changing the interface hierarchy can solve it. Since interface Car is more abstract now, create less abstract interfaces (interface SportsCar etc) extending the interface Car. Also, you have class CarImpl to implement the less abstract interfaces.
Finally, you can't stop another developer from instantiating Car as long as Car interface is defined.
The whole point of a factory is to solve problems like these, i.e. not allowing client code to explicitly construct an instance of a specific class. Your factory should now return an instance of a 'default' class (as mentioned by others) which won't be an instance of CarImpl, but something more specialised, e.g. a sedan, or whatever you conceive to be a default car.

Encapsulation - why do we need it when setters are already public? [duplicate]

This question already has answers here:
Why are getter and setter method important in java? [duplicate]
(6 answers)
Closed 7 years ago.
Encapsulation is hiding the data. I would like to hear some really interesting answers here.
What is the point behind keeping variables as private when we already declare public setter methods for variables?
I understand the usage of encapsulation but when we are making the setters as public what is the point behind keeping the variables as private, we can directly use public access modifiers.
Is it because we do not want others to know the exact way we are storing data or managing data on the back-end?
Is it because we do not want others to know the exact way we are
storing data or managing data on the back-end?
Yes, that's the point. It is related to the concepts of abstraction and information hiding too.
You provide a public setter that when invoked by the class client will have the effect that you have documented. It is none of the client's business how this effect is actually achieved. Are you modifying one of the class attributes? Ok, let the client know that, but not the fact that you are actually modifying a variable. In the future, you could want to modify your class so that instead of a simple backup variable it uses something completely different (a dictionary of attributes? An external service? Whatever!) and the client will not break.
So your setter is an abstraction that you provide to the client for "modify this class attribute". At the same time you are hiding the fact that you are using an internal variable because the client doesn't need to know that fact.
(Note: here I'm using the word "attribute" as a generic concept, not related to any concrete programming language)
I fully agree with Konamiman's answer, but I'd like to add one thing:
There are cases where you really don't want that abstraction. And that's fine.
A simple example I like to use here is a class for a 3-dimensional float vector:
class Vector3f {
public:
float x;
float y;
float z;
};
Could you make those fields private and provide setters instead? Sure, you could. But here you might argue that the class is really just supposed to provide a tuple of floats and you don't want any additional functionality. Thus adding setters would only complicate the class and you'd rather leave the fields public.
Now, you can easily construct scenarios where that might bite you later on. For instance, you might one day get a requirement that Vector3fs are not allowed to store NaNs and should throw an exception if anyone tries to do so. But such a hypothetical future problem should not be enough to justify introducing additional abstractions.
It's your call as a programmer to decide which abstractions make sense for the problem at hand and which ones would only get in your way of getting the job done. Unnecessary abstractions are over-engineering and will hurt your productivity just as much as not abstracting enough.
Bottom line: Don't blindly use setters everywhere just because someone claimed that's good practice. Instead, think about the problem at hand and consider the tradeoffs.
Because by encapsulation we provide single point of access. Suppose you define a variable and its setter as follows
String username;
public void setUsername(String username){
this.username = username;
}
Later you like to add some validation before setting username property. If you are setting the username at 10 places by directly accessing the property then you don't have single point of access and you need to make this change at 10 places. But if you have one setter method then by making a change at one place you can easily achieve the result.
Think about this : I'm representing a real life object, a Lion through a class. I'd do something like this.
class Lion {
public int legs;
}
Now my class is needed by some other developer to create an object and set its legs field. He'd do something like this
Lion jungleKing = new Lion();
jungleKing.legs = 15;
Now the question is, Java won't restrict him to setting any number more than 4 as the number of legs for that object. It's not an error, and it'll run just fine. But it's a logical blunder, and the compiler won't help you there. This way a Lion may have any number of legs.
But if we write the code this way
class Lion {
private int legs;
public void setLegs(int legs){
if(legs > 4){
this.legs = 4;
}
else this.legs = legs;
}
}
Now you won't have any Lion with more than 4 legs because the policy of updating the fields of the class has been defined by the class itself and there's no way anyone not knowing the policy is going to update the legs field because the only way to update the legs field is through the setLegs() method and that method knows the policy of the class.
Although Konamiman's answer is spot on, I'd like to add that, in the particular case of public setters versus directly exposing public fields you are asking, there is another very important distinction to keep in mind apart from information hiding and decoupling implementation from the public surface, or API, of a class; validation.
In a public field scenario, there is no way to validate the field's value when it's modified. In case of a public setter (be it a Foo {get; set;} property or a SetFoo(Foo value)) method you have the possibility to add validation code and launch required side-effects and this way ensure that your class is always in a valid or predictable state.
What if you do want to a range check before assignment? That's one of the cases I use setters and getters
More or less simple and realistic example I encountered in practice is an Options class, which has a lot of setters and getters. At some point you might want to add new option which depends on others or has side effects. Or even replace group of options with Enum. In this case setA function will not just modify a field, but will hide some additional configuration logic. Similarly getA will not just return value of a, but something like config == cStuffSupportingA.
Wikipedia has a good overview of [mutator methods(https://en.wikipedia.org/wiki/Mutator_method), which is what setter methods are and how they work in different languages.
The short version: if you want to introduce validation or other logic that gets executed on object modification it is nice to have a setter to put that logic in. Also you may want to hide how you store things. So, those are reasons for having getters/setters. Similarly, for getters, you might have logic that provides default values or values that are dependent on e.g. configuration for things like Locale, character encoding, etc. There are lots of valid reasons to want to have logic other than getting or setting the instance variable.
Obviously, if you have getters and setteres, you don't want people bypassing them by manipulating the object state directly, which is why you should keep instance variables private.
Other things to consider include whether you actually want your objects to be mutable at all (if not, make fields final), whether you want to make modifying the object state threadsafe with e.g. locks, synchronized, etc.
Setting fields as private documents a powerful fact: these private fields are only directly used within the current class. This helps maintainers by not having to track down field usage. They can reason better on the code by looking at the class and determining that the effects on and from these fields with the class' environment go through public and protected method calls. It limits the exposure surface on the class.
In turn, defining a "setter" for a private field is not about giving it publicity again. It is about declaring another powerful fact: an object belonging to this class has a property that can be modified from the outside. (The terms object and property are used in the sense of a bounded part of the whole and an observable fact about this part, not in the OOP sense)
Why then declare a "setter" on a field when making the field public would suffice? Because declaring a field not only binds a name to a property of the objects of the class, but also commits to use memory storage for this property.
Therefore, if you declare a "private field with a setter", you declare three things:
You declare that the name you gave to the field/setter cluster represents a property of the object which is of interest when the object is seen as a black box.
You declare that the value of this property is modifiable by the environment of the object.
You declare that in this particular concrete class, the property of the object is realized by committing some memory storage to it.
I advocate that you never make your fields private with getters and setters indiscriminately. Fields are for describing storage. Methods are for interactions with the environment. (And the particular case of "getters" and "setters" are for describing properties of interest)

Java: Enforcing doubly linked objects

I am designing a game engine in Java.
At the core of this engine exist the two classes Asset and Attribute, where an Asset has a list of Attributes. Most Attributes need no link back up to their Attribute, meaning that Attributes can and often do appear in the lists of more than one Asset. However, there is an extention of Attribute called UniqueAttribute, which is an implementation for those that are specific to their Asset, and utilise a link back.
Ideally, my Asset's addAttribute method would look something like this if I cut out the other code:
public void addAttribute(Attribute attribute){
if(attribute instanceof UniqueAttribute)
((UniqueAttribute)attribute).setAsset(this);
attributeList.add(attribute);
}
Unfortunately, since they live in different packages, UniqueAttribute.setAsset() must be public. This leaves the method open to outside users of the engine to mess with, and while I could just handwave it off by saying using this method directly is a bug - it seems rather sloppy.
The second option is to provide the UniqueAttribute with the Asset on construction, meaning that the code at the point of creation would look something like this:
asset.addAttribute(new UniqueAttribute(asset));
While I can add a check-and-throwable or assert to confirm the correct asset is passed in, I am basically relying on the user to connect the two, which I also would prefer not to do.
The third option is to bite the bullet and put 50 java files all into the same package so that I can just use the standard visiblity.
Is there some kind of pattern or something that will help link these two together without exposing the wires, or forcing me to put everything into one massive package?
Irrelevant rant: I have always disliked that the concept of subpackages in java has not really been expanded in any meaningful way. A subpackage, as far as java is concerned is simply a different package, and there have been many occasions I could do with more visibility modifiers directly related to this.
My suggestion would be that Asset, Attribute and UniqueAttribute should all be in the same package (possibly along with a few other core "engine" classes). Then you can use standard package visibility for UniqueAttribute.setAsset.
You don't need to put all other classes in the same package - your Asset.addAttribute method should be public and accessible from other packages so the rest of your application can just use that directly.
So the solution could be called "3-" in your categorisation.
As some more general points, also consider:
Whether you really need the complexity of both Attributes and UniqueAttributes - I'm not sure you really do, having previously implemented a reasonably complex game object model without needing anything that looked like a UniqueAttribute. If the UniqueAttribute "needs a link back" then perhaps it is trying to be too clever / do too much?
Even if you do need both, do you really want to write code that treats them the same way / as part of the same object heirarchy? they seem quite conceptually different, and you will end up writing a lot of conditional code if you conflate the two.....
There are various other advantages of attributes being consistently shared and immutable - it's better for memory usage, concurrency and testability among other things. And as they are presumably quite small, the cost of copy-on-write semantics is trivial in the cases where you need it.
I would add a callback method in Attribute which is called when an instance of Attribute is added to an Asset:
class Attribute {
protected void addedToAsset(Asset asset) {
// do nothing
}
}
This method would be called in the addAttribute method
class Asset {
public void addAttribute(Attribute attribute) {
attributeList.add(attribute);
attribute.addedToAsset(this);
}
}
And the method would be overridden in UniqueAttribute in order to control the link with Asset:
class UniqueAttribute extends Attribute {
Asset asset;
protected void addedToAsset(Asset asset) {
// manage the previous link if needed
if (this.asset != null) { ... }
this.asset = asset;
}
}
Wit this solution, Asset and Attribute should be placed in the same package. But UniqueAttribute could be in whatever package you want.
Modify your scond option
asset.addAttribute(new UniqueAttribute(asset));
like this:
class UniqueAttribute {
Asset asset;
public UniqueAttribute(Asset asset) { this.asset = asset; asset.addAttribute(this); }
}
Do a similar approach for the non unique Attribute. That means instead of using addAttribute() from the outside, only use it inside of the constructors.
An other option is to add two factory methods to Asset: createAttribute() and createUniqueAttribute();
Well, basically you want to do 3 things:
make setAsset method visible inside the package containing Asset class
hide setAsset method from all other packages
don't use subpackages to achieve that
That's a bit problematic: if you declare public that method in Attribute class all other classes including that package (let's call it AttributePackage), you can't prevent the user to include somewhere that package.
On the other hand you could do the following:
create an interface containing only the Attribute method that user should use, let's call it AttributeInterface
make Attribute implement that interface
add AttributeInterface to a new package
An user that want use Attribute class should use it through AttributeInterface meanwhile
Asset will use Attribute class directly in order to have access to all methods.
I'll make an example:
//attribute interface package
public interface AttributeInterface{
public void publicAttributeMethodClientShouldUse();
}
//attribute package
public class Attribute{
public void setAsset(Asset a);
public void publicAttributeMethodClientShouldUse();
}
Asset will reference directly Attribute meanwhile user should reference AttributeInterface. Hope to be clear.
First, these entities do appear to be so closely related as to be placed in the same package. I'd put them in the same package and make the addAttribute method package-private.
Bear in mind though that since the introduction of AccessibleObject in Java, visibility and access control in the language has become merely cosmetic... Anyone using your library can grab your classes and make private methods and fields accessible and modifiable! Hell, they can even modify final members! So, don't put much emphasis in the visibility aspect and just make sure your model and method flow make sense for your users and work correctly.

Categories

Resources