Confusion about classes - oop

I am quite new to OOP concepts and I'm trying to create a food delivery system system, and I have different users(admin,clerks,officers) that access the system
I have customers that will be registered into the system and orders that will be placed for the customers.
Therefore I have created methods for registering customers(registerCustomer) and placing orders(placeOrder) alongside other methods. Now I am quite confused which classes these methods will go under. Should the registerCustomer go under my User class(which different users inherit from) or Customer class. Same thing about the order placement. Should I create an order class or will placeOrder go under Customer or User class

There are quite a lot of ways you could do this, and many books and online resources that can teach you about object oriented programming. In general, you want to place your methods in classes that those methods operate on, and not in classes that can't be affected by those methods. So, if only Customers can be registered, and Clerks and Officers cannot, then the registerCustomer() method should be accessible only from the Customer class and not the User class it inherits from. Similarly, if only a Customer can place an Order then that's where the placeOrder() method should be located.
However, you should also consider what other object participates in each operation. For instance, perhaps the registerCustomer() method really belongs in a FoodDeliverySystem class. For instance:
FoodDeliverySystem mySystem = new FoodDeliverySystem();
Customer myCustomer = new Customer();
Order myOrder = new Order();
mySystem.registerCustomer(myCustomer);
myCustomer.placeOrder(myOrder);

Related

Usage of domain services as data provider to entities and value objects

Let's say I have a domain which purpose is to evaluate financial instruments in a given currency. We can imagine having an abstract instrument class defined as follow:
Then we can have different implementations of the Valuate method. But in all the cases, we need to know the price of the instrument and the FxRate to apply to convert the computed value from the currency of the instrument to the currency given in parameter.
I see different possibilities here:
Instruments hold their Price as property/member and they have a
Dictionary of FxRates to perform the convertion
Prices and FxRates
are provided by external domain services (ex: PriceProvider,
FxRateConverter). And could be injected in the Valuate function as parameters from Application Service.
On my opinion the first solution doesn't seems "right".
In the second cases, I'm not sure if using a Domain Service is the correct way to go, as I read in many blogs that Domain Services should not contains private members and should be simple stateless methods. In this case we will need two domain services, once having the price for each instrument and one with all the FxRates for each currencies we may work with. Eeach service must be instanciated after having retrieved the prices and FxRates from the DB. So implementation of such services will be instanciated from the application service which should only know the interface and not the concrete class of those services.
So, what is on you opinion the correct way to go if we want to respect DDD principles?

Where to put methods that interact with multiple classes

I have a class called Contact and one called Account
and I have a method called public static Account GetAccount(Contact c) {...}
Where is the best place to put this method? What design patterns should I be looking at?
A) With the Contact class
B) With the Account class
C) Have the method accessible in both classes
D) Somewhere else?
There are probably many good answers to your question. I'll take a stab at an answer, but it will have my personal biases baked in it.
In OOP, you generally don't see globally accessible) functions, disconnected from, but available to all classes. (Static methods might be globally available, but they are still tied to a particular class). To follow up on dkatzel's answer, a common pattern is in OOP is instance manager. You have a class or instance that provides access to a a database, file store, REST service, or some other place where Contact or Account objects are saved for future use.
You might be using a persistence framework with your Python project. Maybe something like this: https://docs.djangoproject.com/en/dev/topics/db/managers/
Some persistence frameworks create handy methods instance methods like Contact.getAccount() -- send the getAccount message to a contact and the method return the associated Account object. ...Or developers can add these sorts of convenience methods themselves.
Another kind of convenience method can live on the static side of a class. For example, the Account class could have a static getAccountForContact() method that returns a particular account for a given Contact object. This method would access the instance manager and use the information in the contact object to look up the correct account.
Usually you would not add a static method to the Contact class called getAccountForContact(). Instead, you would create an instance method on Contact called getAccount(). This method could then call Account.getAccountForContact() and pass "self" in as the parameter. (Or talk to an instance manager directly).
My guiding principle is typically DRY - do not repeat yourself. I pick the option that eliminates the most copy-and-paste code.
If you define your method in this way, it's not really connected with either of your classes. You can as well put it in a Util class:
public class AccountUtil{
public static Account getAccount(Contact c){ ... }
// you can put other methods here, e.g.
public static Contact getContact(Account a){ ... }
}
This follows the pattern of grouping static functions in utility classes like Math in Java / C#.
If you would like to bound the function to a class in a clear way, consider designing your class like this:
public class Contact{
public Account getAccount(){ ... } // returns the Account of this Contact
// other methods
}
In OOP it is generally recommended that you avoid using global functions when possible. If you want a static function anyways, I'd put it in a separate class.
It depends on how the lookup from Contact to Account happens but I would vote for putting it in a new class that uses the Repository pattern.
Repository repo = ...
Account account = repo.getAccount(contact);
That way you can have multiple Repository implemtations that look up the info from a database, or an HTTP request or internal mapping etc. and you don't have to modify the code that uses the repositories.
My vote is for a new class, especially if the function returns an existing account object. That is, if you have a collection of instances of Contact and a collection of instances of Account and this function maps one to the other, use a new class to encapsulate this mapping.
Otherwise, it probably makes sense as a method on Contact if GetAccount returns a new account filled in from a template. This would hold if GetAccount is something like a factory method for the Account class, or if the Account class is just a record type (instances of which have lifetimes which are bound to instances of Contact).
The only way I see this making sense as part of Account is if it makes sense as a constructor.

Placement of service methods

Let's assume I have two service classes with the following methods:
GroupService
createGroup()
deleteGroup()
updateGroup()
findGroup()
UserService
createUser()
deleteUser()
updateUser()
findUser()
Now, I am thinking about the aesthetics of theses classes.
Imagine we want to implement a method which search for all user of a specific group.
Which service class is responsible for such a method?
I mean, the return value is a user (or maybe a collection of users) but the parameter (which means the name of the group) is a group.
So which service class is the better place to put this method in?
None of both. The method belongs in the class Group, which is returned by createGroup() and findGroup(). If only these two services are your options, though, go with the GroupService, because all arguments of GroupService get group names as arguments. It is more usual to vary the return type of methods than the argument.
I'd suggest the User Service, since you are requesting User entities. A service should shield consumers from implementation details (persistence mechanism etc), if the users were returned from the Group Service, it would require knowledge of how users are persisted.
I would create another class called "Membership" and have the methods that search for users in groups or groups a particular user belongs to. I tend to err on the side of large number of small classes rather than small number of large classes.
Depends on the way of your thinking, If you want to search on users with specific group, So in fact you want do some search on users with specific criteria, so It's better to put it in user service, but if you want to get some property from group, it's better to put it in group service, You should show what's your class signature and their responsibility.

Providing a WCF Interface to an Existing Set of Classes

I have inherited an application that is logically split into 4 tiers, but physically resides across two. The 4 logical tiers are:
asp.net website
business logic in a C# .Net assembly (referenced from website)
data access c# assembly - classes generated by codesmith tool (referenced from business logic)
sql server database
An example of the way that the website interacts with the business layer is:
Booking b = new Booking();
b.property1 = x;
b.property2 = y;
result = b.method();
ie. it sets the data on public properties of the biz class then executes a method that in-turn reads from the properties.
Unfortunately, there are lots of properties and some of these are not base types, they are other objects eg the Booking object contains collection of Vouchers objects
I need to make the tiers 2-4 available to a new user interface (a very different website that will serve in-store kiosks).
I would like to expose the business layer through WCF. I have created an IBooking interface, defined the method signatures and decorted with [OperationContract] etc. Where I'm stuck is how to manage the data. I realise that I could define a data contract to match the various public properties of the Booking object but then I would need to make significant changes to the existing website - rather than it setting the properties and calling a method withouth parameters it would need to populate an instance of the data contract and pass this as a parameter to every method call.
Could anyone advise on the best way to approach this please. I am able to make changes to the exisiting website but I'd like to keep these to a minimum.
Many thanks,
Rob.
I'd suggest the simplest means of implementing this would be to create a WCF wrapper around your existing business logic without altering your current website. This can be done without any (significant) code changes to what you already have. The 'downside', if you consider it such, is that your existing website won't use your WCF services.
You've already created an contract for the service. If you haven't already, create message contracts for the operation parameters. Then you can create your 'new' website by working with the service contract & message contracts.
Services are different to OO, in that you don't normally set properties & then call parameterless methods - instead you invoke an operation and include any relevant, required data at the same time. Your service implementation - the class that implements the IBooking contract - will do the work of
instantiating your existing classes
populating those objects
calling the parameterless methods, and
returning results.
e.g.
// contract
[OperationContract]
MyResponseMessage DoMethod(MyResultRequest requestData);
// and the implementing class (the 'service')
public MyResponseMessage DoMethod(MyResultRequest requestData)
{
MyResponseMessage responseData = new MyResponseMessage();
Booking b = new Booking();
b.property1 = requestData.X;
b.property2 = requestData.y;
responseData = b.method();
}

Does anyone have a good article or good advice for class naming for n-tier web applications?

I'm used to the layout that LLBLGen gives when it generates objects based on a database structure, which might generate the following class files for a given "User" table in the database:
/EntityClasses/UserEntity.vb
/CollectionClasses/UserCollection.vb
This provides some base functionality for data access. However, when you want to implement business logic on top of that, how are you laying things out? For example, given a table structure that might look like this:
USER
userId
firstName
lastName
username
password
lockedOut
What if you wanted to lock out a user? What code would you call from the presentation layer? Would you instantiate the UserEntity class, and do:
User = new UserEntity(userId)
User.lockedOut = true
User.Save()
Or would you create a new class, such as UserHelper (/BusinessLogic/UserHelper.cs), which might have a LockOutUser function. That would change the code to be:
UH = new UserHelper()
UH.LockOutUser(userId)
Or would you extend the base UserEntity class, and create UserEntityExt that adds the new functionality? Therefore, the code from the presentation layer might look like:
User = new UserEntityExt(userId)
User.LockOutUser()
Or... would you do something else altogether?
And what would your directory/namespace structure and file/class naming conventions be?
I think what you are looking for is a service layer which would sit on top of the domain objects. You essentially have this with your second option although I might call it UserService or UserTasks. By encapsulating this LockUser process in a single place it will be easy to change later when there might be more steps or other domain objects involved. Also, this would be the place to implement transactions when dealing with multiple database calls.