How to design an api to be called by different applications - api

Application A has an api setAge(String staffName). Application B and C both call this api.
If a staff Jack has different names in A, B, C: JackA, JackB, JackC, so how to design application A to map JackB=>JackA and JackC=>JackA?

You need to model identity in some way. If your business objects (e.g. staff members) are persisted in a relational db you can use the table's primary key, but this is a rather bad practice, as technical keys should not be relied upon on the application level. Instead use a unique business-id for your entities. That can be a String or a UUID for example. When accessing the entities in your API, clients have to pass that business-id as a parameter.
If you are in an OO language like Java, you might have to consider implementing object equality through equals and hashCode contracts (see here).

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?

Nullable GUID (Guid?) as the ID for Domain Class (NHibernate)

I am using Guid.comb for my primary key in my tables.
I never found any sample using nullable guid as the ID for the domain class; is this a bad practice with NHibernate?
The reason:
I am binding a list of POCO to combo box; without the nullable guid, I have to handle validation for Guid.Empty instead of using default build in DataAnnotations Required Validation.
Thanks you
The main reason for a primary key is that it defines a unique identifier for a particular record. If you were to be able to make your primary key nullable, then NHibernate would not be able to tell the difference between a newly created record with an empty GUID and a already existing record in your database with an empty or nullable GUID.
So yes, you do not see any examples of this because it would be a very bad practice.
In regards to your example of binding POCO's to a combo box, this is also a bad practice. Following the separation of concerns principle, you would not want to mix your UI logic with domain-specific logic such as the POCOs/entities that you are using with NHibernate to persist to the database. Typically, you would create a ViewModel class that would store whatever data is needed for the UI. You would then have a Service / Business layer which would store the business logic and handle converting/mapping your ViewModel classes to POCOs/entities/DTOs.
So in your example, if the application was following the separation of concerns principle, you would not even run into the issue you are facing because you would not be exposing the objects you wish to create/save/update using NHibernate. Separating your application in this way provides many other benefits such as not directly tying your database architecture to your UI, allowing you to easily modify the UI, Service Layer, or database without dramatically impacting any other layer, etc.

Builtin objects with NHibernate

Does anyone know of a way to mix static object instances with those managed by NHibernate. I have an application where I use the repository pattern to manage db object instances, and those instances have some complex many-many, one-many, and many-one relationships. There are some scenarios where I'd like to have a guaranteed object (like a "User" type instance of "sys_user", for example). The instance must be able to participate in relationships, and I'm willing to have a hardcoded primary key for the few objects I want.
Basically I'm looking for a way to make my repository intermingle statically defined objects into the output, so if I ask for a list of "User"s i get the static "sys_user" plus those defined in the database. Furthermore, I'd like to be able to have that "sys_user" participate in a relationship with DB objects, i.e. - MyClass("db instance").UserProperty == "sys_user" instance, as defined by a fk on the MY_CLASS db table with a special value (say -1)
In essence, this is just a way to avoid an installation time requirement of pre-loading predefined objects that the app expects into the DB, as well as preventing them from being modified after installation. I want to code some logic that relies on special instances being present, and not allow users of the app to inadvertantly break that contract.
this should be exactly the case you describe, no need for repository though, just NHibernate http://fabiomaulo.blogspot.com/2009/08/from-db-to-ram-wellknowinstancetype.html

WCF and Inheritance

I'm working on a project where I have an abstract class of Appointment. There are Workouts, Meals and Measurements that all derived from Appointment. My architecture looks like this so far:
Dao - with data access layer being entity framework 4 right now
POCO classes using the T4 templates
WCF
Silverlight Client, ASP.net MVP, mobile clients
Would I put business rules in the POCO class? or map my Entities to a business object with rules and then map those to DTOs and pass those through WCF?? and when I pass the DTOs do I pass over type Appointment? Or write a service method for each sub class like Workout or Meal?
I haven't found any good material using table per type inheritance and WCF.
thanks in advance!
-ajax
it mainly depends on complexity you require. You are using POCO classes it is good starting point. You now have to choose how complex application are you going to build, how much business logic do you want to add and what do you want to expose to your clients?
The POCO entity can be just DTO or you can turn POCO entity into business object by adding business methods and rules directly into that entity - you will transform the entity into Active record pattern or to Domain object. I don't see any reason to map your POCOs to another set of business objects.
Exposing POCO entity in WCF service is the simplest way. You can use operations which will works directly with Appointment class. Additionally you have to give your service information about all classes derived from Appointment - check KnownTypeAttribute and ServiceKnownTypeAttribute. Using entity often means that service calls transport more than is needed - this can be problem for mobile clients with slow internet connection. There is one special point you have to be aware of when exposing entity which is aggregation root (contains references to another entitities and collection of entities) - if you don't have full control over client applications and you allow clients sending full modified object graph you have to validate not only each entity but also that client changed only what he was allowed to. Example: Suppose that client want to modify Order entity. You send him Order with all OrderItem entities and each item will have reference to its Product entity = full object graph. What happens if instead of modifing Order and OrderItems client changes any of Products (for example price)? If you don't check this in your business logic exposed by WCF and pass the modified object graph into EF context, it will modify the price in your database.
If you decide to use your entities like business objects you usually don't expose those entities, instead you will create large set of DTOs. Each operation will work with precisely defined DTO for request and response. That DTO will carry only information which are really needed - this will reduce data payload for service calls and avoid passing modified prices of product, because you will simply define your DTO to not transfer price or even whole product from the client. This solution is much more time consuming to implement and it adds additional layer of complexity.
Because I have mentioned object graphs I must clarify that there is another hidden level of complexity when using them: change tracking. EF context needs to know what have changed in object graph (at least which OrderItem was modified, which was added or deleted, etc.) for correct persistence. Tracking and multi tier solution is a chalenge. The simplest solution does not track changes and instead uses additional query to EF. This query returns actual persisted state of object graph and modified object graph is merged with it (special care is needed for concurrency checks). Other solutions uses some tracking support in entity - check Tracking changes in POCO and Self-tracking entities. But this is only for entities. If you want to track changes in DTO you have to implement your own change tracking. You can also read articles from MSDN magazine about multi tier applications and EF:
Anti-Patterns To Avoid In N-Tier Applications;
Building N-Tier Apps with EF4

Beans, methods, access and change? What is the recommened practice for handling them (i.e. in ColdFusion)?

I am new to programming (6 weeks now). i am reading a lot of books, sites and blogs right now and i learn something new every day.
Right now i am using coldfusion (job). I have read many of the oop and cf related articles on the web and i am planning to get into mxunit next and after that to look at some frameworks.
One thing bothers me and i am not able to find a satisfactory answer. Beans are sometimes described as DataTransferObjects, they hold Data from one or many sources.
What is the recommended practice to handle this data?
Should i use a separate Object that reads the data, mutates it and than writes it back to the bean, so that the bean is just a storage for data (accessible through getters) or should i implement the methods to manipulate the data in the bean.
I see two options.
1. The bean is only storage, other objects have to do something with its data.
2. The bean is storage and logic, other objects tell it to do something with its data.
The second option seems to me to adhere more to encapsulation while the first seems to be the way that beans are used.
I am sure both options fit someones need and are recommended in a specific context but what is recommended in general, especially when someone does not know enough about the greater application picture and is a beginner?
Example:
I have created a bean that holds an Item from a database with the item id, a name, and an 1d-array. Every array element is a struct that holds a user with its id, its name and its amount of the item. Through a getter i output the data in a table in which i can also change the amount for each user or check a user for deletion from this item.
Where do i put the logic to handle the application users input?
Do i tell the bean to change its array according to the user input?
Or do i create an object that changes the array and writes that new array into the bean?
(All database access (CreateReadUpdateDelete) is handled through a DataAccessObject that gets the bean as an argument. The DAO also contains a gateway method to read more than one record from the database. I use this method to get a table of items, which i can click to create the bean and its data.)
You're observing something known as "anemic domain model". Yes, it's very common, and no, it's not good OO design. Generally, logic should be with the data it operates on.
However, there's also the matter of separation of concerns - you don't want to stuff everything into the domain model. For example, database access is often considered a technically separate layer and not something the domain models themselves should be doing - it seems you already have that separated. What exactly should and should not be part of the domain model depends on the concrete case - good design can't really be expressed in absolute rules.
Another concern is models that get transferred over the network, e.g. between an app server and a web frontend. You want these to contain only the data itself to reduce badnwidth usage and latency. But that doesn't mean they can't contain logic, since methods are not part of the serialized objects. Derived fields and caches are - but they can usually be marked as transient in some way so that they are not transferred.
Your bean should contain both your data and logic.
Data Transfer Objects are used to transfer objects over the network, such as from ColdFusion to a Flex application in the browser. DTOs only contain relevant fields of an object's data.
Where possible you should try to minimise exposing the internal implementation of your bean, (such as the array of user structs) to other objects. To change the array you should just call mutator functions directly on your bean, such as yourBean.addUser(user) which appends the user struct to the internal array.
No need to create a separate DAO with a composed Gateway object for your data access. Just put all of your database access methods (CRUD plus table queries) into a single Gateway object.