Using two objects in the same method, what is the best implementation? - class

I am a newbie in object oriented design. While reading, a question came to my mind and I couldn't decide what design pattern to use (or should i use it at all).
For example, in the library, the due dates of the books depend on both the books and the people. If the book is rare, the due date should be less than other books, or if the person is a frequent customer, the due date should be longer. So this feature accessesing the attributes of both classes, where or how would it be more correct to add it?
I thought of different scenarios and interpreted the pros and cons as follows:
Creating an interface named due date and ensuring that both classes (Book and Customer) implement it. But where can I merge two dates like this? For example, if the due date for the book is 2 weeks and 1 week is added due to the customer's characteristics, where should the result of 3 weeks appear?
Creating a separate class and sending instances of two objects as parameters to a method. In this case, creating a new class for each feature to be added (due date calculation in this example) seems to be a very tedious task.

You can try this,
Here I have created a method in class Book that calculates total due date for a book based on book due date and customer due date.
class Customer:
def __init__(self):
self.due_date = 1 #week
class Book:
def __init__(self):
self.due_date = 2 #weeks
self.customer = Customer()
def due_date_of_the_book(self):
var = self.due_date + self.customer.due_date
print(var)
obj = Book()
obj.due_date_of_the_book()
=> 3

Related

How to handle static data in ES/CQRS?

After reading dozens of articles and watching hours of videos, I don't seem to get an answer to a simple question:
Should static data be included in the events of the write/read models?
Let's take the oh-so-common "orders" example.
In all examples you'll likely see something like:
class OrderCreated(Event):
....
class LineAdded(Event):
itemID
itemCount
itemPrice
But in practice, you will also have lots of "static" data (products, locations, categories, vendors, etc).
For example, we have a STATIC products table, with their SKUs, description, etc. But in all examples, the STATIC data is never part of the event.
What I don't understand is this:
Command side: should the STATIC data be included in the event? If so, which data? Should the entire "product" record be included? But a product also has a category and a vendor. Should their data be in the event as well?
Query side: should the STATIC data be included in the model/view? Or can/should it be JOINED with the static table when an actual query is executed.
If static data is NOT part of the event, then the projector cannot add it to the read model, which implies that the query MUST use joins.
If static data IS part of the event, then let's say we change something in the products table (e.g. typo in the item description), this change will not be reflected in the read model.
So, what's the right approach to using static data with ES/CQRS?
Should static data be included in the events of the write/read models?
"It depends".
First thing to note is that ES/CQRS are a distraction from this question.
CQRS is simply the creation of two objects where there was previously only one. -- Greg Young
In other words, CQRS is a response to the idea that we want to make different trade offs when reading information out of a system than when writing information into the system.
Similarly, ES just means that the data model should be an append only sequence of immutable documents that describe changes of information.
Storing snapshots of your domain entities (be that a single document in a document store, or rows in a relational database, or whatever) has to solve the same problems with "static" data.
For data that is truly immutable (the ratio of a circle's circumference and diameter is the same today as it was a billion years ago), pretty much anything works.
When you are dealing with information that changes over time, you need to be aware of the fact that that the answer changes depending on when you ask it.
Consider:
Monday: we accept an order from a customer
Tuesday: we update the prices in the product catalog
Wednesday: we invoice the customer
Thursday: we update the prices in the product catalog
Friday: we print a report for this order
What price should appear in the report? Does the answer change if the revised prices went down rather than up?
Recommended reading: Helland 2015
Roughly, if you are going to need now's information later, then you need to either (a) write the information down now or (b) write down the information you'll need later to look up now's information (ex: id + timestamp).
Furthermore, in a distributed system, you'll need to think about the implications when part of the system is unavailable (ex: what happens if we are trying to invoice, but the product catalog is unavailable? can we cache the data ahead of time?)
Sometimes, this sort of thing can turn into a complete tangle until you discover that you are missing some domain concept (the invoice depends on a price from a quote, not the catalog price) or that you have your service boundaries drawn incorrectly (Udi Dahan talks about this often).
So the "easy" part of the answer is that you should expect time to be a concept you model in your solution. After that, it gets context sensitive very quickly, and discovering the "right" answer may involve investigating subtle questions.

Choosing between Class and Struct

I am an aspiring iOS developer with not much experience except 3 months of courses on threehouse.
I decided to make an app (just for fun) that counts the calories within your salad.
I have constructed a very rough model which uses a class Vegetable and I inherit different classes for each vegetable, however this is clearly wrong and I could see it from the first 10 minutes. Now I am wondering if my approach wouldn't be better with just using a Struct named Produse and instantiate from there every ingredient since most of the ingredients in the salad are the same and I am only interested in the properties name: String, type:ProduceType (an enum), caloriesPerHundredGrams: Double. All of these member values are essentially the same for fruits, vegetables and spices.
Any suggestions?
P.S. I don't know how to retrieve data from the web yet and I intend for this exercise to have all of my ingredients hardcoded. I will use a server as a backend once I learn that!

How to share state between Akka actors?

I have a BalanceSheetActor defined as follows:
class BalanceSheetActor extends Actor {
val tradables = mutable.Set[Contract]
}
and I have some simple DepositContract defined as follows:
case class DepositContract(faceValue: Double)
Each contract in my model is an asset for one BalanceSheetActor and a liability for another BalanceSheetActor and thus the state of any Contract will be shared between actors (i.e., each contract will be a member of at least two sets of tradables).
Suppose that I want to increment the faceValue of the DepositContract by some amount. I would either need to...
remove the old contract from both sets of tradables and replace it with a new DepositContract(faceValue + amount).
model each Contract as an akka.Agent.
model each Contract as an akka.Actor (and thus encapsulating the state).
Option 1 seems needlessly complicated (additionally contracts are highly likely to get out of sync), option 2 seems OK but I will need to create on the order of millions of contract agents and am concerned about memory usage. I have similar concerns for option 3 as well. I have no idea if these memory usage concerns are well founded. Thoughts?
I am hoping that there is an option 4 that this Scala/Akka noob has not thought of...

MongoDB model design for meteorjs app

I'm more used to a relational database and am having a hard time thinking about how to design my database in mongoDB, and am even more unclear when taking into account some of the special considerations of database design for meteorjs, where I understand you often prefer separate collections over embedded documents/data in order to make better use of some of the benefits you get from collections.
Let's say I want to track students progress in high school. They need to complete certain required classes each school year in order to progress to the next year (freshman, sophomore, junior, senior), and they can also complete some electives. I need to track when the students complete each requirement or elective. And the requirements may change slightly from year to year, but I need to remember for example that Johnny completed all of the freshman requirements as they existed two years ago.
So I have:
Students
Requirements
Electives
Grades (frosh, etc.)
Years
Mostly, I'm trying to think about how to set up the requirements. In a relational DB, I'd have a table of requirements, with className, grade, and year, and a table of student_requirements, that tracks the students as they complete each requirement. But I'm thinking in MongoDB/meteorjs, I'd have a model for each grade/level that gets stored with a studentID and initially instantiates with false values for each requirement, like:
{
student: [studentID],
class: 'freshman'
year: 2014,
requirements: {
class1: false,
class2: false
}
}
and as the student completes a requirement, it updates like:
{
student: [studentID],
class: 'freshman'
year: 2014,
requirements: {
class1: false,
class2: [completionDateTime]
}
}
So in this way, each student will collect four Requirements documents, which are somewhat dictated by their initial instantiation values. And instead of the actual requirements for each grade/year living in the database, they would essentially live in the code itself.
Some of the actions I would like to be able to support are marking off requirements across a set of students at one time, and showing a grid of users/requirements to see who needs what.
Does this sound reasonable? Or is there a better way to approach this? I'm pretty early in this application and am hoping to avoid painting myself into a corner. Any help suggestion is appreciated. Thanks! :-)
Currently I'm thinking about my application data design too. I've read the examples in the MongoDB manual
look up MongoDB manual data model design - docs.mongodb.org/manual/core/data-model-design/
and here -> MongoDB manual one to one relationship - docs.mongodb.org/manual/tutorial/model-embedded-one-to-one-relationships-between-documents/
(sorry I can't post more than one link at the moment in an answer)
They say:
In general, use embedded data models when:
you have “contains” relationships between entities.
you have one-to-many relationships between entities. In these relationships the “many” or child documents always appear with or are viewed in the context of the “one” or parent documents.
The normalized approach uses a reference in a document, to another document. Just like in the Meteor.js book. They create a web app which shows posts, and each post has a set of comments. They use two collections, the posts and the comments. When adding a comment it's submitted together with the post_id.
So in your example you have a students collection. And each student has to fulfill requirements? And each student has his own requirements like a post has his own comments?
Then I would handle it like they did in the book. With two collections. I think that should be the normalized approach, not the embedded.
I'm a little confused myself, so maybe you can tell me, if my answer makes sense.
Maybe you can help me too? I'm trying to make a app that manages a flea market.
Users of the app create events.
The creator of the event invites users to be cashiers for that event.
Users create lists of stuff they want to sell. Max. number of lists/sellers per event. Max. number of position on a list (25/50).
Cashiers type in the positions of those lists at the event, to track what is sold.
Event creators make billings for the sold stuff of each list, to hand out the money afterwards.
I'm confused how to set up the data design. I need Events and Lists. Do I use the normalized approach, or the embedded one?
Edit:
After reading percona.com/blog/2013/08/01/schema-design-in-mongodb-vs-schema-design-in-mysql/ I found following advice:
If you read people information 99% of the time, having 2 separate collections can be a good solution: it avoids keeping in memory data is almost never used (passport information) and when you need to have all information for a given person, it may be acceptable to do the join in the application.
Same thing if you want to display the name of people on one screen and the passport information on another screen.
But if you want to display all information for a given person, storing everything in the same collection (with embedding or with a flat structure) is likely to be the best solution

Help design a class diagram of a booking system

I got a request from my friend to write a php booking system module for his bowling club website, I am thinking to make this module as generic as possible, ie can also be used for booking pool tables etc.
So I started to draw up my UML class diagram:
I have 2 interfaces IBookingHandler(has implementation like BowlingBookingHandler) to handle different types of bookings and IPriceOption(has implementation like BowlingNormalPrice) to handle different types of prices. IBookingHandler uses IPriceOption to generate the total cost of the booking.
A data class "Booking" which represent a booking record in object
A ata parent data class "Type" and subclass "Lane" which has methods like etCurrentStock" to get instances of types for the booking.
Could anyone please review this design, and let me know what things are wrong or missing?
Much appreciated.
James Lin
You probably want a separate class for the customer. One customer could possibly have multiple bookings.
Is it wise to ha a implemenation for normal price? what's normal price? what if they want senior price during weekdays and disco bowling price during the evenening, and on new years eve they want another price. You don't want to release a new version everytime the price changes.
If you want to connect it to the bowling lane system ( there are plenty of them on the market) you probably want to have knowledge of all the players not just the one making the booking.
The more customer info you collect the better for your friend. Since he then have a cheap and easy way of advertising.