I would like to translate the attached UML to Pseudocode. I have the following class and interface headers below.
I would like to know
1) if this is correct?
2) what is the relation between Store and Manager and Store and StoreEmployee?
I have Manager and StoreEmployee as private fields in Store. Is this correct?
if yes, then why they are not included in attributes
3)What is the relation between store and Store Test ?
4) I have Employee as interface while PayRoll Record as concrete class?
Is this correct? both have broken line arrow connection?
public interface Employee { }
public class Manager implements Employee{ }
public class StoreEmployee implements Employee{ }
public class SalesAssociate extends StoreEmployee { }
public class PayrollRecord { } //
public class Store extends PayrollRecord { } // does it have Manager and StoreEmployee as private fields
public class StoreTest { } //does it have Store as private field
Here are some quick answers that don't fulfil your questions perfectly, while still hopefully point you in the right direction.
You have your extends mixed in with your composed of. Check your UML documentation again. So, no you are incorrect.. but also correct in some places. :)
A Store has a single manager (if there is not a number attached, then it is assumed to be a 1..1 relationship).
Look at how you used the same arrow in previous solutions.
Yes, look at the heads of the arrows. The Employee implies inherits from, where the PayRollRecord is just a general usage arrow.
For these, the previous answers should help you answer your questions here. :)
public class Store extends PayrollRecord { } // does it have Manager and StoreEmployee as private fields
public class StoreTest { } //does it have Store as private field
Related
I'm considering Realm as a database solution for various reasons, but the big one currently being the TransactionTooLargeException now being thrown in Nougat has made it so I have to rework my current database architecture, based on ActiveAndroid, which has its own annoying limitations. The difficulty is that Realm does not support inheritance (https://github.com/realm/realm-java/issues/761) and they don't seem in any particular hurry to get around to it. Instead, they recommend using composition over inheritance, but I can't figure out how to make that work with Gson/Json deserialization.
Example:
Superclass: Animal, with subclasses Dog and German Shepherd
public class Animal {
private int numLegs;
private boolean hasFur;
}
public class Dog extends Animal {
private String color;
private boolean canDoTricks;
}
public class GermanShepherd extends Dog {
public boolean isGuardDog;
public boolean isAtRiskOfHipDysplasia()
}
(Sorry, this is a super canned example, just to illustrate).
Now let's say the json for this looks like:
{
"numLegs" : 4,
"hasFur" : true,
"color" : "Black & Brown",
"canDoTricks" : true,
"isGuardDog" : true,
"isAtRiskofHipDysplasia" : false
}
Now, I cannot modify the Json because it's an API that's giving it to me.
Looking at this answer: https://stackoverflow.com/a/41552457/4560689, it appears it is possible in a very hacky way to make it sort of work, but the answer notes that there are limitations including that the serialization would be wrong. Since the server only talks in the json format that doesn't involve crazy composition, this presents a problem.
Can I write a custom Gson deserializer/serializer to make this work? If so, what would that look like? I basically need to be able to convert a json payload into up to N objects, where N - 1 objects are nested inside the base object.
So with composition (note this isn't necessarily "Realm" composition, just an example, since it looks like Realm has to use some weird form of interface-composition), I'd have a class like below:
public class GermanShepherd {
public Animal animal;
public Dog dog;
// Generate a bunch of delegate methods here
}
Am I barking up the wrong tree? It feels like Realm might not work for what I'm trying to do, and inheritance is built into the API I'm using in multiple places, and specifically in the objects I want to persist, so I have to either figure out a workaround or use another solution. ActiveAndroid (what I'm using now) is also a less than ideal solution and I'm sick to death of dealing with skirting around deadlocks, crashes, querying on background threads that now cause crashes if the data is too big to pass in an Intent, etc...all issues with SQLite. I'm open to solutions to my main question or to alternatives that would solve this problem. Thanks in advance for your help!
You should create a new RealmObject class for each flattened concrete class, and map your JSON representation to them.
To retain inheritance, you can simulate it by inheriting getters/setters from interfaces that inherit from one another.
public interface IAnimal extends RealmModel {
int getNumberOfLegs();
void setNumberOfLegs(int legs);
boolean getHasFur();
void setHasFur(boolean hasFur);
}
public interface IDog extends IAnimal {
String getColor();
void setColor(String color);
boolean getCanDoTricks();
void setCanDoTricks();
}
public interface IGermanShepherd extends IDog {
boolean getIsGuardDog();
void setIsGuardDog(boolean isGuardDog);
boolean getIsAtRiskOfHipDysplasia();
void setIsAtRiskOfHipDysplasia(boolean isAtRisk);
}
Because then you can do
public class GermanShepard
extends RealmObject
implements IGermanShepard {
private int numLegs;
private boolean hasFur;
private String color;
private boolean canDoTricks;
private boolean isGuardDog;
private boolean isAtRiskofHipDysplasia;
// inherited getters/setters
}
You can even make repository class out of it
public abstract class AnimalRepository<T extends IAnimal> {
protected Class<T> clazz;
public AnimalRepository(Class<T> clazz) {
this.clazz = clazz;
}
public RealmResults<T> findAll(Realm realm) {
return realm.where(clazz).findAll();
}
}
#Singleton
public class GermanShepardRepository extends AnimalRepository<GermanShepard> {
#Inject
public GermanShepardRepository() {
super(GermanShepard.class);
}
}
And then
#Inject
GermanShepardRepository germanShepardRepository;
RealmResults<GermanShepard> results = germanShepardRepository.findAll(realm);
But you can indeed merge them into one class and then give it a String type; parameter to know what type it originally was. That's probably even better than having all these GermanShepards.
I have a parent class - Product
public abstract class Product {}
And 3 sub-classes which extends it:
public class Vinyl extends Product {}
public class Book extends Product {}
public class Video extends Product {}
All sub-classes override the preview() method with their specific implementation.
Now, I have a new design demand: I need to define a combo item of vinyl & book which also has a preview() method (which is a combination of vinyl & book). In the instructions it says I can create Interface\ class field member or any implementation I want to support it, but I'm not sure how exactly.
Is the new design should also be implemented with inheritance or should I change the current design?
Is the new design should also be implemented with inheritance or should I change the current design?
The new design can be implemented purely with inheritance. But the real problem with this would be that you would have way too many subclasses. You could easily create a new subclass of Product called VinylBook and be done with it. But what happens when you have to introduce another combination, say VinylVideo. You would have to create a new subclass for this as well and so on.
The solution is to use inheritance and composition together. The Composite pattern would be a good fit for this problem. According to wikipedia :
The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
Let's start by defining a CompositeProduct
public class CompositeProduct` extends Product {
private List<Product> products;
public CompositeProduct(List<Product> products) { this.products = products }
public String preview() {
String previewText = "";
for(Product product : products) { previewText+=product.preview(); }
return preview;
}
}
You now have composite product that behaves as if it is one single product allowing you to create combo products on the fly without the need to create a new subclass for each combo.
An example of how you can create products on the fly :
Book book = new Book();
Vinyl vinyl = new Vinyl();
List<Product> products = new List<>();
products.add(book);
products.add(vinyl);
CompositeProduct vinylBook = new CompositeProduct(products);
You can also take a look at the Decorator pattern if you are looking at adding additional behavior to your products on the fly.
I would like to give an alternative since I wasn't pleased by the other solution.(Don't get me wrong, it's simple and straight forward, also the Composite concept is a very good one to learn and the user also mentioned the Decorator pattern that it's really useful).
My problem with that solution is that you give the products (whichever they are) and then what can you do?
Let's imagine
public abstract class Product {
abstract void preview();
}
Now your CompositeProduct is so generic that can only implement something like this
void preview(){
for(Product product : products) product.preview();
}
And I bet that's not what you want.
My alternative is using Composition through interfaces. I can't tell much with more detail on the Domain so I will give a simple example.
What is a Book? Let's imagine something Readable.
public interface Readable { void read(); }
public class Book extends Product implements Readable {}
What is a Vinyl? Showable
public interface Showable { void show(); }
public class Vinyl extends Product implements Showable {}
Now BookVinyl would simply be
public class BookVinyl extends Product implements Readable, Showable { }
What will this give you? Well, now BookVinyl can be read, just like a book, and show, just like a Vinyl. And the preview? It can show and then read or whatever.
Whole day I have tried to find a answer on the question:
"How to add auto-Incrementing "id" field in an Entity class?".
I am using Morphia (a type-safe java library for Mongo DB). After a couple hours of digging in source code and googling I have found a LongIdEntity class in org.mongodb.morphia.utils package. Based on this class I have implemented the following solution. See below:
City class:
#Entity
public class City {
#Id
private Long id;
}
Hotel class:
#Entity
public class Hotel {
#Id
private Long id;
}
CityLongIdEntity class:
public class CityLongIdEntity extends LongIdEntity {
public CityLongIdEntity(Datastore ds) {
super(ds);
}
}
HotelLongIdEntity class:
public class HotelLongIdEntity extends LongIdEntity {
public HotelLongIdEntity(Datastore ds) {
super(ds);
}
}
DAO implementation:
CityDAO class:
public class CityDAO extends BasicDAO<City, Long> {
public CityDAO(Datastore ds) {
super(ds);
}
#Override
public Key<City> save(City c) {
if (c.getId() == null) {
CityLongIdEntity ent = new CityLongIdEntity(getDs());
getDs().save(ent);
c.setId(ent.getMyLongId());
}
return getDs().save(c);
}
}
HotelDAO class:
public class HotelDAO extends BasicDAO<Hotel, Long> {
public HotelDAO(Datastore ds) {
super(ds);
}
#Override
public Key<Hotel> save(Hotel h) {
if (h.getId() == null) {
HotelLongIdEntity ent = new HotelLongIdEntity(getDs());
getDs().save(ent);
h.setId(ent.getMyLongId());
}
return getDs().save(h);
}
}
Or you can see all this code on the Github
The UML diagram is also available:
All this code works as expected and I am happy, but I have a couple questions:
As you can see, for each Entity I need to create additional Entity, for example: for entity City I created CityLongIdEntity (this entity is crucial part of auto-incrementing functionality) . In this case, if my app will have 20 Entities (City, Address, Hotel, User, Room, Order etc.) I will need to create a 40 classes! I am afraid, but I think it will be "Code smell". Am I right?
Also, the Entity doesn't know about EntityNameLongIdEntity and EntityNameLongIdEntity has no idea who is Entity. And only specific EntityDAO class combines ans uses those classes together. Is it ok? Or it is again code smell?
Each EntityDAO class overrides extends BasicDAO class and overrides method save(). The difference between overrided methods save() for different DAO classes is minimal. I am afraid. that is code duplication and code smell again. Am I right?
please provide your opinion.
We require numeric IDs on some entities, but our implementation is a little different:
We use a regular ObjectId on all entities. Where required, we add a numeric ID.
There is a dedicated AutoIncrementEntity, which keeps a counter for different keys — that would be your class name.
We don't use DAOs but a generic save method, where we check if we have an instance of a class with a numeric ID. If that ID hasn't been set, we fetch one and update the AutoIncrementEntity. The relevant method isn't used at the moment — let me know if it's totally unclear and I'll finish that code.
Two more things from my implementation, which might be a little confusing:
You can always provide a starting number, so our numeric IDs could be 1000, 1001, 1002,... instead of 1, 2, 3,...
The key in the AutoIncrementEntity isn't required to be a class, it could also be a subset. For example, you want to number employees within a company, then the key for employees of company A would be employee-A, for company B company-B,...
I have something like this:
and I need to know what the best practice is for "hooking up" interactivity.
On the left we have a RoleSlot, which consists of an assigned Employee, and 1-5 ProjectRole(s). If I click on one of those project roles, then we get to view its ProjectResp(onsibilities) on the right.
The question is, how should I do this?
This ProjectManager class and the RoleSlot class are in different packages.
Should I:
Set up a listener to each of those little ListViews from the ProjectManager class? That would require making the RoleSlot's private ListView accessible somehow.
Or should I make the ProjectManager implement the RoleSlotInterface and define a method like handleSelectedRole()?
Or is there another, better choice?
I'd like to know the pros and cons, if possible. Cleaner code is better code.
I would expose a read-only selectedRoleProperty() on the RoleSlot class, and a roleProperty() on the ProjectResp class. I would set up a binding between them in the ProjectManager class.
class RoleSlot {
public ReadOnlyObjectProperty<ProjectRole> selectedRoleProperty();
}
class ProjectResp {
public ObjectProperty<ProjectRole> roleProperty();
}
class ProjectManager {
private final RoleSlot roleSlot;
private final ProjectResp projectResp;
public ProjectManager() {
roleSlot = ...;
projectResp = ...;
projectResp.roleProperty().bind(roleSlot.selectedRoleProperty());
}
}
The thing is that I've been coding the following exercise and I wanted to ask you something about it:
Develop a system that meets the following requirements:
Create a test generator reminding the following functional requirements:
There are two types of questions: open and multiple choice. The first ones are textual questions that students must develop to respond. The latter are textual questions that have options for students to choose 1. Each question belongs to a topic and each topic is identified by a code and a description.
An exam has N questions and every question has an answer (entered by the student). It is important to identify the student that takes the test and the examiner (the person who assembled the exam).
In order to generate the test, the examiner must indicate the amount of questions you want for each topic. The questions are selected at random from a database of questions. The correction is made in two parts: automatic correction in multiple choice and manual correction in the open questions.
Generated tests should persist and it must be able to create a copy of each exam for each student. The student completes the test, then get the correction automatically, awaiting for manual correction by the examiner. Finally, to complete the correction, the examiner corrects the open questions.
Reports: List of exams and resolutions showing the questions and answers of each exam for each student along with it's note.
I've already coded my program, but the thing is that I have some doubts about choosing the right classes to build my project, because sometimes I can't tell if all nouns from the requirements should be classes or not, or if it just depends on the scope of the system... Reading a couple of books, I've found that we have to select only nouns that have a meaning, and for that reason we usually omit some of them.
The classes I have are the following:
public class Student {
private String name;
// methods
}
public class Exam { // the examiners create the exams
private int id;
private Examiner examiner;
private List<Question> questions = new ArrayList<Question>();
private List<Test> tests = new ArrayList<Test>();
private Map<Topic, Integer> quantityChosenPerTopic = new HashMap<Topic, Integer>();
private Map<Topic, List<Question>> questionsByTopicDisordered;
// methods
}
public class Examiner {
private String name;
// methods
}
public abstract class Question {
private Topic topic;
private String text;
// methods
}
public class OpenQuestion extends Question {
// methods
}
public class MultipleChoiceQuestion extends Question {
private List<String> options = new ArrayList<String>();
private String correct;
// methods
}
public class Test { // the students take the tests
private int number;
private Student student;
private float mark = -1;
private Map<Question, String> answers = new HashMap<Question, String>();
private Map<Question, Boolean> correction = new HashMap<Question, Boolean>();
// methods
}
public class Topic {
private int code;
private String description;
// methods
}
In the previous version of the system, I also had these classes:
public class Option {
private String option;
// methods
}
public abstract class Answer {
// methods
}
public class OpenAnswer extends Answer {
private String text;
// methods
}
public class MultipleChoiceAnswer extends Answer {
private Option option;
// methods
}
A person who helped me with this decided to take out those last classes: Option, Answer, OpenAnswer and MultipleChoiceAnswer. The reason he gave me was that it has not much sense to have them in the program because they just handle one variable and he recommended me to use them as that. And other person told me that it's important that the code works and it should be understandable by other people, plus it's not recommended to have many little classes that don't have almost nothing or very big classes with lots of code. That's why I wanted to ask you that. Thanks.
I would code it so that the resulting classes will have some behaviour, if a class consists only of information then it's better to view it as a data structure.
So, in my opinion, I would not create classes adding properties first, but their methods, by doing so you automatically exclude data structures from classes.
You said
Reading a couple of books, I've found that we have to select only nouns that have a meaning, and for that reason we usually omit some of them
...in my opinion a meaning reflect actions that could be carried out by a class, methods.