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

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,

Related

Be suspicious of classes of which there is only one instance

tl;dr -- What does the below quoted paragraph mean?
Be suspicious of classes of which there is only one instance. A
single instance might indicate that the design confuses objects with
classes. Consider whether you could just create an object instead of a
new class. Can the variation of the derived class be represented in
data rather than as a distinct class? The Singleton pattern is one
notable exception to this guideline.
McConnell, Steve (2004-06-09). Code Complete (2nd Edition)
Extended version:
I'm currently reading Code Complete, and I'm having trouble understanding the above mentioned paragraph. For context, it's from Chapter 6 under guidelines for inheritance. At first I thought this was advice against using Singletons, but I was obviously proven wrong by the time I got to the end of the paragraph.
I simply can't grasp what the author is trying to get through my thick skull. For example, I don't know what he means by design confusing objects with classes, nor what that means in the context of having a class with only one instance. Help!
The wording is pretty confusing there, but I believe what's meant is that sometimes a novice programmer might create a whole new type just to instantiate one object of it. As a particularly blatant example:
struct Player1Name
{
string data;
};
There we could just use string player1_name; (or even an aggregate for multiple players) without creating a whole new type, hence the confusion of trying to use classes to model what new objects (new instances of existing types) can already do.
In such a case, a developer might spam the codebase with hundreds of new user-defined data types and possibly massive inheritance hierarchies with no potential for a single class to be reused beyond a single instance for every single new thing he wants to create when the existing classes generally suffice.
The real problem is not that the classes are being instantiated once,
but that their design is so narrowly applicable as to only be worth instantiating once.
Classes are generally meant to model a one-to-many relationship with their instances (objects). They're supposed to be at least somewhat more generally applicable beyond a single instance of that class. Put crudely, a class should model a Dog, not your neighbor's specific pet dog, Spark. It's supposed to model a Rectangle, not a precise Rectangle42x87 that is 4.2 meters by 8.7 meters. If you're designing things to be instantiated one time, you're probably designing them too narrowly and probably have existing things you can use instead.
A new data type is typically meant to tackle a class (category) of problems, so to speak, rather than one very precise one that calls for only one instance of that class. Otherwise your class designs are going to be one-shot deals that are just superficially creating classes all over the place to solve very individual problems with no potential for broader application whatsoever.
A singleton is an exception to the rule since it's not utilizing classes in this normal object-oriented kind of way. There it's deliberately setting out to create a single instance, lazy constructed, and with a global point of access. So there it's not by some accident and misunderstanding of object-oriented design that the developer created a class designed to be instantiated one time. It's a very deliberate and conscious design decision, so to speak, rather than a misunderstanding of how to use the tools.

Saving Abstract and Sub classes to database

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.

Object Oriented Programming beyond just methods?

I have a very limited understanding of OOP.
I've been programming in .Net for a year or so, but I'm completely self taught so some of the uses of the finer points of OOP are lost on me.
Encapsulation, inheritance, abstraction, etc. I know what they mean (superficially), but what are their uses?
I've only ever used OOP for putting reusable code into methods, but I know I am missing out on a lot of functionality.
Even classes -- I've only made an actual class two or three times. Rather, I typically just include all of my methods with the MainForm.
OOP is way too involved to explain in a StackOverflow answer, but the main thrust is as follows:
Procedural programming is about writing code that performs actions on data. Object-oriented programming is about creating data that performs actions on itself.
In procedural programming, you have functions and you have data. The data is structured but passive and you write functions that perform actions on the data and resources.
In object-oriented programming, data and resources are represented by objects that have properties and methods. Here, the data is no longer passive: method is a means of instructing the data or resource to perform some action on itself.
The reason that this distinction matters is that in procedural programming, any data can be inspected or modified in any arbitrary way by any part of the program. You have to watch out for unexpected interactions between different functions that touch the same data, and you have to modify a whole lot of code if you choose to change how the data is stored or organized.
But in object-oriented programming, when encapsulation is used properly, no code except that inside the object needs to know (and thus won't become dependent on) how the data object stores its properties or mutates itself. This helps greatly to modularize your code because each object now has a well-defined interface, and so long as it continues to support that interface and other objects and free functions use it through that interface, the internal workings can be modified without risk.
Additionally, the concepts of objects, along with the use of inheritance and composition, allow you to model your data structurally in your code. If you need to have data that represents an employee, you create an Employee class. If you need to work with a printer resource, you create a Printer class. If you need to draw pushbuttons on a dialog, you create a Button class. This way, not only do you achieve greater modularization, but your modules reflect a useful model of whatever real-world things your program is supposed to be working with.
You can try this: http://homepage.mac.com/s_lott/books/oodesign.html It might help you see how to design objects.
You must go though this I can't create a clear picture of implementing OOP concepts, though I understand most of the OOP concepts. Why?
I had same scenario and I too is a self taught. I followed those steps and now I started getting a knowledge of implementation of OOP. I make my code in a more modular way better structured.
OOP can be used to model things in the real world that your application deals with. For example, a video game will probably have classes for the player, the badguys, NPCs, weapons, ammo, etc... anything that the system wants to deal with as a distinct entity.
Some links I just found that are intros to OOD:
http://accu.informika.ru/acornsig/public/articles/ood_intro.html
http://www.fincher.org/tips/General/SoftwareEngineering/ObjectOrientedDesign.shtml
http://www.softwaredesign.com/objects.html
Keeping it very brief: instead of doing operations on data a bunch of different places, you ask the object to do its thing, without caring how it does it.
Polymorphism: different objects can do different things but give them the same name, so that you can just ask any object (of a particular supertype) to do its thing by asking any object of that type to do that named operation.
I learned OOP using Turbo Pascal and found it immediately useful when I tried to model physical objects. Typical examples include a Circle object with fields for location and radius and methods for drawing, checking if a point is inside or outside, and other actions. I guess, you start thinking of classes as objects, and methods as verbs and actions. Procedural programming is like writing a script. It is often linear and it follows step by step what needs to be done. In OOP world you build an available repetoire of actions and tasks (like lego pieces), and use them to do what you want to do.
Inheritance is used common code should/can be used on multiple objects. You can easily go the other way and create way too many classes for what you need. If I am dealing with shapes do I really need two different classes for rectangles and squares, or can I use a common class with different values (fields).
Mastery comes with experience and practice. Once you start scratching your head on how to solve particular problems (especially when it comes to making your code usable again in the future), slowly you will gain the confidence to start including more and more OOP features into your code.
Good luck.

Design classes - OOPS features

I am interested in improving my designing capability (designing of classes with its properties, methods etc) for a given.
i.e. How to decide what should be the classes, methods and properties?
Can you guys suggest me good material for improving on this?
Please see:
Any source of good object-oriented design practises?
Best Resources to learn OO Design and Analysis
among many....
Encapsulation: The wrapping up of data and functions into a single unit is known as encapsulation. Or, simply put: putting the data and methods together in a single unit may be a class.
Inheritance: Aquiring the properties from parent class to child class. Or: getting the properties from super class to sub class is known as inheritance.
Polymorphism: The ability to take more that one form, it supports method overloading and method overriding.
Method overloading: When a method in a class having the same method name with different arguments (diff parameters or signatures) is said to be method overloading. This is compile-time polymorphism – using one identifier to refer to multiple items in the same scope.
This is perhaps a question which every programmer thinks of one day.
The designing capability comes with your experience gradually. What I would say is in general scenario if you can visualize the Database objects for a given problem, the rest is a cakewalk (isnt true sometimes if you work on a techie project with no DB)
You can start thinking of objects which are interacting in the real world to complete the process and then map them to classes with appropriate properties and then methods for defining their behavior. Ten you can focus on the classes which contribute to running the workflow and not to any individual real world object.
This gets a lot simplified if we focus on designing the DB before we jump directly to code design.
A lot depends on the pattern you choose - If you see a problem from MVC perspective, you will naturally be drawn towards identifying "controller" classe first and so on.
I guess I need not repeat the golden sources of design and OOPS wisdom - they already posted here or there.
I would recommend you to read up on some UML and design patterns. That gets you going with the thinking in "drawing" terms. You can also get a good grasp of a big class/object a lot easier.
One particular book that is good in this area.
Applying UML and Patterns
Give a look a Domain-Driven Design, which defines entities, value objects, factories, services and repositories and the GRASP patterns (General Responsibility Assignment Software Patterns) e.g. Expert, Creator, Controller.
Have a look at the part 1 screencast the first part is not silverlight but just a command line calculator that starts out as a single bit of code, and is then broken down into classes.

OOP - How to choose a possible object candidate?

I 'm concern about what techniques should I use to choose the right object in OOP
Is there any must-read book about OOP in terms of how to choose objects?
Best,
Just write something that gets the job done, even if it's ugly, then refactor continuously:
eliminate duplicate code (don't repeat yourself)
increase cohesion
reduce coupling
But:
don't over-engineer; keep it simple
don't write stuff you ain't gonna need
It's not a precise recipe, just some general guidelines. Keep practicing.
P.S.
Code objects are not related to tangible real-life objects; they are just constructs that hold related information together.
Don't believe what the Java books/schools teach about objects; they're lying.
You probably mean "the right class", rather than "the right object". :-)
There are a few techniques, such as text analysis (a.k.a. underlining the nouns) and Class Responsibility Collaborator (CRC).
With "underlining the nouns", you basically start with a written, natural language (i.e. plain English) description of the problem you want to solve and underline the nouns. That gives you a list of candidate classes. You will need to perform several passes to refine it into a list of classes to implement.
For CRC, check out the Wikipedia.
I suggest The OPEN Toolbox of Techniques for full reference.
Hope it helps.
I am assuming that there is understanding of what is sctruct, type, class, set, state, alphabet, scalar and vector and relationship.
Object is a noun, method is a verb. Object members can represent identity, state or scalar value per field. Relationships between objects usually are represented with references, where references are members of objects. In cases, when relationships are complex, multidirectional, have arity greater than 2, represent some sort of grouping or containment, then relationships can be expressed as objects.
For other, broader technical reasons objects are most likely the only way to represent any form of information in OOP languages.
I am adding a second answer due to demian's comment:
Sometimes the class is so obvious
because it's tangible, but other times
the concept of object it's to abstract
like a db connector.
That is true. My preferred approach is to perform a behavioural analysis of the system (using use cases, for example), and then derive system operations. Once you have a stable list of system operations (such as PrintDocument, SaveDocument, SpellCheck, MergeMail, etc. for a word processor) you need to assign each of them to a class. If you have developed a list of candidate classes with some of the techniques that I mentioned earlier, you will be able to allocate some of the operations. But some will remain unallocated. These will signal the need of more abstract or unintuitive classes, which you will need to make up, using your good judgment.
The whole method is documented in a white paper at www.openmetis.com.
You should check out Domain-Driven Design, by Eric Evans. It provides very useful concepts in thinking about the objects in your model, what their function are in the domain, and how they could be organized to work together. It's not a cookbook, and probably not a beginner book - but then, I read it at different stages of my career, and every time I found something valuable in it...
(source: domaindrivendesign.org)