首页 > 代码库 > Interaction between objects

Interaction between objects

http://stackoverflow.com/questions/3744345/object-oriented-style-programming-for-interaction-between-objects?rq=1

One thing I‘ve noticed is that people that are new to OOP get caught up in trying to map the physical world into the code they are writing. Do you really care that John and Betty are people or are you actually wanting to depict a bank account? I think your choice of objects in the example actually make it harder to figure out the solution to the problem.

The important parts of this are 1) Where to put the logic of how to move the money. 2) Where to store the data of how much money each person has.

You need to decide if you want to talk about the problem in the context of a person or a customer of a bank (may be a person, company, or something else). I‘m guessing you are talking about a customer because assuming it is a person would be limiting and misleading. Also, a Bank is a pretty generic term, is it the big brick building with people inside of it or is it the online website with several different pages that do different things. A bank account object can have a method (possibly static depending on how you decide to store your data and what all you are going to use your object for) that knows how to transfer from one account to another. The logic of how to transfer does not belong to Betty or John or a bank, it belongs to a bankAccount which can have special logic based on the type of account if there are fee‘s involved or the like. If you gave that logic to the bank you would end up with a giant bank class with methods for everything from greating a customer to dealing with money in very specific account types. Each account type my have different rules for how it handles transfers. Think of times where you may want to show a transfer or deposit as pending.

If you are just solving the problem of transfering money, there is no need to create a bunch of objects. Based on the known requirements and presumed future requirements the below would be a good choice. CheckingAccount.Transfer(johnsAccountNo, bettysAccountNo, amount)

 

 

 

http://codereview.stackexchange.com/questions/63441/object-interaction-in-oop-especially-python

You should try to find a better way to decouple them. An idea cold be removing the need of keeping a list of groups in Person and a list of people in Group. You could do it by introducing a third class, let‘s call it Subscriptions, that will contain a list of subscriptions. An easy way to do that could be a (person, group) pair. That class will then offer all the methods to edit subscriptions (with a subscribe(person, group) and an unsubscribe(person, group) as well as methods to query them, like get_groups(person) or get_members(group).

Interaction between objects