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).
Related
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.
I have been coding in java for about a year and a half, and have made some small games and programs that I think turned out very well. The problem is that I am mostly self taught and I most of my code and class structure is not organized or "correctly structured". This didn't matter to me for the smaller things I made, but if I were to take on a larger project I would want to structure it correctly and make it organized.
In a previous mini-RPG game I had
Main Class (Main loop + Main method)
Player Class (containing player position and player stats)
Engine Class (containing map and collision detection between player and map
Map Class (containing map data)
My Main class contained an instance of Player and of Engine, and Engine had an instance of Map. The problem is that Player then could't tell the Engine where it was, and the Engine couldn't adjust Player's position and stats when something happened on the Map. So I ended up having some static variables and methods in both Player and Engine to get them to communicate.
I guess my overall question is is this the correct structure of classes, and is it correct to use static methods and variables here? If not, how would you structure these classes, or would there need to be more or less classes?
My overall objective is to understand how to structure classes in this previous game so I can better structure classes in a bigger project I want to take on.
It is a rather broad question, but the general answer is no.
As a rule you shouldn't use static fields to connect instances. (There are a couple of possible exceptions, but as a rule of thumb it's a useful one.) The basic idea of OOP is that everybody has a reference to whoever they want to send messages to. So if a Player needs to tell the Engine something, it should have a reference to whichever Engine instance it belongs to. Or you can redesign your architecture so only Engine sends messages to Map and Player, it's difficult to tell without more detail about your setup whether that would be appropriate in this case.
Another piece of general advice is to try to sit down with a piece of paper, write down the name of all three of your classes and in a separate column write down all the things the system has to do. And then you should try to figure out who's responsible for what. In a good design this decision is simple, if you find yourself shoehorning different things into one class, that's a sign that you should maybe need a more detailed model with more classes.
I would also suggest you take a look at the observer pattern and the publish-subscribe pattern, as it might be what you need.
Try take take a look at some design-patterns.
Which design pattern you want to use depends on what you prefer. Some can be found here on Wikipedia.
I also take it that you are familiar with OOP? Some more general info can be found here on Wikipedia.
Looking at your specific story, I think a MVC-design would be a nice solution.
MVC meaning Model View Controller.
Here you have your Model, classes holding different forms of data.
Your Controller, controls your Model, contains all the real logic.
And your View, this is the graphic end of your application.
You'd probably want to put and instance of your player in your engine as well. That way your engine will control everything (the player and the map). Hope that helps!
From what you described there a few possible ways to handle this. One would be to use a messaging system. I would look into Java Messaging Service (JMS). Another would be to make your app event drive. Here is a neat little tutorial on how to do this using spring : https://spring.io/guides/gs/messaging-reactor/. Having said that, if your intent is get a better understanding of problem solving using Java, I would first try and mimic these two approaches on your own, without any bulky frameworks.
I'm working on a moderate-sized Java project and trying to stick to the best possible practices, so I thought I'd run a few questions by you guys. Since I currently have time, I want to do it right. My apologies in advance if this sort of question isn't appropriate for StackOverflow. Perhaps others can refer to it for stylistic advice.
I'm writing a class called LinkOpener which has one public, static method: openAgencyWindows. You feed it an (oil) well serial number and, based on the serial number, a opens regulatory website for any one of the 50 US states. I'd be doing quite a bit of scraping, and due to the labyrinthine nature of these websites the code can get pretty extensive. Should I:
Include all of my scraping code in a LinkOpener class, including methods to handle serial numbers that correspond to each state in the US (sorted alphabetically).
Give each state its own class, which would extend a Scraper class that contains a few common website scraping/regex methods. Each state class would have one to three methods to assist with scraping.
Do something else?
Any assistance would be much appreciated.
Your second alternative will be more readable and a more object-oriented approach, which is good. It is also possible to call methods in the specific classes without knowing what state it is through abstract methods in the implemented class.
For OOP practice I am working on a hobby project, a quiz program which reads a table from txt file and asks questions about entries in the table. The idea is to have this facilitate learning of the material given for a course in our dept.
So far I wrote the I/O bit, put together a pretty modest GUI and the classes to represent the different types of entities in the datatable. I am not sure about how to proceed with the core of the program though, I mean question generation and validation.
My first idea was to have a class AbstractQuestion which pretty much defines what a question is and what fields it has (a string representation, an answer and a difficulty level). Then I thought I could write classes for different types of questions, for instance one class for simple value inquiries (like giving the name of an entity and asking for a particular property), another class for more complicated questions (for instance inquiring about interactions of entities etc).
I am not sure if this is the best way to go however. Can't really express why but I have a feeling that this is not the neatest way to go about it. Would it make sense to work on a Factory class? Essentially I need to:
provide means for a question to be generated based on one, or more, entities randomly picked from the datatable
different types of questions need to be created on the runtime, based on input from the user (desired difficulty level)
questions need to be validated and the user needs to be notified by the main Quiz class (so the questions need to be accessible).
I could start simple and implement only one type of question, get it to work and add new features in time but I think it's good practice to improve my understanding of OOP, and besides I'm afraid if it works and I start giving it out for people to test it out, I'll eventually end up working on something else. I'd like to be able to conceptualize my project better, and I think this could be a good opportunity to improve that.
PS: In case it wasn't obvious, I am not a programmer by educational background :)
You could use an Abstract Factory to create factories that know how to create questions based on specific parameters.
As for the notification you could use Observer Pattern. Study them and see examples in the language of your preference
Think in terms of two things:
What objects use Question objects? What do they need Questions to do? That is we talk about the Interface(s) of the Question.
How do Questions do those things? The Behaviour of the Question.
Initially, think only about the Interfaces. I'm not clear what we need the question to do. Seems to me that a question whose answer is free-form text and a question which offers a "Pick one of A to D" and a question which asks "Pick one or more of A to D" might well loom very different in a UI. So are you thinking in terms of "Question: please display yourself, get your answer and tell me the user's score" or "Question: what is your text? Question: what kind of answer do you take? Question : what are your four options? Question: the user entered 'a' what did they score?"
Once you've got the idea of the question's responsibilities clear, then you can consider the appropriate number of different Question interfaces and classes, and hence decide whether you need a creational pattern such as Factory. Factory works well when you have a number of different classes all implementing the same interface.
Factory: go make me a question. Question: go and ask the user.
I've got simple quiz application running on production =) There are different type of questions, with different behaviours (they should be asked, answered and tipped in different fashion). Questions have different complexity etc.
In my situation, the most appropriate solution, was creation Question superclass with some abstract methods (it could be an interface as well) and different implementation. And there were QuestionGenerator (works as a factory), factory, based on some input return different implementation.
Think, about your interface (common part) of your question and use factory pattern.
There could be more complicated scenario, where you can find some advantages of using AbstractFactory or Builder patter.
In my simple case, extracting interface was enought
Not sure if the title captures what I'm trying to say here.
When designing in OO should I be splitting my objects up into their most specific areas - so if I have a factory object that deals with creating objects but later on i come across a way of creating objects for another purpose even though they may be the same objects is it worth creating a seperate fcatory or just add to the exsiting.
My biggest worry is bulking up classes with tons of stuff, or splitting objects and diluting my projects into a sea of classes.
Any help?
EDIT:
I guess on a side note/sub topic part of me wants to find out the level of granularity you should use in a program. Kind of, how low should you go?
My biggest worry is bulking up classes with tons of stuff, or
splitting objects and diluting my
projects into a sea of classes
This is a very valid point and in any even reasonably sized project, extremely difficult to get right up front especially because realistically, requirements themselves evolve over time in most cases.
This is where "Refactoring" come in. You design based on what you know at any given point and try not too make too many leaps of faith as to what you think the system MAY evolve to.
Given that you know what you are building right now, you design your classes trying to make the best possible use of OO concepts - eg encapsulation / polymorphism. This is itself, like others have noted as well, can be notoriously difficult to achieve and thats where experience, both in designing OO systems as well as knowledge of the domain can really come in handy.
Design based on what you know --> Build It --> Review it --> Refactor it --> Re-design --> and it goes on and on..
Finding the correct level of detail and responsibility is what makes OOP design so difficult. We can help you with a specific case but not with anything this general. If there were algorithms or strict methodologies of how to solve this, everyone could be an OOP designer.
A rule of thumb I like for deciding "is this getting too big now?" is "can I explain the purpose of it concisely?" If you start having to introduce caveats and lots of weasel words to explain the functions of a component of your design (be it class, member variable, method or whatever) it might be a good indicator that it's getting too complex and should be split up.
In your specific case, if you already have a factory object then the DRY Principle (Don't Repeat Yourself) would say that it's a bad idea to create another factory that does the same thing.
Is this an actual problem that you face? Or merely a fear about how your code might grow in the future?
If you are using the same type of object to solve drastically different problems then you may need to redesign the class to focus on seperation of concerns. If you need a more specific answer, you will need to provide an example of a type of class that would need this functionality.
I might have worded things badly in
the Q. I guess I wouldnt be repeating
myself its just more of a case of
where to put the code, it could be
added to an exsiting factory that
creates design objects for exporing
data to excel spreadsheets. On the
other hand I could see it could also
have its own factory for importing
excel data. Both factories would
produce the same objects but the inner
workings are completely different. –
If you aren't doing or plan on doing any class abstraction (subclassing or using interfaces) you may not need to use the factory pattern at all. The factory pattern is generally best suited for supplying objects of a base class type or that implement a specific interface.
Both
factories would produce the same
objects but the inner workings are
completely different.
Not sure if I've understood you correctly, but this sounds like a candidate for the AbstractFactory pattern.