Saving Abstract and Sub classes to database - sql

I have an abstract class "StrategyBase", and a set of sub classes, StrategyA/B/C etc. The sub classes use some of the properties of the base class, and have some individual properties. My question is how to save this to a database.
I'm currently using SqlCE, and Linq-To-Sql by creating entity classes automatically with SqlMetal.exe. I've seen there are three solutions shown in this question, but I'm not able to see how these solutions will work or not with SqlMetal/entity classes. Though it seems to me the "concrete table inheritance" would probably work without any manual modifying. What about the other two, would they be problematic?
For "Single Table Inheritance" wouldn't all classes get all variables, even though they don't need them? And for the "Class table inheritance" solution I can't really see at all how that will map into the entity-classes for a useful purpose. I may note that I extend these partial entity classes for making the classes of my business objects.
I may also consider moving to EntityFramework instead of SqlMetal/Linq2Sql, so would be nice also to know if that makes any difference to what schema is easy to implement.
One likely important thing to note is that I will constantly be develop new strategies, which makes me have to modify the program code, and probably the database shcema; when adding a new strategy.
Sorry the question is a bit "all over the place", but hopefully it's some clear advantages/disadvantages here that you may be able to advice. ?
Cheers!

Actually, this exact question gets asked an awful lot, and has been answered many times. You probably have not searched using database terminology.
The problem is applying OO terminology and thinking in a non-object subject area; making an ordinary straight-forward task very complex and limited.
Martin Fowler's and Scott Ambler's books are not worth a dollar for the lot of them, details in this answer, starting at the 11 Dec 10 entry.
If you still have questions, post a comment.

One option would be to make StrategyBase Serializable, then you can store it as a string in the database. I don't know how big the string would be, as it all depends on the size of your object, but you can make the database field nvarchar(1024) or even nvarchar(max). Ultimately this would result in the entire object being stored in a single table field as string.
Alternatively, as your link eludes to, you can just make a table that mimics each class, and each class object is a field in the table.

Related

What is the interaction between Objective-C and RDBMSes like SQLite?

I would like to learn how to persist data to a RDBMS from Objective-C, and I don't really know where to start to learn this. Do I learn a RDBMS? Do I learn data modeling?
I'm wondering are there techniques or special considerations when modeling the data as to not run into any pitfalls? I.e. are there rules of thumb like "don't subclass" or "always encapsulate your attributes."
In my limited experience it has been quite difficult to translate an Objective-C class into a relational database. It would seem that CoreData might get me started off on the right path, but it also seems like CoreData kinda just gives me a lot of things to take for granted (I'm curious to know what's going on under the hood with the SQL calls...). Or am I understanding this framework wrong?
I'm looking for any resources that would get me started down the path of better understanding RDBMSes and how Objective-C model classes typically interact with them for data storage.
EDIT:
In an effort to answer my own curiosity, I've picked up Joe Celko's SQL for Smarties as well as Beginning Database Design by Clare Churcher. Neither of them really give much by way of the interaction between controller classes written in non-SQL languages (in my case Objective-C), SQL, and the database. There's a missing link that I'm just not understanding...
Check out BaseTen https://bitbucket.org/mka/baseten/wiki/Home
Sorry it's taken so long to come back to you. What you are asking is not specific to Objective-C. My first introduction of connecting Object-oriented code to RDBMS was Enterprise Object Frameworks in NextStep. But since then, that idea has been copied in most object-oriented languages including Java and Ruby (see ActiveRecord).
Conceptually, on the programming side there is usually a entity class that is used to represent each row of a table. In some cases, such as CoreData or WebObjects, a map is used to create an interface between the application code and the database. Because of this map, a developer can use instances of the generic entity class to represent the data. Of course, many times that class is subclassed to added methods specific to a particular entity.
For example, say you have a table for contacts, which has a column for first name and a column for last name. Often in an application you want to display the full name. In a subclass of the entity class, one can add a method that returns the first and last name as a single string.
In other frameworks, such as ActiveRecord, I believe you must always have a subclass that represents each table.
Conceptually, I find Object-Oriented programming to align well with RDBMS.
Table (contacts) -> Class (Contact)
Row -> Instance of class (aContact)
Columns (firstName) -> Properties (aka instance variables, attributes) (firstName)
Relationships:
to-one (father) -> Properties (father, an instance of Contact)
to-many (emailAddresses) -> Array (emailAddresses, an array of instances of EmailAddress class)
Hope this answers your question better,

The core of object oriented programming [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I am trying to understand the core of object oriented programming for php or actionscript proect. As far as I understand, we will have a Main class that control different elements of the project. For example, photoslider class, music control class..etc. I created instance of those classes inside my Main class and use their method or property to control those objects.
I have studied many OOP articles but most of them only talks about inheritance, encapsulation...etc I am not sure if I am right about this and I would appreciate if someone can explain more about it. Thanks!
Same question , i was asking when i were just starting my career but i understood Object Orientation as i progress in my career.
but for very basic startng point in oop.
1- think about object just try to relate your daily household things like ( your laptop, your ipad, your Mobile, your pet)
Step 2-
Try to relate objects like ( Your TV an your remote ) this gives you the basic idea how object should relate to each other.
Step 3-
Try to visulize how things compose to create a full feature like your Body compose of (Heart, Lungs and many other organs)
Step 4-
Try to think about object lifetime ( Like as a example a car enigne is less useful outside Car , so if car is a object than this object must contain a engine and when actual car object destroys engine is also destroyed)
Step 5-
Try to learn about a polymorphism ( Like a ScrewDriver can take may shapes according to your need then map to your objects if your using c# than try to leran about ToString() method overriding)
Step 6 -
Try to create a real life boundry to your real life object ( Like your House ; You secure your house by various means )
this is the initial learning .. read as much as text as you find and try to learn by your own examples
in the last ; oop is an art first , try to visulize it.
my main suggestion is to look at the objects as "smart serfs": each one of these will have memory (the data members) and logic (the member functions).
In my experience, the biggest strength of OOP is the control that you have on the evolution of your design: if your software is remotely useful, it will change, and OOP gives you tools to make the change sustainable. In particular:
a class should change for only one reason, so it must be solve only one problem (SINGLE RESPONSABILITY PRINCIPLE)
changing the behaviour of a class should be made by extending it, not by modifying it (OPEN CLOSED PRINCIPLE)
Focus on interfaces, not on inheritance
Tell, don't ask! Give orders to your objects, do not use them as "data stores"
There are other principles, but I think that these are the ones that must be really understood to succeed in OOP.
I'm not sure I ever understood OOP until I started programming in Ruby but I think I have a reasonable grasp of it now.
It was once explained to me as the components of a car and that helped a lot...
There's such a thing as a Car (the class).
my_car and girlfriends_car are both instances of Car.
my_car has these things that exist called Tyres.
my_car has four instances of Tyres - tyre1, tyre2, tyre3, tyre4
So I have two classes - Car, Tyre
and I have multiple instances of each class.
The Car class has an attribute called Car.colour.
my_car.colour is blue
girlfriends_car is pink
The sticking point for me was understanding the difference between class methods and instance methods.
Instance Methods
An instance method is something like my_car.paint_green. It wouldn't make any sense to call Car.paint_green. Paint what car green? Nope. It has to be girlfriend_car.wrap_around_tree because an instance method has to apply to an instance of that Class.
Class Methods
Say I wanted to build a car? my_new_car = Car.build
I call a Class method because it wouldn't make any sense to call it on an instance? my_car.build? my_car is already built.
Conclusion
If you're struggling to understand OOP then you should make sure that you understand the difference between the Class itself and instances of that Class. Furthermore, you should try to undesrstand the difference between class methods and instance methods. I'd recommend learning some Ruby or Python just so you can get a fuller understanding of OOP withouth the added complicaitons of writing OOP in a non-OOP language.
Great things happen with a true OOP language. In Ruby, EVERYTHING is a class. Even nothing (Nil) is a class. Strings are classes. Numbers are classes and every class is descended from the Object class so you can do neat things like inherit the instance_methods method from Object so String.instance_methods tells you all the instance methods for a string.
Hope that helps!
Kevin.
It seems like you're asking about the procedures or "how-tos" of OOP, not the concepts.
For the how-tos, you're mostly correct: I'm not specifically familiar with PHP or ActionScript, but for those of us in .NET, your program will have some entry point which will take control, and then it will call vairous objects, functions, methods, or whatever- often passing control to other pieces of code- to perform whatever you've decided.
In psuedo-code, it might look something like:
EntryPoint
Initialize (instanciate) a Person
Validate the Person's current properties
Perform some kind of update and/or calculation
provide result to user
Exit
If what you're looking for is the "why" then you're already looking in the right places. The very definitions of the terms Encapsulation, Inheritance, etc. will shed light on why we do OOP.
It's mostly about grouping code that belongs to certain areas together. In non-OOP languages you often have the problem that you can't tell which function is used for what/modifies which structures or functions tend to do too many loosely related things. One work around is to introduce a strict naming scheme (e.g. start every function name with the structure name it's associated with). With OOP, every function is tied to a data structure (the object) and thus makes it easier to organize your code. If you code gets larger/the number of tasks bigger inheritance starts to make a difference.
Good example is a structure representing a shape and a function that returns its center. In non-OOP, that function must distinguish between each structure. That's a problem if you add a new shape. You have to teach your function how to calculate the center for that shape. Now imagine you also had functions to return the circumfence and area and ... Inheritance solves that problem.
Note that you can do OOP programming in non-OOP languages (see for example glib/gtk+ in C) but a "real" OOP language makes it easier and often less error-prone to code in OOP-style. On the other hand, you can mis-use almost every OOP language to write purely imperative code :-) And no language prevents one from writing stupid and inefficient code, but that's another story.
Not sure what sort of answer you're looking for, but I think 10s of 1000s of newly graduated comp sci students will agree: no amount of books and theory is a substitute for practice. In other words, I can explain encapsulation, polymorphism, inheritance at length, but it won't help teach you how to use OO effectively.
No one can tell you how to program. Over time, you'll discover that, no matter how many different projects your working on, you're solving essentially the same problems over and over again. You'll probably ask yourself regularly:
How to represent an object or a process in a meaningful way to the client?
How do I reuse functionality without copy-pasting code?
What actually goes in a class / how fine-grained should classes be?
How do support variations in functionality in a class of objects based on specialization or type?
How do support variations in functionality without rewriting existing code?
How do I structure large applications to make them easy to maintain?
How do I make my code easy to test?
What I'm doing seems really convoluted / hacky, is there an easier way?
Will someone else be able to maintain the code when I'm finished?
Will I be able to maintain the code in 6 months or a year from now?
etc.
There are lots of books on the subject, and they can give you a good head start if you need a little advice. But trust me, time and practice are all you need, and it won't be too long -- maybe 6 or 9 months on a real project -- when OO idioms will be second nature.

DDD: Should everything fit into either Entity or Value Object?

I'm trying to follow DDD, or a least my limited understanding of it.
I'm having trouble fitting a few things into the DDD boxes though.
An example: I have a User Entity. This user Entity has a reference to a UserPreferencesInfo object - this is just a class which contains a bunch of properties regarding user preferences. These properties are fairly unrelated, other than the fact that they are all user preferences (unlike say an Address VO, where all the properties form a meaningful whole).
Question is - what is this UserPreferencesInfo object?
1) Obviously it's not an Entity (I'm just storing it as 'component' in fluent nhibernate speak (i.e. in the same DB table as the User entity).
2) VO? I understand that Value Object are supposed to be Immutable (so you cant cange them, just new them up). This makes complete sense when the object is an address for instance (the address properties form a meaningful 'whole'). But in the case of UserPreferencesInfo I don't think it makes sense. There could be 100 properties (Realistically) There could be maybe 20 properties on this object - why would I want to discard an recreate the object whenever I needed to change one property?
I feel like I need to break the rules here to get what I need, but I don't really like the idea of that (it's a slippery slope!). Am I missing something here?
Thanks
Answer 1 (the practical one)
I'm a huge proponent of DDD, but don't force it. You've already recognised that immutable VOs add more work than is required. DDD is designed to harness complexity, but in this case there is very little complexity to manage.
I would simply treat UserPreferencesInfo as an Entity, and reference it from the User aggregate. Whether you store it as a Component or in a separate table is your choice.
IMHO, the whole Entity vs VO debate can be rendered moot. It's highly unlikely that in 6 months time, another developer will look at your code and say "WTF! He's not using immutable VOs! What the heck was he thinking!!".
Answer 2 (the DDD purist)
Is UserPreferencesInfo actually part of the business domain? Others have mentioned disecting this object. But if you stick to pure DDD, you might need to determine which preferences belong to which Bounded Context.
This in turn could lead to adding Service Layers, and before you know it, you've over-engineered the solution for a very simple problem...
Here's my two cents. Short answer: UserPreferenceInfo is a value object because it describes the characteristics of an object. It's not an entity because there's no need to track an object instance over time.
Longer answer: an object with 100+ properties which are not related is not very DDD-ish. Try to group related properties together to form new VOs or you might discover new entities as well.
Another DDD smell is to have a lot of set properties in the first place. Try to find the essence of the action instead of only setting the value. Example:
// not ddd
employee.Salary = newSalary;
// more ddd
employee.GiveRaise(newSalary);
On the other hand you may very well have legitimate reasons to have a bunch of properties that are no more than getters and setters. But then there's probably simpler methods than DDD to solve the problem. There's nothing wrong with taking the best patterns and ideas from DDD but relax a little of all the "rules", especially for simpler domains.
I'd say a UserPreferenceInfo is actually a part of the User aggregate root. It should be the responsibility of the UserRepository to persist the User Aggregate Root.
Value objects only need to be newed up (in your object model) when their values are shared. A sample scenario for that would be if you check for a similar UserPreferenceInfo and associate the User with that instead of Inserting a new one everytime. Sharing Value Objects make sense if value object tables would get to large and raise speed/storage concerns. The price for sharing is paid on Insert.
It is reasonable to abstract this procedure in the DAL.
If you are not shraing value objects, there is nothing against updating.
As far as I understand, UserPreferenceInfo is a part of User entity. Ergo User entity is an Aggregate root which is retrieved or saved using UserRepository as a whole, along with UserPreferenceInfo and other objects.
Personally, I think that UserPreferenceInfo is entity type, since it has identity - it can be changed, saved and retrieved from repository and still be regarded as the same object (i.e. has identity). But it depends on your usage of it.
It doesn't matter IMHO how object is represented in the DAL - is it stored in a separate table or part of other table. One of the benefits of DDD is persistence ignorance and is ususally a good thing.
Of course, I may be wrong, I am new to DDD too.
Question is - what is this UserPreferencesInfo object?
I don't know how this case is supported by NHibernate, but some ORMs support special concepts for them. For example DataObjects.Net include Structures concept. It seems that you need something like this in NH.
First time ever posting on a blog. Hope I do it right.
Anyway, since you haven't showed us the UserPreferencesInfo object, I am not sure how it's constructed such that you can have a variable number of things in it.
If it were me, I'd make a single class called UserPreference, with id, userid, key, value, displaytype, and whatever other fields you may need in it. This is an entity. it has an id and is tied to a certain user.
Then in your user entity (the root I am assuming), have an ISet.
100 properties sounds like a lot.
Try breaking UserPreferenceInfo up into smaller (more cohesive) types, which likely/hopefully are manageable as VOs.

Motivating factors for composing a particular object?

I know there are LOTS of reasons why you would compose a certain object inside another one. Some schools of thought have made explicit the reasons for architecting a program a certain way e.g. 'data-driven design' or 'domain-driven design'. I'm still a beginner to OOP, and it's often hard for me to understand why one object should be contained by another. Sometimes, I find myself with an object that seems awesome, and then I get to the point where I realize, "Okay, now I have to put this somewhere?" Is the reasoning behind this similar to where I'd decide put a file on my hard disk?
I have a couple guiding principles for this:
If it models a relationship in the physical world.
If the composer has data needed to construct the object.
If the composed object will be listening to the composer.
What do you look for when you make this decision?
Well, one very simple concept that helped me with this is simply the concept of "has a" versus "is a". Ask yourself, is the contained object something the containing object has, or is it something the containing object is? If it's something the containing object has, then containment is appropriate. Otherwise maybe you should be looking at inheritance.
A dog IS an animal, and has a nose, so it's:
class Animal
{
}
class Dog : Animal
{
Nose n;
}
Now this works fine. One "problem" with this approach is that you tightly couple noses and dogs, so sometimes you'll see things like containing an interface pointer rather than an object, or you might Google "Dependency Injection". But as the saying goes, "has a" and "is a" is often close enough for government work.
Early on, just try lots of examples and over time it will become natural. If you end up with spaghetti, throw some meatballs at it and try again! :)
What alternatives are you considering? Are you talking about Containment versus Inheritance, John Lockwood's comments about hasA and isA help with that issue.
Or are your perhaps talking about, Containment versus Association? There are various flavours of hasA. For example a Person may haveA Spouse, but clearly does not containA Spouse. There's a difference between changing a Spouse and changing a Nose.
The kinds of relationship that you consider:
Lifetime: Does it make sense to create a Person without a Nose? Can Noses exist without a Person? Can a Person exist without a Spouse? The answers to these questions drive the kind of operation you choose to have on Person. Probably don't need a setNose() method, though maybe we do need a wipeNose() method, and we probably do need a marry(Person) method.
Cardinality: How many Noses for a Person? How many Wheels and Seats does a Vehicle have? Answers to this determine the kinds of data structures? Just a reference? A list? An hash table?
I found it helpful to read about UML modeling, especially class diagrams. This reflects much experience of how to usefully capture various kinds of relationships.
Sometimes, I find myself with an
object that seems awesome, and then I
get to the point where I realize,
"Okay, now I have to put this
somewhere?"
From the above sentence, it sounds like you're trying to design from the bottom up. One of the thing's I've learned over the years is that top down design is the way to go. You should only write the class after you know where it needs to be used. Otherwise you just end up writing classes that "seem awesome" and contain code that might not be useful at all.

Desigining Proper Classes

I've read all the books about why to create a class and things like "look for the nouns in your requirements" but it doesn't seem to be enough. My classes seem to me to be messy. I would like to know if there are some sort of metrics or something that I can compare my classes to and see if there well designed. If not, who is the most respected OO guru where I can get the proper class design tips?
Creating classes that start clean and then get messy is a core part of OO, that's when you refactor. Many devs try to jump to the perfect class design from the get go, in my experience that's just not possible, instead you stumble around, solving the problem and then refactor. You can harvest, base classes and interfaces as the design emerges.
if you're familiar with database design, specifically the concept of normalization, then the answer is easy: a data-centric class should represent an entity in third normal form
if that is not helpful, try this instead:
a class is a collection of data elements and the methods that operate on them
a class should have a singular responsibility, i.e. it should represent one thing in your model; if it represents more than one thing then it should be more than one class.
all of the data elements in a class should be logically associated/related to each other; if they aren't, split it into two or more classes
all of the methods in a class should operate only on their input parameters and the class's data elements - see the Law of Demeter
that's about as far as i can go with general abstract advice (without writing a long essay); you might post one of your classes for critique if you need specific advice
Try to focus on behaviour instead of structure. Objects are 'living' entities with behaviour and responsibilities. You tell them to do things. Have a look at the CRC-card approach to help you model this way.
i think Object design is as much art as it is science. It takes time and practice to understand how to design clean & elegant classes. Perhaps if you can give an example of a simple class you've designed that you aren't happy with SO users can critique and give pointers. I'm not sure there are any general answers outside of what you've already read in the texts.
The most respected OO guru i personally know is StackOverflow. Put your classnames here and i reckon you'll get a goodly number of reviews.
Classes are typically used to model concepts of the problem domain. Once you have a well-defined problem (aka the set of use cases), you will be able to identify all participants. A subset of the participants will be intrinsic to the system you are designing. Start with one big black box as your system. Keep breaking it down, as and when you have more information. When you have a level where they can no longer be broken down (into concepts in your problem domain), you start getting your classes.
But then, this is a subjective view of a non-guru. I'd suggest a pinch of salt to the menu.
Metrics? Not so's that you'd trust them.
Are your classes doing the job of getting the program working and keeping it maintainable through multiple revisions?
If yes, you're doing ok.
If no, ask yourself why not, and then change what isn't working.