How to architecture dynamic domain model java web app - java

Domain model are
Event (Fun, Sports, Quiz ) has many Problems (Fun problems, Sports, Quiz related problems).
Problem has many solutions (each team uploads a solution), solution has many grade (each Judge posts grade).
Initial goal is to start with one type of event (for example Quiz event) and it has multiple problems and solutions. Judge can grade the solutions.
In future there may be new type of event (Spots event) can come in with different properties & behaviours. For the sports event, problem may have new set of properties & behaviours and solution module should be disabled because for sports event judge can directly update grade.
So do i need to have workflow for each event, to turn on & off a particular module.
want to do as micro services with spring boot with mongodb.
What i done so far
I have
abstract class for Event, Problem, Solution and grade (Based on the event type grading property may change).
Registration domain with Team, Problem and solution as reference property.
How to proceed further and am i do it current ?

I think you can start by modeling an scalable design. In my opinion the starting point is correct as you have to distinguish between Events, Problems, Solutions, Teams and Judges.
Once this is done, I always try to make things as much generic as I can, so when I start to mix all the pieces they can interact independently of their real state. This is, I try to make the interaction between the pieces just by using their interfaces / abstract classes (One problem -> Many Solutions, One Team -> One Solution, etc). I see no information about those properties you talk about, but I suposse they can belong to the generic Problem and just be configured on each specific type of Problem (but not declared).
If you are able to achieve this, you can then create an enumeration for the types (Fun, Sports, Quiz, Spots) so you can configure each type of problem by the relationship Problem-Type.
I don't know how to represent the Problems as I have not enough information on your domain. But what I would do is something like this, so when new types of problems appear in the future I only have to create a new type enumeration value and its relationships:
Undertand it just as an example for making easier for you to understand my words, it's quite far from what the real design would be as I have not enough information about each piece on the puzzle.
Even though, with that as an starting point you can choose to apply some interesting design patterns such as Abstract Factory (if you want to supply the solution as a template for a given problem, so teams have to fill it instead of creating it from scratch) or Strategy Pattern (so you can interact the same way with each Problem and let the behaviour be controlled depending on the ProblemType or any other variable that determines the Problem state).
As a summary:
Try to extract the common factor of each part and how it itneracts with other ones.
Additionally, try to make interaction independently of particular types and properties, exposing as much as you can in the common interfaces (as long as it makes sense, obviously).
If not possible, Abstract Factory is an option, so it lets you make internal relationships aware of implementation details without coupling the external parts.
Once you do that you will be one step closer to making a dynamic model that grows with no efforts meeting your needs.

Related

Correct way to do a use case diagram with different user types

I am doing an android application that has two types of users, doctors and patients.
For the most part they do the same thing but in certain activities they do different things.
For example, in the calendar activity, the doctor fills out available appointment times they have, whereas the patient fills out their medications in their calendar.
In my use case diagram I have put the steps each user type takes in separate sections. Is this the correct way to do it or should I just do one section that has one actor called 'user' that outlines the generic tasks they share.
Click here to see my use case diagram
Any feedback is greatly appreciated
Your diagram seems more like a workflow, not a Use Case. Use Cases are at a very high level of abstraction. Also, they are purely Functional decompositions of the application, where you should avoid making premature design decisions. A Use Case shows the different actors that are involved and the actions they want to perform. Making them takes a systematic approach to ensure no bits of functionality are missed.
Important elements in a Use Case Diagram are:
The various actors using the application, including those responsible for the 'backend' and maintenance.
What the actors actually want to accomplish as the main Use Cases.
All derived Use Cases that are necessary to implement the main Uses Cases. I prefer the <<includes>> relationship to show this. There may be several levels of derived Use Cases.
The re-use of Use Cases between various other Use Cases.
You should avoid:
OO-type inheritance and other OO relationships. These will cause you to make premature design decisions.
Workflow. Use Cases are independent of how the actor triggers them. Workflow is actually a design decision, to be made long after Use Case analysis.
Blocks that don't actually do anything, like your 'Home' blocks. Use Cases are functional blocks, you must be able to define what information goes in, what information goes out, and what transformations it performs.
To fix your diagram, you should focus on the core functions the users want to perform. For the patient, that would be e.g. "Book Appointment", "Edit Medicine Schedule" and "Communicate with Doctor". Then you should break these up into smaller use cases using <<include>>. For example, the "Book Appointment" use case should include showing the calendar and choosing a day.
Have fun!

Modelling event type objects

We have an application that is composed of a number of independent components and sub-systems. We are looking at implementing a simple event logging mechanism where these components & sub-systems can log some events of interest. Events could be something like
New account created
Flight arrived
Weekly report dispatched to management etc.
As you can see, the event types are heterogeneous in nature and the attributes that needs to be logged differs based on the event types. New account created event, for example, will also log the account-id, the name of the user who created the new account etc. Whereas, the flight arrived event will be logging the flight number, arrived at, arrived from etc.
I'm wondering what is the good way of modelling the event types and the attributes.
One option is to do it object oriented way - to have an AbstractEvent that will have some common attributes (timestamp, message etc) and then create a full hierarchy of classes underneath. The flight events, for example, can look like
abstract class AbstractEvent;
abstract class FlightEvent extends AbstractEvent;
class FlightArrivedEvent extends FlightEvent;
class FlightCancelledEvent extends FlightEvent;
The problem I see with this approch is that we have hundreds of events which will result in class explosion. Also, whenever we add a new event (very likely), we have to create a class and distribute the new package to all the components and sub-systems.
The second option I can think of is on the other end of the spectrum. Have a simple Event class that contains the basic attributes and wrap a map inside it so that the clients can populate any data they want. The code in that case will look something like this.
class Event {
private timestamp;
private eventType;
private Map attributes;
public Event ( String eventType ) {
timestamp = System.nanoTime();
this.eventType = eventType;
attributes = new HashMap();
}
public Event add ( String key, String value ) {
attributes.put ( key, value );
return this;
}
}
//Client code.
Event e = new Event("FlightEvent:FlightArrived")
.add("FLIGHT_NUMBER", "ABC123")
.add("ARRIVED_AT", "12:34");
While this is flexible, it suffers from inconsitency. Two components can log the FLIGHT_NUMBER key in two different formats (FLIGHT_NUMBER & FLGT_NO) and I can't think of a good way to enforce some convention.
Any one have some suggestions that can provide a nice compromise between these two extreme options?
There is a Java event framework (see java.util.EventObject and the Beans framework) but the fundamental question you are asking is not connected with events. It is a design question, and it is this: do I use Java classes in my application to represent classes in my business domain?
It is clear that the different types of event are different "classes" of thing, but for maintainability reasons you are considering representing your business data in a map so that you don't have to write and distribute an actual class. If you take this to a logical extreme, you could design your whole application with no classes and just use maps and name-value pairs for everything - not just events. It would be a mess and you would be debugging it forever because you would have no type-safety whatsoever. The only way of finding what was in map would be to look up in some documentation somewhere what someone might have added to it and what type that object might be.
So, here is the thing - you would not have actually have gotten rid of your class definition.
You will have moved it into a Word document somewhere that people will have to refer to in order to understand what is in your map. The Word document will need to be maintained, verified and distributed but unlike the Java class, it won't be checked by the compiler and there is no guarantee that the programmers will interpret it correctly.
So I would say, if there is a class, put it in your code and then focus on solving the problems of distributing and versioning the Java classes instead of distributing and versioning Word documents.
I will mention versioning again as this is an issue if you might serialise the objects and restore them, so you need to think about that.
Some caveats:
If you are writing a piece of middleware software that routes events from one system to another system, it might be you don't need to know are care what the data is, and it might make sense to use a generic holder in this case. If you don't need to look at the data, you don't need a class for it.
You might get complaints from high-level designers and architects about the number of classes and the work they have to do in defining them compared with a map and name/value stuff. This is because putting classes (i.e., the real design) in Java is harder than putting them in a Word document. Easier, if you are high-level hand-waving type guy, to write something wishy-washy in Word that doesn't need to run or even compile and then give the real design work to the programmers to get working.
Can [someone] provide a nice compromise between these two extreme options?
No. There is no generic one-size-fits-all answer to this problem. You will have to find yourself a balance which fits the general design of your product. If you nail everything down, you will need thousands of classes. If you give a lot of leeway, you can get away with a few but you're paying your freedom with precision. See my blog post "Designing a Garbage Bin"
Do you have shared attributes? As in: Do you expect to define attributes of events like you define classes right now with very tight-fitting semantics?
That would mean you have a simple event and typed attributes (i.e. String value simply isn't sufficient). You need formatting and validation for attributes or ... attributes themselves need to be classes.
If this is the case, you can use my type-safe map pattern: http://blog.pdark.de/2010/05/28/type-safe-object-map/
Event type "explosion" is not a problem. In fact it is a desirable approach as it allows the components to be independent of one another. I wouldn't necessarily make all events inherit from a single superclass unless it gives you a lot of reusable code because it can cause dependencies to start proliferating.
I would put the event types in a separate project that will be a dependency of both the publisher and consumer.
What is your communication mechanism for these events between components? JMS? If so you could also consider making your messages XML and using JAXB.
I would definitely discount the map approach as it destroys any hope of polymorphism or any other oo niceties.

Elegant code when there are many subclasses?

I have an interesting programming problem that has had me stumped for days. Some context to aid my questions:
Currently I am writing a game that uses a Material Emum to hold all the materials needed in the game ie Material.DIRT, Material.WATER, Material.CLOTH ...
However I wish to make the code as modifiable as possible and have the ability that should someone want to extend the game to add new materials they can do so. Thus my current Enum system breaks down and so I have attempted to switch to a Class/Subclass system. I have found two ways to do this, they are explained below with their pros and cons.
Case 1 - Having an abstract Material class and subclassing.
Thus every material would extend Material. This is advantageous as we can now "group" like materials together ie Fabric could extend Material and then Wool and Cotton etc extend this. The problem with this is that for every material there has to exist a class and with so little parameters for each material it feels like a waste. If there is 1000 materials there would be 1000 classes all with virtually nothing in them. I could cut this down by having anonymous classes but now the code has no way to differentiate one material from the other. I could use an id system which is the major problem with case 2.
The question for case 1 is:
Is there a more elegant way of doing this?
Case 2 - Having a single Material class and instantiating each new material as an instance of this class defining each material with a different id/name. This saves a lot of writing and also allows us to differentiate between materials. The problem with this is now we have an id system, what do we base this system on? Strings, ints? I ask this because I am always keen to have a complex free system that avoids using hardcoded strings and ints in the code. This is why I like the enums as there is no worry of typesetting. Another problem is users wanting to add new materials could have conflicting ids with other users.
My question for case 2 is:
Is there a full proof method of being able to differentiate instances uniquely and consistently (is the same every runtime)?
Thank you for reading. Any help or methods on how best to do this would be most appreciated.
Edit: I should note that some materials may have methods and behaviours associated with them. Some behaviours may be unique to certain materials and some that are similar for a "group".
Use a configuration file with all the materials in it, written in some DSL (simple table, basically).

Inheritance/Interface design of a game

I'm designing a game, but I can't quite get my head around the inheritance structure. I'm normally fairly good at it, but this one just has too much overlap and I can't decide on it all.
I'm seeking to model sailing vessels - think the Age of Sail. Presumably therefore everything extends a Vessel class.
There are then several types of vessel style: rowed (galleys, canoes), square-rig, fore-and-aft rig, with different behaviour. Each of these is further subdivided into several other types. I can't decide whether this should be a series of interfaces or extensions of Vessel. Note also that there can be some cross over (a vessel can be both rowed and square rigged) which leads me to think interfaces?
Ships also have different behaviours: merchant vessels, men of war, privateer, pirates. I really can't work out whether this should be an interface or an extension of another class. There is no crossover of type in this case, however.
Finally there are several behaviours which individual ships can have. Merchants may be in a convoy (defend themselves) or independent (run away). Men of war almost always attack unless heavily outgunned... but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs. I'm assuming that this should be an interface too?
My big problem is that each style of ship (frigate, battleship etc) can fulfil almost any of these roles, so I can't build a simple solid inheritance structure. Frigate can't extend man-o-war because some are privateers. Sloop can't extend square rigged because some are fore and aft rigged. etcetc.
Any thoughts would be appreciated, I'm at a bit of a loose end.
Thanks
Make the "behavior" part as interfaces. That will help you assigning different behaviors to different ships without problem. Strategy Pattern is helpful here. In a nutshell, it states that the changeable and the constant properties should be separated.
For different means of movements, composition sounds like the most suitable answer at this moment.
Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need.
This might help you:
"There are then several types of vessel style:..." is specifying different possible behaviors. So "Movable" interface and its subclasses are for that. In the "Vessel" class, you can have a member of type "Movable". Since "Movable" is an interface, any class which implements it, is assignable to this member. So any subclass of Vessel can have any possible behavior, which we cna change at runtime as well. You can also make it an ArrayList. (Not sure if you actually want to do it or not). But if you need multiple different behaviors for a same vessel, you can do it.
When you say "Ships also have different behaviours:..." it feels like separate classes extending Vessel will satisfy this requirement. The sentence "There is no crossover of type in this case, however." makes life easier.
For the nest para "Finally there are several behaviours which individual ships can have...", you should add one more member for different possible behaviors. It will mostly be an ArrayList as one vessel will have multiple attack modes.
Fro the last para, if you can give some more details, I may be able to give some more ideas.
Ok, here are some ideas:
Vessels have one or more means of propulsion (oars, sails, etc.), which you can model by composition (e.g. have a list of propulsion methods).
Vessels use one of a variety of strategies (use the strategy pattern -- see http://en.wikipedia.org/wiki/Strategy_pattern -- for this)
Strategies which depend on the presence of other nearby ships will need some way of querying for those other ships -- so you'll need some sort of data structure that allows you to find which objects are near which other objects (look into the sort of data structures that are used for broad-phase collision detection)
As an alternative to the strategy pattern, you could switch to using a component-based design. In this setup, a vessel would be composed of one or more propulsion components, a strategy component, etc. You could then combine individual components as you see fit to make different vessels.
As an extra bonus, component-based designs are very helpful if you want your game to be data-driven, because you can just write a saver/loader for each different type of component, rather than for each possible type of vessel.
You might want to see here if you're interested in this sort of approach:
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
I want to provide a bit of advice based on the second paragraph of Bhusan's answer, which I quote here in full:
"Regarding the "but may work in fleets, squadrons or independently. Privateers and pirates only attack if weaker - usually independently but occasionally in pairs." part, I guess this has nothing to do with the inheritance tree. You can make "groups" of classes depending up on your need."
This leads me to believe that you additionally may want to consider the Composite pattern for certain groups of ships, at least those that are comprised of ships that all share the same behavior. See http://en.wikipedia.org/wiki/Composite_pattern where it is written that "the composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object."
For instance you say "Merchants may be in a convoy (defend themselves)", but presumably they can defend themselves individually as well? This is all easier said than done of course, and my advice to you is to not over-think it and start with a very small subset of what you want to do as a protoype
You should separate the types and use the strategy pattern.
Immutable properties should be bound to the inheritance tree (e.g. a frigate won't turn into canoe, these are exact, non-behavioral types, inheriting from vessel) and everything that may change should be stored as references to behavioral types which are intrachangable. (Man-o-war is a behavioral type)
AI should be handled separately, for instance with states, but that is also have to be in a different module in your architecture.
Instead of thinking about it as strictly inheritance, I think you need to think about object Composition and how that can help make things easier.
For example: a Ship has a Behaviour. (Composition... the ship delegates to the behaviour to determine how to react to X situation)
A Pirate is a Behaviour (Inheritance from a Behaviour interface)...
You should not extend the Vessel class. Rather, a Vessel object should contain other objects that describe it. (This is known as Dependency Injection, to be annoyingly pedantic--forget I said that.) You have a Propulsion class, with instances for square-sails, fore-and-aft, and oars. You might want special instances of each for big and small hulls. You have a Behavior class to handle their attitude. Sometimes a simple integer works as well as a class. Your Armament class could be, instead, just a number of guns. (Or two numbers, one for poundage.) If you expect to ram, or have a ship loaded with rockets, or need to distinguish between long guns and carronades, you might need to go back to using the a class.
This lets you switch characteristics on the fly if you want--though you probably don't. Still, you can go from sail to using sweeps, or switch bold ship-of-the-line behavior with save-the-cargo behavior of a merchant to implement a captain losing his nerve. Anyway, it's there if you need it.

How do you structure a java program? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.
The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:
should I have a separate class listening for mouse clicks?
When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?
I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.
What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.
Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.
The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.
Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.
Good luck!
One main principle of good software development is the Single Responsibility Priciple. It states that a function or class should only have one responsibility.
This way your classes and objects shouldn't become too big and unmanageable.
I think one of the most important concepts to master when developing software is the concept or Orthogonality. It's not the simplest definition, but in essence it means that one component (such as reading mouse clicks) shouldn't be directly tied to an unrelated component (moving a square on the screen).
In your case, the code reading mouse clicks should be separate from the code that actually moves the box. Whether you implement this as inner/anonymous classes or not is up to you. But if you follow the Orthogonality principle, it will be easy to change at a later date should you change your mind.
One problem here is that all the rules have some leeway in them where you have to use your own best judgement.
For example, the app you are describing now seems to me so simple I'd probably do it in a single class, with perhaps a couple of nested, perhaps anonymous classes. In any event, I could make a decent case for fitting the whole thing into a single source file, claiming that multiple source files would actually increase the complexity of the whole thing.
But if your GUI had a number of different controls, perhaps each controlling different behavior, it would become time to split the functionality up so you're not ending up with a big bowl of spaghetti code.
The Java GUI libraries try to naturally separate (view+controller) from model. You are encouraged to define and display the GUI in one module (= file) but to have your data model and perhaps functionality in another. For complicated GUIs, there may also be multiple GUI implementation modules held together by code.
One way to keep things "clean" is to work in "layers" where each layer "knows" only what it needs to know. To be specific, the GUI layer needs to know about the existence of its underlying models – tables and lists and whatnot need to be connected to TableModels and ListModels, etc. It doesn't need to know about details of these models though, so it can simply refer to those models by interface.
The model layer, on the other hand, need know nothing about the GUI. The less it knows, the better, and this would theoretically enable you to exchange GUIs without needing to touch the models.
My model can also contain ActionListeners to respond to actions undertaken by e.g. pushing buttons in the GUI.
Of course, actions and changes to the model will often result in changes to the GUI. How to communicate these changes to the GUI if the model layer doesn't know about the GUI? You can use bound bean properties here. Here's a short tutorial: http://www.javalobby.org/java/forums/t19476.html . So you have the same kind of structure: Changes happen in your model, they're communicated to beans with property change support within the model, and the GUI can attach listeners to those properties to find out something changed.
Whether you perform actual, effective actions (e.g. writing files, converting data, whatever) within your model code or whether you split "processing" code off into yet another module is up to you and will again depend on how cluttered your model already is. If there's a tiny handful of fields and methods feeling lonely in there, you may decide to mash things together but the moment it starts to look messy you'll want to refactor your processing code out into its own module. Processing sounds like the kind of module that doesn't want to know about other modules either; you may end up just calling its methods from the model level.
I've described my basic style for doing GUI development. There are certainly other recommendations out there, and you will likely develop your own style based on your experience. This is just intended to give you an idea and a possible starting point.
Step 1 - find the demo applets supplied by Sun. http://java.sun.com/applets/jdk/
Step 2 - read those demo applets. At least three. Preferably all of them.
One you've read several applets, you should see a little more clearly how to organize programs. You can then ask questions with a lot more focus pointing to specific applet examples and your specific programming problem.
Yeah, I'm a beginner programmer myself. Yeah, segregating functionality across multiple classes is a good way to reduce complexity and increase cohesion of individual classes.
Increasing cohesion good because by having more complex data structure your algorithms become less complex and your code is less dependent on each other.
For instance in your case it might be a good idea to separate the classes in accordance to MVC (Model View Controler).
You have a Model which represents the way your game data is structured.
You have a Viewer which present your Model in what ever form you please.
Have a Controller which picks up changes in the Model (via Listeners) and then updates the Viewer
Now you can change your Model and add extra functionality requiring only small changes in the way the Viewer works.
There are many Patterns out there but there isn't a hard rule when to use one over the other. There are some cases in which you can use several and there are cases in which will require you to chose one design pattern over the other.
Every beginning Java programmer should start with the Sun Tutorials. They are quite good.
Another good source, especially among free sources, is Bruce Eckel's "Thinking in Java", available from http://www.mindview.net/Books/TIJ/.
But the latter is a little dated compared to the former. That is why I recommend both.

Categories