How to decide methods in class - java

I am new to Object Oriented Programming. I am developing a software for a Grocery Store. The Grocery Store has Customers, Customers has Address and Subscriptions. All these are different classes in the application.
I am little confused, that in which class should I create which method and how I should decide this.
Like
viewSubscription() should be a part of Subscription class or Customer class.
modifyCustomer() should be a part of Customer class or Store class.

Methods are behavior, variables are state.
What can a subscription? from what is a suscription made?
A Suscription cant view itself, who will view a subscription? a customer?
A suscription should be a class indeed, but a POJO, its a collection of states. And customers can see those states.

One of the ideas of object oriented programming is to group things together that make sense. In your example, since they are dealing with information related to the Customer, I would probably place both methods in the Customer class.

OOP makes it easy to break down complex problems. You might want to sit down and do a schema of the relations between your classes and what data your classes will contain. It will become obvious where which method should go.
Why should view subscription should a member of Subscription?
Always ask your self this simple question: view subscriptions of what? On what do you want to do the action.
I bet you want to view the subscription of a Customer! Make viewSubscription a method of Customer! customer1.viewSubscription()
Check out UML and OCL. They will help you to model your ideas.

Just an overview: An object represents a real life entity lets say for example a car, A car has some properties like it has wheels,a steering,a gearbox and much more, the same way it has some behaviors like it moves forward, steers left, steers right and it stops.
All the things mentioned above related to the car when brought down to an Object oriented programming approach will look like, We make a class Car and the properties(wheels,a steering,a gearbox etc) are defined as variables inside that class and the behaviors(moves forward, steers left, steers right) are defined as functions in that class.There's no hard and fast rule relating OOP you just have to make it feel logically as Real Life as possible for instance in your case the Subscription Class has all the information related to the subscription and the Customer has a subscription so the viewSubscription()method should come inside Customer Class as a Private field because it should fetch and display the subscription information related to a particular customer. modifyCustomer() as it involves modifying the data fields of the Customer class so this too will come inside the customer class as all the modification of the field values should probably be done inside the class containing the fields.

Related

How to correctly call the functions of a member object inside another object

This is one of the object-oriented design questions from educative.io's OOD course. It asks us to design Amazon i.e. an online shopping system. I am thinking how to incorporate the 4th requirement into the design. Their solution is to create a ShoppingCart class and make it a field of Customer class. And it seems from the functions provided in their solution that, whenever a user wants to add an item, Customer.getShoppingCart().addItem() is called. But since Customer.getShoppingCart() is a getter function, it returns a copy of the actual shopping cart. So the item is not added to the correct List. Am I missing something here? How should we correctly delegate the additem functionality from Customer to ShoppingCart
Edit: The best solution I can think of now is make Customer extend ShoppingCart. Although this is counterintuitive, there's nothing wrong doing so.

"Container" classes, good or bad practice, why?

I'm curious as to which is the better practice and the reasoning behind it, for this example I'm going to be using a social application which contains a 'friends' and a 'ignore' list with some custom logic based on them, (For sending messages directly, etc)
Which would be the better practice, and why?
Scenario 1:
class user {
List<> friends;
List<> ignores;
...
logical methods here
}
Scenario 2:
class User {
Social social;
...
}
class Social {
List<> friends;
List<> ignores;
...
logical methods here
}
I've seen both scenarios used throughout numerous applications and I'm curious as to which is the "Correct" way to lay it out in java, these will have methods such as
#addFriend(User user)
check ignore
check valid user
check other info
add to list
end
#getFriend(int id)
find friend by id
check online status
return friend
It seems like while have a 'Social' class may be a cleaner approach, does it really follow good practices? Seems like it'd use more memory/user just for cleaner code.
The reason why you have such constructs as your Social, most of the time, is that they represent a logical set of data and operations which is needed for different entities in your application.
If nothing other than User has those properties and actions, then there is no point in doing it separately from User. But you may design it separately anyway, for future uses (for example, if you want to be able to expand it later and you believe there will be other entities which will need Social functionality).
Looking at this from an object-oriented viewpoint, it means that the Social is a type. And then you have to ask yourself, is whether your User is_a Social or whether your User has_a Social. Does it make sense to say that the user has a "social subsystem" or is the user a "social object"? If the correct relation is is_a, then User should extend Social. If not, it should have a Social member, such as you described.
However, in Java, since you can't have multiple inheritance of implementation, sometimes your type may inherit from several types, and you have to decide which of them to extend. Many times, you simulate multiple inheritance of implementation, by having a member of what should have been the "second parent class", declare all the methods in your class, and delegate them to that member.
So the general guidelines are, more or less:
If in your application's domain, the only class where it will make sense to have friends and ignores and their operations is User, and no other conceivable entity would ever need them, then implement them directly in User.
If other entities may need similar functionality, and not all of them extend User anyway, you may consider this functionality to be an entity or class in its own right, and then you should have every class which has an is_a relationship to this entity extend it.
If Java's limitations of multiple inheritance don't allow extending directly, as it makes more sense for the class to extend some other class, you should embed an object and delegate the operations.
There may be other practical reasons to separate the Social entity from User, despite User being the only class to use them. For example, if you have several different possible implementations of "social" behavior, you may want to be able to use various Social subclasses as "plug-ins" inside User, rather than subclassing User.
Don't worry about memory so early. Go for readable/cleaner code. Premature optimization is root of all evil.
This is really based on the logic of your program. But consider that increasing the number of classes unnecessarily, is not good practice.
In your example, if the User class only contains a Social field, and you will just delegate all the method calls to the Social class, then go with scenario one.
On the other hand, if the User class has many more fields, like name, date of joining ... then it would be even better to create a separate class for such fields such as UserInfo in order to better structure your program and enhance code readability.
Now the main concerns are not the memory or performance costs of class structure.
Way more important are readability and clean code, AND the possibility to persist domain classes in a DB in the most simple and efficient way.
The later include composition or aggregation concern which is specific for different DB's.
You should care about the design aspects becoz with this you will have maintainable,scalable and readable code.
Now going by your example , i find second scenario as good case as it follows the SRP(Single Responsibilty Principle)
Don't worry about memory here as it wont make iota of difference here.
So do you want to do something like:
for(Connection connection : userSocialConnections ){
sendMessageTo(connection);
}
If so, then the method sendMessageTo would need to accept a connection (friend or ignored, basically a user) and probably if the runtype connection is ignored (or has blocked the user) then the sendMessageTo will return without sending a message polymorphically. This would require that in java that the IgnoredPeople And Friends are subtypes of something called as Connection(or people or anything you like; in fact, a connection is also a user - current or potential, isn't it?). This approach seems (to me) more like thinking in problem domain. Storing as two list inside user or inside social inside user does not matter much as long as they both (ignored and friends) have a common interface.
I would ask, what all other scenarios can be there for user's friends or ignored list. Do they need to be loaded lazily or stored separately.

How can I design this concept in a object oriented manner?

I am having a bit of issues with design. Maybe I am thinking about this all wrong, but it seems that what I am designing only works well in a procedural manner.
The Game
I am working on a game, this game has about 10-20 players inside of it, and consists of 3 rounds. When players start up the game, the server loads their data from a database, stores it in a java class, and sends data that is requested to the client. Lets call this Player.java. This class is persistent in between the rounds of the game.
Every player in the game also has a role. This role changes in-between each round and I need this role to be linked with Player.java in some way. Right now I have 3 roles: Hunter, Seeker, and Spectator. Each role has the same basic things: onDeath(), onRespawn(), onKill(KillEvent event). I also need to be able to easily check what role a player is. (For example linking the roles with a enum).
The Problem
The problem I am running into now is how do I implement this in a OOP way? Originally, I had each role as a class that implements Role.java, and every time a role is created, it takes a Player in the constructor. This is all fine and dandy until I start changing people's roles in the middle of the rounds and after the end of each round. It seems like bad practice to me if I am consistently setting the players role to a new object.
Summary
To sum this up (since I am terrible at describing things), it seems like all of this would work perfectly in a procedural manner, but I can't figure out for the life of me a good way to implement this concept using OOP. The way I have it implemented now, each Player has a enum stating what role they are, and to change that role I simply change the enum in Player. With that being said though, once I get to the game logic, I end up with a TON of nested if statements, something that I feel could be greatly reduced with some polymorphism.
So to end with a question, what would be a good plan of attack to implement this (or a slightly modified version of this system) in a object oriented way without having to consistently create new objects that take in data from old objects? (I don't have a ton of experience with OOP, but to me this just seems like a bad idea)
I think I would go for this solution:
Make Player an Interface
Create a Proxy-Class for it (a class that has only one property, which is of type Player, and redirects all methods to this object). Lets call it ConcretePlayer
Add a setRole method, taking a Role to ConcretePlayer.
Make Role implement Player
Create Subclasses of Role like you did, each takes a ConcretePlayer in their constructor.
Store the stats that are shared among all Roles in the ConcretePlayer
Externally use Player or ConcretePlayer to access everything.
It's not fleshed out perfectly, but I think you get the idea. You may find that Role and Player shouldn't share the same interface, or that you want to create an own interface for the callbacks, but that depends on the rest of your code and usecases.

Storing large variety of objects with different functionalities

I'm developing a game in Java which I can only describe as a variant of The Sims.
The main interface for the game consists of a level and will have a large variety of furniture which can be placed on the map. My problem is that whilst I can think of ways to construct a system which will allow me to assign properties to each item of furniture, I want to make sure I do it the correct way before I head down a long path to completing it. For example, if I referenced an object with an identifier of "sofa", the furniture object's members could be accessed through searching through all available objects and finding the one with the matching identifier.
My method would be to make a very large .java file with instances from a base furniture class for each item of furniture, with each one having an identifier and all its different properties assigned, such as image, position, rotation etc, plus their own unique code for each different function they provide (eg. sitting, sleeping).
For saving/storing these objects in a text file, I would just store the name of the identifier in the string array in the text file and when loading, I could just create the object by instantiating the object the identifier points to.
Would I be correct in using most of these methods, or are better ones available? If you've found it a struggle to comprehend what I've written (and I had trouble writing it clearly), then a more simple question would be:
How are items of furniture managed in The Sims with respect to the sheer amount available and the many different variations/rotations they can be placed in (and stored/saved)?
I think what you need to do here is try and abstract as much of the common functionality to the base classes and then each item should extend as necessary.
Eg
A Sofa... Seat extends Furniture extends Object
A Office chair would be the same
A DiningTable would be different tho... Table extends Furniture extends Object
You will also want various Interfaces so that a Sofa implements Sittable think of the functionailty that might be common to different objects, like they might all be Placeable
Also for saving and loading you might want to make your objects serializable.
Read up on Abstraction, Interfaces and Serialization
Component-Entity-System may be a good thing for you to look into. It's basically what you're describing. There's a large collection of entities, each entity has a collection of Components, and there are systems which know what to do with certain components.
EG: A piece of furniture is an entity named "chair". It has many components, one of them is "Renderable". And your game loop passes all renderables into the "renderer" System which calls the Renderable.render() method.
Note, this isn't very object oriented, but I find it's tough to design games like this in an OO way because the object hierarchies explode. Everything has some things in common with everything else. You'd end up with generic classes like "Unit" and "Thing" which isn't very OO either.

Model shared between two objects

I have three classes interacting in an interesting way. One is a model class, and it has to be accessed by both of the other classes, so a single instance of it is kept as a member of each. Both of these classes interact with the model in different ways.
There are a couple of instances where the model object has to be completely thrown away and replaced with a new instance, and this complicates things. And these occasions arise in both of the viewing/controlling classes. So, either one of those classes has to be able to send a signal to the other saying "We need to coordinate and facilitate the replacement of our Model object with a new Model object." Right now I have code in class B to tell class A to construct a new Model and send it back, but now I need to handle the opposite situation, where the event arises in class A, and unfortunately class A does not have a reference to class B and probably shouldn't.
What's a good way to handle this?
Update: Sorry, folks, this can't be a singleton. Singletons are when you need to guarantee there's only one of something. That has nothing to do with any of the requirements I expressed above. This class is not a singleton and shouldn't be.
Update: Up till now, there has actually only been one instance of this Model class, but I had a vague suspicion I needed to allow for more, and I didn't want to limit myself by using the Singleton design pattern when that actually addresses different concerns from what I have. Turns out I was right: yesterday I received a new requirement and now I need support an arbitrary number of these. :) Don't limit yourself when you don't have to, and don't misuse design patterns for situations where they were not intended!
You'll want an intermediary model layer, a model "holder" object that each of the two classes reference. The ModelHolder holds a reference to the model.
This ModelHolder should also support listeners, so when its model is thrown out, it can notify any listeners that the model has changed.
Ok, if you need to change the model (but not force) you can make a listener interface, and make both objects A and B implement it:
public interface ModelListener {
public void modelChanged(Model newModel);
}
and at the proper time you can notify the listeners of the new model change. You can also have a list that holds all the registered listeners.
List<ModelListener> modelListeners = new ArrayList<ModelListener>();
public void setNewModel(Model m) {
for (ModelListener aListener : m.modelListeners)
aListener.modelChanged(m);
}
As always there are tradeoffs between simplicity and robustness. You might want to experiment with the levels you need for your own case.
I encounter this design issue often in GUI projects (Swing, GWT). What I usually do is create a higher-level "State" model, which holds an instance of the object that is shared between 2 or more classes. State then has a ModelListener interface, which the other classes can implement to get notification of changes to the underlying model. State.setFoo() then fires ModelChanged events to the listeners, which respond accordingly.

Categories