Java Attribute Driven Collection - java

I need to implement some specific functionality and I am wondering if you might know of a java library that does this, or something like it already. I would rather use an existing before building my own.
Basically I want a collection type class that contains instances of FooBar. When the container is constructed, I specify the attribute values or ranges that qualify a FooBar for membership, so when a FooBar instance is inserted, it will be rejected if it does not meet the criteria. In addition, if the attributes of any FooBar in the container are modified in such a way that they no longer meet the membership criteria, they will be ejected (preferably with some sort of callback to registered listeners).
I can elaborate more, but I think the concept is fairly straight forward.
Seen anything like that ?
Thanks.

You could add a set of listeners to the class performing the add / retain and which allows the class to 'choose' whether to add candidate as a listener - and also later on based on your interesting events occurring - whether to 'retain' them or evict them:
public interface AddableEvictable {
public boolean isAddable();
public boolean evict();
}
Then add a Set to your interesting server class and candidate classes to add/(/later evict) would need to (a) implement this simple interface and (b) offer themselves to the server class for it to decide whether to add/not (and later when/if to evict)

Related

How can I interpret to a sequence diagram an action from an Analysis Pattern?

Based on the Accountability Analysis Pattern:
The concept is that we have a class diagram following the logic of the Accountability Analysis Pattern. How can I use the given function assignStaffContact() to assign contact?
I have undrerstood that StaffContact class is a control class and the Client, StaffMember are entity classes (we don't care about the TimePeriod class).
I cannot figure out which classes are gonna play a part in the procedure of assigning staff contact in order to create the proper sequence diagram (UML) of this action. Arbitrarily there must be a boundary class providing the wanted interface. The actor is gonna pick the case of assigning staff contact, which will trigger the method assignStaffContact() of the control class StaffContact but with which entity classes this will communicate and finally assign the staff?
I am getting confused with class ContactForCampaign and the logic behind it being connecte to the classes Client and StaffMember. I hope I explained well enough my problem and my thought process.
This diagram says that:
A StaffContact instance can be associated to several ContactForCampaign instances
Each instance of ContactForCampaign is associated with exactly one instance of a Campaign, and defines exactly one StaffMember object as responsible, and. one Client object as commissioner (probably for the campaign).
As a consequence, we can only guess that StaffContact::assignContact() requires to know which StaffMember to add (should be an argument of the operation). Since several ContactForCampaign instances can be considered, the ooeration would probably also need to know which ContactForCampaign is relevant for the assignment. Probably this can be determined with the help of a Campaign parameter. Two cases must then be considered: replacing a staff member of an existing ContactForCampaign or create a new one if no assignment exist for a campaign. You have now all the ingredients for your sequence diagram. Note also that the operation would need to know which client is to be assigned as commissioner if a new ContactForCampaign os created.
The result could look like (simplified):
Note that StaffContact::removeStaffContact() does not seem relevant, in view of the multiplicity 1 for the StaffMember, unless you condider removing as well the ContactForCampaign, which would then cause to lose the information regarding the commissioner.
Last but not least, in view of the 1 multiplicity on the side of StaffContact, it would not be a control class, since the control is in princple existing for the time of the use case execution only, and should not have a permanent semantic link to the objects that it controls.

A design pattern to handle similar groupings of objects with different multiplicities?

I am designing a program that allows you to create an object with traits and then add it to a database. For example, a renting property like so:
public class Property
{
PropertyType type;
int bedrooms;
int bathrooms;
double squareFootage;
boolean furnished;
}
Then, you or other users can search the database for objects based on those traits. But here are the restrictions:
All properties have one of each trait defined (you can't leave one trait blank)
You may search for properties by any one trait, combination of traits, or no traits (to see all). AND you can specify a multiplicity for each trait. For example, you can specify a HOUSE with 2, 3 or 4 bedrooms and 2 or 3 bathrooms. Thereby not putting restrictions on square footage or furnishing.
This poses a problem, as the existence of a trait in the search criteria may or may not exist, and may have a multiplicity. Here is my current solution to hold the search criteria:
public class SearchCriteria
{
ArrayList<PropertyType> type;
ArrayList<int> bedrooms;
ArrayList<int> bathrooms;
ArrayList<double> squareFootage;
ArrayList<boolean> furnished;
}
The problem is that when I want to add another trait to Property, I have to add it to both these classes (and probably more in database controller etc) and add additional functions for it in each. What is a design pattern I can utilize to make this code more modular and abstract?
Essentially, a good answer would be a solution that allows the addition or removal of traits by only changing one class/file.
Simply using an interface Trait with an overidden function getTrait() wouldn't work because the return types aren't the same across all traits.
EDIT: I have to implement a SearchCriteria class because this program is run on a client/server connection, so SearchCriteria will be serialized and sent over a socket, not sent directly to the database.
If you only have a handful of traits, and they're fundamental to your business model, it's totally reasonable to have to change more than one class when you add a new trait or want to change the type of behavior of one of those traits.
However, if you're trying to come up with a model that can handle dynamically adding different types of traits to your object, you may consider not encoding the traits as class properties at all. Rather, have your model contain a list of Traits, where each Trait knows its TraitType. Each TraitType has a specific shape for its data, as well as a specific shape for its Criteria. This would enable you to define your model in a file or database somewhere, and change it on demand, and only have to change the code when you identify a new TraitType. But it would also be an enormous amount of work, and would only be worthwhile if your business needs require a high degree of configurability.

Spring Data MongoDB template converts to wrong class

Using Spring 5.0.6 and Spring-Data-Mongo 2.0.7, I have an issue when fetching entities being transformed into the wrong class. See the following simplified scenario:
Entity setup:
public class PersistableObject {
#Id #Field("_id") private String id;
}
#Document(collection = "myapp_user")
public class User extends PersistableObject {...}
public class RealUser extends User {...}
public class VirtualUser extends User {...}
So, there is a common MongoDB collection storing both types of User, discriminated by the automatically added _class property.
Furthermore, there is a Repository into which the MongoTemplate is injected.
#Autowired
private org.springframework.data.mongodb.core.MongoTemplate template;
Everything fine, so far. Now, if I want to fetch all documents that contain a RealUser, I could call this
template.findAll(RealUser.class)
I'd expect the template to find all documents that have the discriminator property _class set to com.myapp.domain.RealUser.
But this doesn't work as expected. I even get all VirtualUsers, as well, put into objects of type RealUser with all VirtualUser-specific properties missing, and all RealUser-specific properties set to null.
Furthermore, when I go and save a User, which is actually a VirtualUser in MongoDB, but has been squeezed into a RealUser class, Spring would change the _class-property to the wrong type, magically converting a VirtualUser into a RealUser.
So both methods here would load the entire collection and squeeze all objects into the specified class, even if it is the wrong one:
template.findAll(VirtualUser.class)
template.findAll(RealUser.class)
This behavior is probably not desired, or if so, then it is extremely misleading and harmful. You can easily shred your whole data with this.
Can anyone shed some light on this?
I've created a ticket at Spring's Jira. Find Olivers comment below:
The method actually works as expected but I agree that we need to
improve the JavaDoc. The method is basically specified as "Load the
documents the given type is configured to persisted in and map all of
them (hence the name) to the given type". The type given to it is not
used as a type mapping criteria at the same time. Every restriction
you want to apply on the documents returned needs to be applied
through a Query instance, which exposes a ….restrict(…) method that
allows to only select documents that carry type information.
The reason that findAll works the way it works is that generally
speaking – i.e. without an inheritance scenario in place – we need to
be able to read all documents, even if they don't carry any type
information. Assume a collection with documents representing people
that have not been written using Spring Data. If a
findAll(Person.class) applied type restrictions, the call would return
no documents even if there were documents present. Unfortunately we
don't know if the collection about to be queried carries type
information. In fact, some documents might carry type information,
some might not. The only way to reasonably control this, is to let the
user decide, which she can by either calling Query.restrict(…) or not.
The former selects documents with type information only, the latter.
As I said, I totally see that the JavaDoc might be misleading here.
I'm gonna use this ticket to improve on that. Would love to hear if
the usage of Query.restict(…) allows you to achieve what you want.

Structural and behavioral modelling of the possibility of unknown (or pending variable) objects rather than concrete ones

In the following, I provide an abstract description of my problem, as it will be more complicated if I provide the context and the specific code.
I have a Class Specification. A file reader accesses specific nested specifications from a file and furnishes a Specification instance correspondingly. The file may contain incomplete specifications, i.e. some values are to be bound later (for example, from a user input).
class Specification{
Criteria spec1;
AnotherCriteria spec2;
...
}
Now consider the interface:
Interface Criteria {
criteriaMethod1();
criteriaMethod2();
}
And consider the implementing class:
class ConcreteCriteria1 implements Criteria{
someDataMember;
#Overrride
criteriaMethod1(){
// some implementation goes here
}
#Overrride
criteriaMethod2(){
// some implementation goes here
}
}
Now let's consider a class responsible for performing some specific tasks depending on a Criteria passed:
class WorkExcuter {
doSomeWork(Criteria criteria);
}
I have a case, in such the criteria passed to doSomeWork is unknown, for example, in a waiting state to get some input from the user. This unknown state forces some specific additional attributes, for example, it's a maximum lenght of characters, an identifier, a waiting time, etc. To model that, let's consider that we have:
Interface ReuqiredInput {
reuqiredInputMethod1();
}
Problem:
I want an 'intelligent' way (e.g. some design pattern) to make both, Specification (in spec1 data memebr) and doSomeWork accept ReuqiredInput instead of Criteria when the state is unknown as described. So they should accept both cases: either Criteria, or RequiredInput.
Possible ways around:
Make ConcreteCriteria1 implement ReuqiredInput, in addition to Criteria; i.e., having a single concrete class implementing both interfaces; but then, I will have my concrete class as an ugly XOR between two different sets of elements that have nothing to do with each other and it has to have a method that figures out which set of elements is filled (to avoid exceptions as the other set will be null), and it complicates the access via the implemented interfaces.
Overload doSomeWork; so that:
class WorkExcuter {
doSomeWork(Criteria criteria);
doSomeWork(RequiredInput input);
}
But that solves the behavior part, but not the structural part, i.e. How to convince Specification that it can accept data member in sepc1 of type RequiredInput instead of Criteria?
Your Criteria doesn't have different data in different states, it has whatever data members it needs for its calculations and they might be unset when it is waiting for user input; there are various options to ensure it receives user input before proceeding to the main calculations. For example
criteriaMethod1() etc. can request user input interactively if needed (presumably, the first time they are called). No RequiredInput objects are used. Likely to be messy because it places user interface code in a business logic component like Criteria.
criteriaMethod1() etc. can return an error if called with an incomplete state, then their caller is expected to ask them what input they require (with some Criteria method returning RequiredInput objects). The caller uses RequiredInput objects to obtain information, passes that information to the Criteria, and then criteriaMethod1() etc. can be called successfully.
even better, Criteria objects are created only when all needed data are available, and they are never in an invalid waiting-for-input state. For the case of combining an incomplete specification file with user inputs, this probably involves specific classes to represent the content of the configuration file and a module that, given the configuration file, asks the user for missing information and creates Criteria. The rest of the program, the part that uses Criteria, only sees complete ones. RequiredInput objects might be useful as an intermediate representation of what the configuration file leaves unspecified.

How should one use abstracted instances

I am designing a game and I have good overview of what I am doing.
However I've been trying to improve my OOP skills but now and then I face the same problem, how should I use the abstracted objects?
Lets say I have a list of Entitys that represents anything that has x and y property on screen and probably width and height haven't figured all out yet!
Then I have special types of entitys, one that can move and one that cannot and probably something like collidable in future.
They're all in a collection of Entitys (List<Entity> in my case) and now I want to simulate entitys that moves and are instances of DynamicEntity on main loop but they're all on abstract list of Entitys and I don't know is the Entity in loop either dynamic entity or not.
I know I could just check it with instanceof but I am pretty sure that's not the best idea..
I've seen some people having something like boolean inside the Entity for checking its type but I don't really want to hardcode all kind of entitys there..
I just want to know what is the best practice in such case?
Usually it's better to avoid checking the type if possible. If you think you need to use instanceof in your code then there's probably an abstraction you could be using to make your design more extensible. (If you decide to add a third type of Entity in the future you don't want to have to go back and update all of your instanceof checks with a third case.)
There are two common ways to have different actions based on an instance's concrete type without checking the concrete type:
One common way is the visitor pattern. The idea here is to create a Visitor class with an action for each type of object. Next, each concrete class has an accept method which simply calls the correct visit method inside the visitor class. This single level of indirection allows the objects to choose the correct action themselves rather than you choosing it by checking the type.
The visitor pattern is usually used for one of two reasons. 1) You can add new actions to a class hierarchy that implements the visitor pattern without access to the classes' source code. You only have to implement a new visitor class and use it in tandem with the visitable classes' pre-existing accept methods. 2) When there are many possible actions one can perform on classes from some type hierarchy sometimes it's more clear to split each action off into it's own visitor class rather than polluting the target classes with a bunch of methods for a bunch of different actions, so you group them with the visitor rather than the target classes.
However, in most cases it's easier to do things the second way: to simply override the definition of a common method in each concrete class. The Entity class might have an abstract draw() method, then each type of Entity would implement that draw() method in a different way. You know that each type of Entity has a draw() method that you can call, but you don't have to know the details of which type of entity it is or what the method's implementation does. All you have to do is iterate over your List<Entity> and call draw() on each one, then they'll perform the correct actions themselves depending on their type since each type has its own specialized draw() implementation.
You're right that you don't want to check the instance type or have some sort of function to check capability. My first question would be - why do you have a list of entities of that base type in the first place ? It sounds to me like you need to maintain a list of dynamic entities.
You could implement a move() method that does nothing for non-dynamic entities, but again that doesn't seem right in this particular scenario.
Perhaps it would be better to implement an event that triggers the iteration of that list, and pass that event into each object in turn. The dynamic entities could decide to move upon that event. The static entities would obviously not.
e.g.
Event ev = ...
foreach(e : entities) {
e.actUpon(ev);
}
In this scenario you could have different event types, and the entities would decide upon their action upon the basis of the event type and the entity type. This is known as double-dispatch or the visitor pattern.
If your processing of entities relies on knowing details about the entity types, then your Entity abstraction doesn't buy you much (at least not in this use-case): your List<Entity> is almost as opaque for you as a mere List<Object>.
If you know that every entity you can imagine will be either static or dynamic, there's no "hard-coding" in having a boolean property to all entities: isDynamic() or something.
However, if the dynamic aspect only makes sense for a subset of your entities, this flag will indeed bring some mess to your abstraction. In this case, my first guess is that you didn't model the use-case properly since you need to work with a list of items that do not provide enough polymorphic information for you to handle them.

Categories