OOP design - creation strategies/patterns - java

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

Related

How can I get a friend to stop thinking global and start thinking relative? [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 8 years ago.
Improve this question
I have a friend who is struggling to learn OO programming (in a Computer Science class), mainly, I believe, due to the fact that he does not understand the relativity/difference between "type" and the actual "instance." It appears to be an issue in understanding how data is stored.
He knows variables, and control structures, and quite a few algorithms, but I think understanding scope and the way objects are defined in Java is confusing to him. The most confusing part is the "template" part, where the methods and variables are defined, but are "owned" by each object.
As this post kind of shows, I'm horrible at explaining this concept, even when I know I'm explaining it to people.
So what I want to know, is how can clearly explain to him instances and classes (as a type, versus the actual data). He knows the basic concept, I think, but does not fully understand the difference between type and data, and how the data is passed around.
More info:
Here's the sort of confusion he is experiencing. We're working with overriding a Critter object in GridWorld (The horribly designed AP test object thing). In any event, we are suppose to redefine some methods.
He'll end up trying to use methods as properties (quite possibly a typo, but also because stuff like GetLocation() may be confusing), or he'll try to use methods on the wrong variable, or not use the right type of variable.
The difference between "Integer nameHere" and "nameHere Integer" is confusing, I think, to him. He may try to do Integer.equals() when he should do nameHere.equals(). I show him the API, but I think it's just plaining confusing.
How do you explain the difference between type and variable, but not only that, but show how a variable can have other variables in it, how when you write
public getSomething()
{
return something;
}
You are getting specific data from the class you instantiated, oh, and by the way, it's different for every single object?
How can I get him to stop thinking "global" and start thinking "relative"? How do you explain "relative"?
I like to use TVs to explain OOP concepts. There are "TVs" as a class, but then there's your TV, in your house. It can do some things that ALL TVs can do, like show a picture, turn on and off, etc.
But it also has a locally defined scope because it is one instance of the class of TVs in the world. If you enter channel 32 on a TV in NYC you get one thing. If you do it in Bangalore, you get something else. Entering a channel is like calling the TV's setChannel(int channel) method.
It's not surprising to users of such real world objects that they work this way. My advice for this particular problem is to stop using abstract and technical language to describe the basic concepts. There are plenty of things in computer science that can't be explained using material objects in the real world, but this isn't one of them.
One can think of classes as a mould, like a mould define how a final product would look like, classes define what all data can be stored, how it can be retrieved, accessed etc.
One can put raw material in mould and get the product and start using it.
Similarly one can create an instance of Class and start using it.
Each object can hold different data (like in mould you can put green liquid, red liquid etc) but there is only a single way to access data defined my class semantics (like final shape of mould product would be identical).
Hope it helps

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).

How should I go about dividing functionality into Java classes?

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.

Why do we sometimes separate behaviour from classes in Java [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 4 years ago.
Improve this question
Its a pretty basic question but I am new to Java designing to please excuse me. :)
I want to know in which scenarios we need to separate the class behavior from the class itself.
for e.g.
If I have an class Employee, I will have some data in it like - name, age etc. Also this class will have some behavior like doWork() etc. Now in what scenario we can have data and the behavior inside once class (Employee) only and in which scenario we need to have 2 different classes for Employee data (EmployeeDTO) and behavior (EmployeeService)
Very subjective question but am looking for some inputs on a design of a small application where I am taking data from a text file. Should I put the data and behavior in different classes or same? What will be your reason to justify this decision?
PS: Any links to information on this will also be very useful :)
Thankyou
Good object-oriented design advocates that each class obey the Single Responsibility Principle. Which I can't summarize any more eloquently than the wikipedia entry:
Martin defines a responsibility as a reason to change, and concludes
that a class or module should have one, and only one, reason to
change. As an example, consider a module that compiles and prints a
report. Such a module can be changed for two reasons. First, the
content of the report can change. Second, the format of the report can
change. These two things change for very different causes; one
substantive, and one cosmetic. The single responsibility principle
says that these two aspects of the problem are really two separate
responsibilities, and should therefore be in separate classes or
modules. It would be a bad design to couple two things that change for
different reasons at different times.
If you think about it, you could jam all of your Java code into one class file, but you don't. Why? Because you want to be able to change, maintain, adapt and test it. This principle says that instead of dividing your code up arbitrarily into different modules, you should take the tact that things should be broken up by their logical responsibilities. This generally means more, small modules which we know to be easier to change, maintain, adapt and test.
I personally would recommend that you factor your code out into smaller discrete classes and combine them later if this proves to be unreasonable -- this will become obvious to you. Its much easier to combine loosely-coupled code in the future than it is to factor out tightly-coupled code.
Do the simplest thing possible. You can always make your code more generalized later and there's a good chance you won't even have to do it.
Apply YAGNI principle every time you need to make a decision. Extreme Programming wiki is also a nice reading.
Put everything into one class right now. When you see your Employee is getting too fat then you can do some refactoring - for example, move method to another class. In statically typed languages like Java it is super easy because compiler helps a lot and IDE support is great.
Reading from file, for example, looks like an obvious candidate to extract to a separate loader class. On the other hand if you have a very common format as input such as XML or JSON you could just create static method List<Employee> Employee.loadFromFile(string fileName) and implement reading logic in a couple of lines of code. It's good enough right now: simple, short and works fine.
May The Real Ultimate Programming Power be with you!
By keeping business logics out of pojo, thus making it a pure transfer object, you have the benefit of loose coupling should one day you find yourself in the situation for the need to switch from Spring framework to EJB JavaBeans.
By putting data and business logic together, it becomes a domain object. The simplest form of managed bean usage promoted in JSF2 uses the domain model whereby the "action" is fused together with form data.
If you choose the first model, you can cleanly separate concerns for designing inheritence and polymorphism for your data objects, while not being bothered if the behaviors defined are making sense, and vice versa.
You use a DTO (like the acronym suggests) when you want to move data around using the lightest weight way possible, such as over the wire to a service.
For the record
Its the classic rich domain object vs anemic domain object.
In general, if you have an UI Object or a Library Object (for example the class Date or the class TextButton), and may be some other kind of Objects then may be you can wrap all in a single Class instead of relies in different classes just for commodity to have all the attributes and methods in the same class.
However, for a classic Business Object (BO) is different. Even if you want a rich domain object, excluding some other problems that i don't want to mention at this point, is the fact that the Business Service (BS) Layer acts as a "fat burning diet plan" and it turns every rich BO into a anemic BO.
Rich BO -------> BS ----------> Anemic BO.

Splitting objects into their most fundamental parts

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.

Categories