Say, we have a superclass Car and two subclasses Ford and Porsche. Now an graphical user interface should display a proper representation (e.g. the name of the Car). We could add an additional method getCarName() to each subclass.
But now, we have another GUI which wants to represent the cars by some other property, e.g. the car name plus production country. We then have to add another method, and so on.
Generally spoken, I want to store some kind of configuration/property in a nice way. The original data structure (with perhaps a lot of subclasses) should not be changed each time another representation is wanted. So I thought of creating a HashMap which associates the subclasses to its property and hand this HashMap to the GUI.
But what kind of key should be used ? HashMap<Car, String> is no solution because I do not want to create objects of cars just to store the representation. The String representation is independent of an instance.
Desing patterns are welcome, too.
You can store all the properties/attributes of any car in a POJO(eg: CarPropertyPOJO) and then use this POJO to display which ever attributes you need. This could be uniformly used across you different pages. As per your question CarPropertyPOJO would contain 2 member variable carName and productionCountry.
In a case you just want to display a property of a single car then just passing a CarPropertyPOJO object to UI would solve the problem.
And suppose you wanna display properties of many cars in a tabular form then you can pass a
Collection object (ArrayList<CarPropertyPOJO> or a HashMap). CarSubClassName could just signify the subClass of the car.
To have a clean design, I would rather prefer to have a method like getProductionCountries in the Car class and that can be overridden by each subclass. When you add a new car, you do need to write more code, but that is rather unavoidable.
Related
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.
I've seen some DDD projects with value object representations of entities.
They usually appear like EmployeeDetail, EmployeeDescriptor, EmployeeRecord, etc. Sometimes it holds the entity ID, sometimes not.
Is that a pattern? If yes, does it have a name?
What are the use cases?
Are they value objects, parameter objects, or anything else?
Are they referenced in the domain model (as property) or are they "floating" just as parameters and returns of methods?
Going beyond...
I wonder if I can define any aggregate as an ID + BODY (detail, descriptor, etc) + METHODS (behavior).
public class Employee {
private EmployeeID id;
private EmployeeDetail detail; //the "body"
}
Could I design my aggregates like this to avoid code duplication when using this kind of object?
The immediate advantage of doing this is to avoid those methods with too many parameters in the aggregate factory method.
public class Employee {
...
public static Employee from(EmployeeID id, EmployeeDetail detail){...};
}
instead of
public class Employee {
...
public static Employee from(EmployeeID id, + 10 Value Objects here){...};
}
What do you think?
What you're proposing is the idiomatic (via case classes) approach to modeling an aggregate in Scala: you have an ID essentially pointing to a mutable container of an immutable object graph representing the state (and likely some static functions for defining the state transitions). You are moving away from the more traditional OOP conceptions of domain-driven design to the more FP conceptions (come to the dark side... ;) ).
If doing this, you'll typically want to partition the state so that operations on the aggregate will [as] rarely [as possible] change multiple branches of the state, which enables reuse of as much of the previous object graph as possible.
Could I design my aggregates like this to avoid code duplication when using this kind of object?
What you are proposing is representing the entire entity except its id as a 'bulky' value object. A concept or object's place in your domain (finding that involves defining your bounded contexts and their ubiquitous languages) dictates whether it is treated as a value object or an entity, not coding convenience.
However, if you go with your scheme as a general principle, you risk tangling unrelated data into a single value object. That leads to many conceptual and technical difficulties. Take updating an entity for example. Entities are designed to evolve in their lifecycle in response to operations performed on it. Each operation updates only the relevant properties of an entity. With your solution, for any operations, you have to construct a new value object (as value objects are defined to be immutable) as replacement, potentially copying many irrelevant data.
The examples you are citing are most likely entities with only one value object attribute.
OK - great question...
DDD Question Answered
The difference between an entity object and a value object comes down to perspective - and needs for the given situation.
Let's take a simple example...
A airplane flight to your favourite destination has...
Seats 1A, 10B, 21C available for you too book (entities)
3 of 22 Seats available (value object).
The first reflects individually identifiable seat entities that could be filled.
The second reflects that there are 3 seats available (value object).
With value object you are not concerned with which individual entities (seats) are available - just the total number.
It's not difficult to understand that it depends on who's asking and how much it matters.
Some flights you book a seat and others you book a (any) seat on a plane.
General
Ask yourself a question! Do I care about the individual element or the totality?
NB. An entity (plane) can consider seats, identity and / or value object - depending on use case. Also worth noting, it has multiple depends - Cockpit seats are more likely to be entity seats; and passenger seats value objects.
I'm pretty sure I want the pilot seat to have a qualified pilot; and qualified co-pilot; but I don't really care that much where the passengers seats. Well except I want to make sure the emergency exit seats are suitable passengers to help exit the plane in an emergency.
No simple answer, but a complex set of a pieces to thing about, and to consider for each situation and domain complexity.
Hope that explains some bits, happy to answer follow-up questions...
I am working on a Java application and came across a general implementation/meta question and wanted to reach out for suggestions.
I am looking to associate a Java object with a quantity. The java object is complex. In my case, it is a serializable object that represents JSON data from a 3rd party API. I am looking to associate a quantity with this complex Java object.
As this may be something that is easier to understand with an example, here is one. Say I have a Car class that is used to represent a car. It contains all the details of what make a car a car and is a general form that can be used to communicate over an API. Say I am making an inventory app for a dealership. The dealership would want to know how many of each Car they have. Hence the need for the association.
Ideas
There are some ways I can think of the do this.
Class it out
One idea would be to create classes that capture this association. One could have an InventoryEntry class that contains a Car and a quantity. Your dealerships inventory would then consist of a List of InventoryEntry objects.
Arrays
One can also implement this association via an Array mechanism. This can be done by creating an ArrayList<Car> for the cars and an ArrayList<Integer> for the quantity. The index for each list would be used to associate the two.
Would you recommend one of these method or some other implementation?
Using ArrayList makes it a little bit easier to start out, but if you are going to maintaining and extending this application, creating a custom class will save you a lot of time in the long run. The reason is that it would be difficult to change the ArrayList class. Yes, you could subclass the arraylist class, and override the methods that you need to, but that is making more work for yourself.
For the basic scenario that you gave, creating a CarInventory class could be extended for new behavior. The new class could just wrap a basic ArrayList or HashMap implementation, but being able to extend your application for long term maintainability is important.
I am designing an application that has two widgets:
-A list that contains arbitrary objects
-A table that displays specific properties of the currently selected object
The goal is to be able to pick an object from the list, look at the properties, and modify them as necessary. The list can hold objects of various types.
So say the list contains Vehicle objects and Person objects
public class Person
{
public String name;
public Integer age;
}
public class Vehicle
{
public String make;
public String model;
}
If I click on a Person object, the table will display the name and age, and I can assign new values to them. Similarly, if I click on a Vehicle object, it will display the make and model in the table and allow me to modify them.
I have considered writing a method like
public String[] getFields()
{
return new String[] {"name", "age"};
}
Which returns a list of strings that represent the instance variables I want to look at, and use some reflection methods to get/set them. I can define this getFields method in all of the classes so that I can use the table to handle arbitrary objects that might be thrown into the list.
But is there a way to design this so that I don't resort to reflection? The current approach seems like bad design.
On the other hand, I could create multiple TableModel objects, one for every possible class. The table would know what rows to display and how to access the object's instance variables. But then everytime a new class is added I would have to define a new table model, which also sounds like a weak design.
You have a class (Vehicle) and you know the names of some properties (make, model) that you want to be able to manipulate dynamically for an instance of this class through a JTable UI.
You have various different approaches to chose from.
A. Use the reflection API
This is what the reflection API is made for. If you want something so dynamic, there is nothing wrong with using reflection. The performance overhead will not be significant for this use case.
B. Use a library like beanutils that is based on the reflection API
This should be easier than directly using the reflection API, but it has the drawback that you need to include another dependency in your project.
C. Create dynamically at runtime the different TableModel classes.
You can do this using either the java compiler API or javassist. Based on information available at runtime, you are able to compile a new class for each different type of table model. If you follow this approach you must be aware that the creation of the class is a heavy task, so the first time you create a TableModel the application will take some time to respond.
What to chose?
Of course this is your decision. For the specific use case, the overhead added by reflection or beanutils is insignificant, so probably it is better to chose between A or B. In another use case where performance is more critical, then you could examine the C approach, without forgetting the class creation response time problem.
EDIT:
I just realized that in this specific use case there is another important functionality required. Convert from String to the appropriate data type of each property and vice cersa. Beanutils has perfect support for that, so it gets a plus here.
Best way to describe this is explain the situation.
Imagine I have a factory that produces chairs. Now the factory is split into 5 sections. A chair can be made fully in one area or over a number of areas. The makers of the chairs add attributes of the chair to a chair object. At the end of the day these objects are collected by my imaginary program and added into X datatype(ArrayList etc).
When a chair is added it must check if the chair already exists and if so not replace the existing chair but append this chairs attributes to it(Dont worry about this part, Ive got this covered)
So basically I want a structure than I can easily check if an object exists if not just straight up insert it, else perform the append. So I need to find the chair matching a certain unique ID. Kind of like a set. Except its not matching the same object, if a chair is made in three areas it will be three distinct objects - in real life they all reperesent the same object though - yet I only want one object that will hold the entire attribute contents of all the chairs.
Once its collected and performed the update on all areas of the factory it needs iterate over each object and add its contents to a DB. Again dont worrk about adding to the DB etc thats covered.
I just want to know what the best data structure in Java would be to match this spec.
Thank you in advance.
I'd say a HashMap: it lets you quickly check whether an object exists with a given unique ID, and retrieve that object if it does exist in the collection. Then it's simply a matter of performing your merge function to add attributes to the object that is already in the collection.
Unlike most other collections (ArrayList, e.g.), HashMaps are actually optimized for looking something up by a unique ID, and it will be just as fast at doing this regardless of how many objects you have in your collection.
This answer originally made reference to the Hashtable class, but after further research (and some good comments), I discovered that you're always better off using a HashMap. If you need synchronization, you can call Collections.synchronizedMap() on it. See here for more information.
I'd say use ArrayList. Override the hashcode/equals() method on your Chair object to use the unique ID. That way you can just use list.contains(chair) to check if it exists.
I'd say use an EnumMap. Define an enum of all possible part categories, so you can query the EnumMap for which part is missing
public enum Category {
SEAT,REST,LEGS,CUSHION
}