Class that represents parts of another object? - vb.net

I have a class called "EntryData" with a couple of fields in it, "name", "entrydate", "enteredby" and "key" a foreign key. The key points to the "DataEntered" class with "key", "startdate", "enddate" and "values", an array of doubles. This matched the layout of a db we were using, which stored data in two tables.
Now we are adapting this to a db that stores all the same data, but in a single table. We would like the API to remain the same.
So, I hope this makes sense:
Can I make a new class called "DataEntered" that has no instances its own, and consists solely of pointers to particular fields in "EntryData"? That is, there would be no objects of this class, it would simply be a sort of wrapper that always referred to the underlying EntryData it was called on, like this…
myEntryDataInstance.DataEntered.startdate
In this case there is no instance of DataEntered.
The easy way to solve my problem would be if I could put periods in my method names, but that doesn't seem to work. :-)

What your asking for is called inheritance but VB does not allow you to inherit from multiple classes. You would have to inherit from one class and then write in pointers to the second class which would have to be saved as a variable in your class.
Problem is, what do you plan to do with this? Are you using the Entity Framework or your own homebrewed data manager? If you are using something gereric, it won't know how to handle you NEW class with multiple tables.

Related

UML composition attributes not feature in the class?

I have a class A and it has data members of class B and class C which are composition relationships. As I am going to draw a composition relationship line from B to A and C to A, does this mean I cannot also include the data members within the class A "box" because the relationship is inferred from the composition relationship lines?
I ask because the data member variable names seem a good way to help understand the context and this cannot be represented if you omit the data members from the class A "box"??
I am not sure if there is a cast-iron rule in UML or whether I am free to choose. This is not for auto-generation of code- just human reading.
At least, in UML you can show a name of each property like a figure below.
According to UML specification, both representations of data members, visually depicted association/composition between two classes or in-class data member display) are equivalent. Here is an example (a little bit modified your case, to make it clearer):
Note that association end also show the scope and collection type (besides the name of course). col_B is defined ase private {ordered} collection (like array).
So, getting back to the formal side of UML spec... a, x, aa, col_b and m_c are all co called A's structural features (or properties). They can all be visually depicted using relationsips between the classes or inside the class itself. You can even show "int" data type as a class and link it using a composition!
Which way you will use is up to you, kind of matter of personal taste.
I always apply a simple rule - basic data types (int, boolean, date, string, etc) and their arrays are showed in the class itself, while the class and enumeration based properties are depicted by a relationship (example on the top).
As simple data types are clear and well known and does not have their own properties, I find it clear enough to show them in-class (diagram is simpler and smaller).
The complex data types (classes and enumerations) however typically have their own properties (data members, associations), even inheritances, and I want to make the class structure stand out on my diagarm.
You can use your own logic though.
In a class diagram you cannot model the same composition both showing the association and the attribute, because in the UML semantic that would mean your class has two composition :-)
If in your diagram you already have classes B and C, I suggest you opt for the association ("relationship lines") solution.
To better understand the context, you can put the roles on the association: this is equivalent to the name of your attributes.

Fluent Nhibernate and Dynamic Table Name

I've got a parent and child object. Depending on a value in the parent object changes the table for the child object. So for example if the parent object had a reference "01" then it will look in the following table "Child01" whereas if the reference was "02" then it would look in the table "Child02". All the child tables are the same as in number of columns/names/etc.
My question is that how can I tell Fluent Nhibernate or nhibernate which table to look at as each parent object is unique and can reference a number of different child tables?
I've looked at the IClassConvention in Fluent but this seems to only be called when the session is created rather than each time an object is created.
I found only two methods to do this.
Close and recreate the nhibernate session every time another dynamic table needs to be looked at. On creating the session use IClassConvention to dynamically calculate the name based on user data. I found this very intensive as its a large database and a costly operation to create the session every time.
Use POCO object for these tables with custom data access.
As statichippo stated I could use a basechild object and have multiple child object. Due to the database size and the number of dynamic table this wasn't really a valid option.
Neither of my two solutions I was particularly happy with but the POCO's seemed the best way for my problem.
NHibernate is intended to be an object relational mappers. It sounds like you're doing more of a scripting style and hoping to map your data instead of working in an OOP manner.
It sounds like you have the makings of an class hierarchy though. What it sounds like you're trying to create in your code (and then map accordingly) is a hierarchy of different kinds of children:
BaseChild
--> SmartChild
--> DumbChild
Each child is either smart or dumb, but since they all have a FirstName, LastName, Age, etc, they all are instances of the BaseChild class which defines these. The only differences might be that the SmartChild has an IQ and the DumbChild has a FavoriteFootballTeam (this is just an example, no offense to anyone of course ;).
NHibernate will let you map this sort of relationship in many ways. There could be 1 table that encompasses all classes or (what it sounds like you want in your case), one table per class.
Did I understand the issue/what you're looking for?

Should one include ID as a property on objects persisted to a database?

I am creating the model for a web application. The tables have ID fields as primary keys. My question is whether one should define ID as a property of the class?
I am divided on the issue because it is not clear to me whether I should treat the object as a representation of the table structure or whether I should regard the table as a means to persist the object.
If I take the former route then ID becomes a property because it is part of the structure of the database table, however if I take the latter approach then ID could be viewed as a peice of metadata belonging to the database which is not strictly a part of the objects model.
And then we arrive at the middle ground. While the ID is not really a part of the object I'm trying to model, I do realise that the the objects are retrieved from and persisted to the database, and that the ID of an object in the database is critical to many operations of the system so it might be advantageous to include it to ease interactions where an ID is used.
I'm a solo developer, so I'd really like some other, probably more experienced perspectives on the issue
Basically: yes.
All the persistence frameworks ive used (including Hibernate, Ibatis) do require the ID to be on the Object.
I understand your point about metadata, but an Object from a database should really derive its identity in the same way the database does - usually an int primary key. Then Object-level equality should be derived from that.
Sometimes you have primary keys that are composite, e.g first name and last name (don't ever do this!), in which cases the primary key doesn't become 'metadata' because it is part of the Object's identity.
I generally reserve the ID column of an object for the database. My opinion is that to use it for any 'customer-facing' purpose, (for example, use the primary key ID as a customer number) you will always shoot yourself in the foot later.
If you ever make changes to the existing data (instead of exclusively adding new data), you need the PK. Otherwise you don't know which record to change in the DB.
You should have the ID in the object. It is essential.
The easiest use case to give as an example is testing equality:
public bool Equals(Object a, Object b) { return {a.ID = b.ID}; }
Anything else is subject to errors, and you'll find that out when you start getting primary key violations or start overwriting existing data.
By counterargument:
Say you don't have the ID in the object. Once you change an object, and don't have it's ID from the database, how will you know which record to update?
At the same time, you should note that the operations I mention are really private to the object instance, so ID does not necessarily have to be a public property.
I include the ID as a property. Having a simple unique identifier for an object is often very handy regardless of whether the object is persisted in a database or not. It also makes your database queries much more simple.
I would say that the table is just a means to persist an object, but that doesn't mean the object can't have an ID.
I'm very much of the mindset that the table is a means to persist the object, but, even so, I always expose the IDs on my objects for two primary reasons:
The database ID is the most convenient way to uniquely identify an object, either within a class (if you're using a per-table serial/autonumber ID) or universally (if you're maintaining a separate "ID-to-class" mapping). In the context of web applications, it makes everything much simpler and more efficient if your forms are able to just specify <input type=hidden name=id value=12345> instead of having to provide multiple fields which collectively contain sufficient information to identify the target object (or, worse, use some scheme to concatenate enough identifying information into a single string, then break it back down when the form is submitted).
It needs to have an ID anyhow in order to maintain a sane database structure and there's no reason not to expose it.
Should the ID in the object read-only or not? In my mind it should be read-only as by definition the ID will never change (as it uniquely identifies a record in the database).
This creates a problem when you create a new object (ID not set yet), save it in the database through a stored procedure which returns the newly created ID then how do you store it back in the object if the ID property is read-only?
Example:
Employee employee = new Employee();
employee.FirstName="John";
employee.LastName="Smith";
EmployeeDAL.Save(employee);
How does the Save method (which actually connects to the database to save the new employee) update the EmployeeId property in the Employee object if this property is read-only (which should be as the EmployeeId will never ever change once it's created).

How to map many columns from one table in database to one array/list in class?

I have a table in database which has some columns like year,name and also 12 columns (m1,m2,...,m12) representing months. I would like to map this table into one class using NHibernate, ideally, these 12 mapped columns would look like:
_mappedMonths[] = new double[12];
Has anyone a solution for this ?
If you really want to map the columns directly to an array, as you describe, take a look at the ICompositeUserType interface. You can find an article about custom NHibernate mapping here, and this blog post might be of interest as well.
However, if it is not super important you might consider mapping the columns just as you normally would, but as private/protected properties, and then create a public property in your class that exposes those private/public properties as an array. That would be a simpler and faster solution, but would result in code that is not quite as clean.

In which class "should" the responsiblity lie in fetching the data from the Data access layer (RDD)

Lets say I have a class representing a course.The course has its own attributes like subject name, descriprion, start- and an ending date and so on.
Then, the course has attributes like a list of participants. In the database this is obviously represented in two classes; the course and a participant table in a one-to-may relationship.
My question is about how to set the list of participant in the course class: Should it be the course class itself that is fetching the data (through a data access layer, or a layer above), or should one delegate the fetching and the setting of the participants to some kind of helper class, making the course class it's self more or less a dumb object, only holding data?
In RDD(Resopnsible driven design) it tells us to make smart object and abstract away the differentce between data and behaviours. In this regards it sounds obvious that the course class should handle the fetching of the participants. Doing this howerver, is creating a direct dependence on a data access object (or a level above), making it more couple up.
Any thought on this would be helpful.
Should it be the course class itself that is fetching the data
This is a pattern known as Active Record. Be aware that many feel that active record is an anti-pattern.
or should one delegate the fetching and the setting of the participants to some kind of helper class
This is a pattern known as Repository.
making the course class it's self more or less a dumb object, only holding data?
Removing the responsibility of saving and retrieving data from the entity doesn't make that entity a dumb object, only holding data. The entity can still hold domain logic, which is a common practice when practicing Domain-Driven Design. In DDD, entities as simple data containers without behavior are called anemic domain model.
The Course class shouldn't be responsible for fetching the participants, in fact, it shouldn't be responsible for fetching the Courses. You bring up the correct point of data access layers, but the course class itself should not work with this layer, it must just represent a course.
You create a class which has the responsibility of fetching the data, i.e the data access layer. You can name this something similar to CourseDao, but the important part is; that it simply gets the data from the database, and returns it to the client as Courses.
This class has methods like Create, Read, Update and Delete.
Now, you want to do the same for participants, with one small difference. Since your Participant table has a foreign key to Course, your ParticipantDao will have an overloaded Read.
Example:
public class ParticipantDao{
public void create(Participant participant){
//Insert participant in db
}
public Participant read(int id){
//read participant from db
}
public List<Participant> read(){
//read all participants from db
}
public List<Participant> read(Course course){
//read all participants in this course from the db
}
public void Update(Participant participant){
//update and so on.
}
}
And your CourseDao can use this ParticipantDao by going something like:
foreach(Course course in read()){
course.setParticipants(this.participantDao.read(course));
}
In short, you have an object to access the data in the database, which is not the same object that represents said data. When you have a One-To-Many relation, these access objects can work together to retrieve the correct data.