OOP where to put orphan methods - oop

Apologies if this has been answered elsewhere, my search didn't yield quite the answer I was looking for.
Hypothetically speaking, let us say I am building an application for a bookshop.
I have a class that handles all my database transactions. I also have a 'Book' class which extends the Database class, calling the Database constructor from it's own constructor, removing the need to instantiate the Database class first:
class Book extends Database {
__construct($book_id){
parent::__construct();
$this->databaseGet("SELECT * FROM..."); // method in Database class
etc...
}
}
I can pass a reference id to the 'Book' class constructor and create an object containing information pulled from the database about that book along with several methods relevant to a given book.
But I also want to list all the books in the database. My question is, where do I put this method and other methods that simply don't have a context such as 'Book'?
I could create a single "GetStuff" or 'Bookshop' class that extends the Database class, which would contain all these single-use methods. But that requires it to be loaded all the time as these orphan methods would be used all over the program.
I could create lots of classes that house a single method but that would require instantiating the class to an object in order to call the method, seems like overkill.
They aren't general utilities, they have a place in the business model. Just where should I put these orphan methods?

If I understand it, you're asking where should code go that relates to a specific type but doesn't implement a behaviour of the type itself. There is no single answer. According to the overall design of the system, it could be part of the type - Smalltalk classes have 'class fields' and 'instance fields', and there is nothing wrong with that - or it could end up anywhere it makes sense. If it relates to something external to the type itself - that is, it's not merely a matter of not being the behaviour of an instance, but a matter of being an interaction with something extraneous - it may make sense to put it outside. For instance, you may have Book, BookDatabase, BookForm, BookWebService, etc. There's no harm in some of those classes having few members, you never know when you'll want to add some more.

Book is a book, Books is collection of books.
Database is one thing you could use to persist a lot of books so you don't have to type them all in again.
It could be an xml file, an excel spreadsheet, even a webservice.
So write Book and Books, then write something like
BookDatabase extends database with methods like
Books GetBooks();
and
void SaveBook(Book argBook);
The real trick is to make Book and Books work no matter what / how they are stored.
There's lot more to learn around that, but first thing to do is start again and not make your data objects dependant on a particular "database".

Seems your design is seriously flawed. You have to separate three concerns:
Your Domain Layer (DM): In this case, Book belongs to it.
Data Access Layer (DAL): Handles database storage. Domain Layer does not know about this layer at all.
Service Layer (SL): handles use cases. A use case may involve multiple object from Domain, as well as calls to DAL to save or retrieve data. Methods in service layer perform a unit of work.
A simplified example:
// Model Object
class Book {
title;
author:
isbn;
constructor(title, author, isbn) {// ...}
// other methods ...
}
// DAL class
class BookDataMapper {
// constructors ...
save(Book book) {}
Book getById(id) {
String query = get from book table where book_id = id;
execute query;
parse the result;
Book book = new Book(parsed result);
return book;
}
Book getByTitle(title) {}
...
getAll(){} // returns all books
}
//Service class
class BookService {
BookDataMapper bookMapper;
buyBook(title) {
// check user account
// check if book is available
Book book = bookMapper.getBytitle(title);
if book available
charge customer
send the book to ship etc.
}
}

Related

NullObject Pattern: How to handle fields?

Suppose we have Book class which contains year_published public field. If I want to implement NullObject design pattern, I will need to define NullBook class which behaves same as Book but does not do anything.
Question is, what should be the behavior of NullBook when it's fields are being assigned?
Book book = find_book(id_value); //this method returns a NullBook instance because it cannot find the book
book.year_published = 2016; //What should we do here?!
The first thing you should do is to make your properties private.
class NullBook {
private year_published;
// OR solution2 private year_published = null;
public setYearPublished(year_published) {
this.year_published = null;
// OR solution2 do nothing!
}
}
You can also define the field private in the parent class, so the children will have to implement the setter to acces the field
class Book {
private year_published;
public setYearPublished(year_published) {
this.year_published = year_published;
}
}
class NullBook extends Book {
public setYearPublished(year_published) {
parent::setYearPublished(null);
}
}
Why use getters and setters?
https://stackoverflow.com/a/1568230/2377164
Thing is: patterns are about balancing. Yes, it is in general good practice to not return null, but to having else to return; but well: what is returned should still make sense!
And to a certain degree, I don't see how having a "NullBook" really helps with the design of your application. Especially as you allow access to various internal fields. You exactly asked the correct question: what should be the published year, or author, or ... of such a "NullBook"?!
What happens for example when some piece of code does a "lookup" on books from different "sources"; and then tries to sort those books on the published year. You sure don't want your NullBook to ever be part of such data.
Thus I fail to see the value in having this class, to the contrary: I see it creating a potential for "interesting" bugs; thus my answer is: step back and re-consider if you really need that class.
There are alternatives to null-replacing objects: maybe your language allows for Optionals; or, you rework those methods that could return null ... to return a collection/array of books; and in doubt: that list/array is simply empty.
Long story short: allowing other classes direct access to private fields is a much more of an import design smell; so you shouldn't be too focused on NullObjects, while giving up on such essential things as Information Hiding so easily on the other hand.

How to structure object: OOP, composition

I have an object, let's call it a Request, that has associations to several other objects like:
Employee submitter;
Employee subjectsManager;
Employee pointOfContact;
And several value properties like strings, dates, and enums.
Now, I also need to keep track of another object, the subject, but this can be one of 3 different types of people. For simplicity let's just talk about 2 types: Employee and Consultant. Their data comes from different repositories and they have different sets of fields, some overlapping. So say an employee has a
String employeeName;
String employeeId;
String socialSecurityNumber;
Whereas a consultant has
String consultantName;
String socialSecurityNumber;
String phoneNumber;
One terrible idea is that the Request has both a Consultant and an Employee, and setSubject(Consultant) assigns one, setSubject(Employee) assigns the other. This sounds awful. One of my primary goals is to avoid "if the subject is this type then do this..." logic.
My thought is that perhaps an EmployeeRequest and a ConsultantRequest should extend Request, but I'm not sure how, say, setSubject would work. I would want it to be an abstract method in the base class but I don't know what the signature would be since I don't know what type the parameter would be.
So then it makes sense to go at it from an interface perspective. One important interface is that these Request objects will be passed to a single webservice that I don't own. I will have to map the object's fields in a somewhat complex manner that partially makes sense. For fields like name and SSN the mapping is straightforward, but many of the fields that don't line up across all types of people are dumped into a concatenated string AdditionalInfo field (wump wump). So they'll all have a getAdditionalInfo method, a getName, etc, and if there's any fields that don't line up they can do something special with that one.
So that makes me feel like the Request itself should not necessarily be subclassed but could contain a reference to an ISubjectable (or whatever) that implements the interface needed to get the values to send across the webservice. This sounds pretty decent and prevents a lot of "if the subject is an employee then do this..."
However, I would still at times need to access the additional fields that only a certain type of subject has, for example on a display or edit page, so that brings me right back to "if subject is instance of an employee then go to the edit employee page..." This may be unavoidable though and if so I'm ok with that.
Just for completeness I'll mention the "union of all possible fields" approach -- don't think I'd care to do that one either.
Is the interface approach the most sensible or am I going about it wrong? Thanks.
A generic solution comes to mind; that is, if the language you're using supports it:
class Request<T extends Subject> {
private T subject;
public void setSubject(T subject) {
this.subject = subject;
}
public T getSubject() {
return subject;
}
}
class EmployeeRequest extends Request<Employee> {
// ...
}
class ConsultantRequest extends Request<Consultant> {
// ...
}
You could similarly make the setSubject method abstract as you've described in your post, and then have separate implementations of it in your subclasses. Or you may not even need to subclass the Request class:
Request<Employee> employeeRequest = new Request<>();
employeeRequest.setSubject(/* ... */);
// ...
int employeeId = employeeRequest.getSubject().getEmployeeId();

WCF: how to modify registers with different types of operations (update, add, delete...)

Well, in this post, I get to the conclusion that is better to work with services in per call mode, because it's more efficient. This makes me to have data context with a short life, the life of the method that I call.
In this example, I see how to modify data of a list of elements, only is needed to set the state of the entity to modified.
However, how could I do with one operation, modifies and updates, for example?
One case can be this. I have books and authors, and the client application have a view with two datagrids, one for authors and other for books. The user can add authors and modify their information in the first datagrid and do the same with the books in the second datagrid. Also can assign books to their authors.
I have the POCO classes, so I have a author class with a property that is a list of books. Well, I can add books to this list, and then when I call the service method updateAuthors, I only need to use the class of author as parameter, EF knows what to do with the books. It is not needed to pass the book too.
But what happens when in the list of books there are new books and also books that exists but its information is modified?
In the example of the post that I mention in the beginning it says how to do it when all the entity are modify, but if I want to add new registers, I need to set the state to add. So if there is mixed entities, how can I do it? does it exist any pattern or a some way to do this? I have to set the state of all the books? I can know the state of the books, because I use an autonumeric as ID, so if the ID is 0 is a new register, in other case is a modification.
Thanks.
Daimroc.
EDIT: Perhaps I don't be very clear in my question. What I want to know is how I can save the changes of many entities at once. For example, I have the Authors, Books and Custormers. I Add, modify and delete information of many of them. In my WCF client I have method to save changes of Authors, other method to save changes of books and other method to save changes of Customers.
How my service is per call, I need to make three calls, one for each type of entities, and this are independents. However, if I use directly entity framework, I can do many changes to many type of entities and I only need to call savechanges once, it make all the work. How can I do the same with WCF and POCO entities?
I am reading about self tracking entities, buy I have the same problem, I can use Applychanges(entity) but if I am not wrong, it applies changes only to one entity. do I need to call N times if I did changes to many entities?
Thanks.
Not sure if this will answer your question, but here is my suggestion:
Manage the state on your POCO entities by using flags (IsNew, IsDirty, IsDeleted);
When you pass the POCO entities to the object context, use the ObjectStateManager to change the attached entity state;
Recursively loop through the list of children entities and apply the same approach.
EDIT:
The following code is the AuthorStateManager class:
public partial class AuthorStateManager : IStateManager<Author, Context>
{
private IStateManager<Book, Context> _BookStateManager = new BookStateManager();
public void ChangeState(Author m, Context ctx)
{
if (m == null) return;
ctx.Authors.Attach(m);
if (m.IsDeleted)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Deleted);
}
else
{
if (m.IsNew)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Added);
}
else
{
if (m.IsDirty)
{
ctx.ObjectStateManager.ChangeObjectState(m, System.Data.EntityState.Modified);
}
}
}
SetRelationsState(m, ctx);
}
private void SetRelationsState(Author m, Context ctx)
{
foreach (Book varBook in m.Books)
{
_BookStateManager.ChangeState(varBook, ctx);
}
}
}
where Authors is the ObjectSet, m is a POCO entity of type Author, ctx is the object context, and SetRelationsState is the method that loops through all the children state managers to update their state.
After changing the state, in my repository object I call ctx.SaveChanges(). This is the Update method in AuthorRepository class:
public Author Update(Author m, bool commit)
{
_AuthorStateManager.ChangeState(m, _ctx);
if (commit)
{
_ctx.SaveChanges();
}
return m;
}
_BookStateManager is a private member of BookStateManager type which modifies the Book state in its own ChangeState() method.
I suggest you make the State Manager classes implement an interface called IStateManager, which has the ChangeState() method.
It seems a bit convoluted, but it gets easier if you generate code for these classes.
If you want to perform multiple actions in a single service call, then the action to take need to move from being a method call to an object. For example, you might have a InsertCustomerAction class which has a Customer instance tied to it. All of these actions would have a base class (Action) and your WCF method would take in a collection of Action instances.

Business Entity - should lists be exposed only as ReadOnlyCollections?

In trying to centralize how items are added, or removed from my business entity classes, I have moved to the model where all lists are only exposed as ReadOnlyCollections and I provide Add and Remove methods to manipulate the objects in the list.
Here is an example:
public class Course
{
public string Name{get; set;}
}
public class Student
{
private List<Course>_courses = new List<Course>();
public string Name{get; set;}
public ReadOnlyCollection<Course> Courses {
get{ return _courses.AsReadOnly();}
}
public void Add(Course course)
{
if (course != null && _courses.Count <= 3)
{
_courses.Add(course);
}
}
public bool Remove(Course course)
{
bool removed = false;
if (course != null && _courses.Count <= 3)
{
removed = _courses.Remove(course);
}
return removed;
}
}
Part of my objective in doing the above is to not end up with an Anemic data-model (an anti-pattern) and also avoid having the logic that adds and removes courses all over the place.
Some background: the application I am working with is an Asp.net application, where the lists used to be exposed as a list previously, which resulted in all kinds of ways in which Courses were added to the Student (some places a check was made and others the check was not made).
But my question is: is the above a good idea?
Yes, this is a good approach, in my opinion you're not doing anything than decorating your list, and its better than implementing your own IList (as you save many lines of code, even though you lose the more elegant way to iterate through your Course objects).
You may consider receiving a validation strategy object, as in the future you might have a new requirement, for ex: a new kind of student that can have more than 3 courses, etc
I'd say this is a good idea when adding/removing needs to be controlled in the manner you suggest, such as for business rule validation. Otherwise, as you know from previous code, there's really no way to ensure that the validation is performed.
The balance that you'll probably want to reach, however, is when to do this and when not to. Doing this for every collection of every kind seems like overkill. However, if you don't do this and then later need to add this kind of gate-keeping code then it would be a breaking change for the class, which may or may not be a headache at the time.
I suppose another approach could be to have a custom descendant of IList<T> which has generic gate-keeping code for its Add() and Remove() methods which notifies the system of what's happening. Something like exposing an event which is raised before the internal logic of those methods is called. Then the Student class would supply a delegate or something (sorry for being vague, I'm very coded-out today) when instantiating _courses to apply business logic to the event and cancel the operation (throw an exception, I imagine) if the business validation fails.
That could be overkill as well, depending on the developer's disposition. But at least with something a little more engineered like this you get a single generic implementation for everything with the option to add/remove business validation as needed over time without breaking changes.
I've done that in the past and regretted it: a better option is to use different classes to read domain objects than the ones you use to modify them.
For example, use a behavior-rich Student domain class that jealously guards its ownership of courses - it shouldn't expose them at all if student is responsible for them - and a StudentDataTransferObject (or ViewModel) that provides a simple list of strings of courses (or a dictionary when you need IDs) for populating interfaces.

Difference between object and instance

I know this sort of question has been asked before, but I still feel that the answer is too ambiguous for me (and, by extension, some/most beginners) to grasp.
I have been trying to teach myself broader concepts of programming than procedural and basic OOP. I understand the concrete concepts of OOP (you make a class that has data (members) and functions (methods) and then instantiate that class at run time to actually do stuff, that kind of thing).
I think I have a handle on what a class is (sort of a design blueprint for an instance to be created in its likeness at compile time). But if that's the case, what is an object? I also know that in prototype based languages, this can muck things up even more, but perhaps this is why there needs to be a clear distinction between object and instance in my mind.
Beyond that, I struggle with the concepts of "object" and "instance". A lot of resources that I read (including answers at SO) say that they are largely the same and that the difference is in semantics. Other people say that there is a true conceptual difference between the two.
Can the experts here at SO help a beginner have that "aha" moment to move forward in the world of OOP?
Note: this isn't homework, I don't go to school - however, I think it would help people that are looking for homework help.
A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.
The truth is that object oriented programming often creates confusion by creating a disconnect between the philosophical side of development and the actual mechanical workings of the computer. I'll try to contrast the two for you:
The basic concept of OOP is this: Class >> Object >> Instance.
The class = the blue print.
The Object is an actual thing that is built based on the 'blue print' (like the house).
An instance is a virtual copy (but not a real copy) of the object.
The more technical explanation of an 'instance' is that it is a 'memory reference' or a reference variable. This means that an 'instance' is a variable in memory that only has a memory address of an object in it. The object it addresses is the same object the instance is said to be 'an instance of'. If you have many instances of an object, you really just have many variables in difference places in your memory that all have the same exact memory address in it - which are all the address of the same exact object. You can't ever 'change' an instance, although it looks like you can in your code. What you really do when you 'change' an instance is you change the original object directly. Electronically, the processor goes through one extra place in memory (the reference variable/instance) before it changes the data of the original object.
The process is: processor >> memory location of instance >> memory location of original object.
Note that it doesn't matter which instance you use - the end result will always be the same. ALL the instances will continue to maintain the same exact information in their memory locations - the object's memory address - and only the object will change.
The relationship between class and object is a bit more confusing, although philosophically its the easiest to understand (blue print >> house). If the object is actual data that is held somewhere in memory, what is 'class'? It turns out that mechanically the object is an exact copy of the class. So the class is just another variable somewhere else in memory that holds the same exact information that the object does. Note the difference between the relationships:
Object is a copy of the class.
Instance is a variable that holds the memory address of the object.
You can also have multiple objects of the same class and then multiple instances of each of those objects. In these cases, each object's set of instances are equivalent in value, but the instances between objects are not. For example:
Let Class A
From Class A let Object1, Object2, and Object3.
//Object1 has the same exact value as object2 and object3, but are in different places in memory.
from Object1>> let obj1_Instance1, obj1_Instace2 , obj1_Instance3
//all of these instances are also equivalent in value and in different places in memory. Their values = Object1.MemoryAddress.
etc.
Things get messier when you start introducing types. Here's an example using types from c#:
//assume class Person exists
Person john = new Person();
Actually, this code is easier to analyze if you break it down into two parts:
Person john;
john = new Person();
In technical speak, the first line 'declares a variable of type Person. But what does that mean?? The general explanation is that I now have an empty variable that can only hold a Person object. But wait a minute - its an empty variable! There is nothing in that variables memory location. It turns out that 'types' are mechanically meaningless. Types were originally invented as a way to manage data and nothing else. Even when you declare primitive types such as int, str, chr (w/o initializing it), nothing happens within the computer. This weird syntactical aspect of programming is part of where people get the idea that classes are the blueprint of objects. OOP's have gotten even more confusing with types with delegate types, event handlers, etc. I would try not focus on them too much and just remember that they are all a misnomer. Nothing changes with the variable until its either becomes an object or is set to a memory address of an object.
The second line is also a bit confusing because it does two things at once:
The right side "new Person()" is evaluated first. It creates a new copy of the Person class - that is, it creates a new object.
The left side "john =", is then evaluated after that. It turns john into a reference variable giving it the memory address of the object that was just created on the right side of the same line.
If you want to become a good developer, its important to understand that no computer environment ever works based on philosophic ideals. Computers aren't even that logical - they're really just a big collection of wires that are glued together using basic boolean circuits (mostly NAND and OR).
The word Class comes from Classification (A Category into which something is put), Now we have all heard that a Class is like a Blueprint,but what does this exactly mean ? It means that the Class holds a Description of a particular Category ,(I would like to show the difference between Class , Object and Instance with example using Java and I would request the readers to visualise it like a Story while reading it , and if you are not familiar with java doesn't matter) So let us start with make a Category called HumanBeing , so the Java program will expressed it as follows
class HumanBeing{
/*We will slowly build this category*/
}
Now what attributes does a HumanBeing have in general Name,Age,Height,Weight for now let us limit our self to these four attributes, let us add it to our Category
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
/*We still need to add methods*/
}
Now every category has a behaviour for example category Dog has a behaviour to bark,fetch,roll etc... , Similarly our category HumanBeing can also have certain behaviour,for example when we ask our HumanBeing what is your name/age/weight/height? It should give us its name/age/weight/height, so in java we do it as follows
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
public HumanBeing(String Name,int Age,float Height,float Weight){
this.Name = Name;
this.Age = Age;
this.Height = Height;
this.Weight = Weight;
}
public String getName(){
return this.Name;
}
public int getAge(){
return this.age;
}
public float getHeight(){
return this.Height;
}
public float getWeight(){
return this.Weight;
}
}
Now we have added behaviour to our category HumanBeing,so we can ask for its name ,age ,height ,weight but whom will you ask these details from , because class HumanBeing is just a category , it is a blueprint for example an Architect makes a blueprint on a paper of the building he wants to build , now we cannot go on live in the blueprint(its description of the building) we can only live in the building once it is built
So here we need to make a humanbeing from our category which we have described above , so how do we do that in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
}
}
Now in the above example we have created our first human being with name age height weight , so what exactly is happening in the above code? . We are Instantiating our category HumanBeing i.e An Object of our class is created
Note : Object and Instance are not Synonyms In some cases it seems like Object and Instance are Synonyms but they are not, I will give both cases
Case 1: Object and Instance seems to be Synonyms
Let me elaborate a bit , when we say HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90); An Object of our category is created on the heap memory and some address is allocated to it , and firstHuman holds a reference to that address, now this Object is An Object of HumanBeing and also An Instance of HumanBeing.
Here it seems like Objects and Instance are Synonyms,I will repeat myself they are not synonyms
Let Us Resume our Story , we have created our firstHuman , now we can ask his name,age,height,weight , this is how we do it in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
System.out.println(firstHuman.getName());
System.out.println(firstHuman.getAge());
...
...
}
}
so we have first human being and lets move feather by give our first human being some qualification ,let's make him a Doctor , so we need a category called Doctor and give our Doctor some behaviour ,so in java we do as follows
class Doctor extends HumanBeing{
public Doctor(String Name,int Age,float Height,float Weight){
super(Name,Age,Height,Weight);
}
public void doOperation(){
/* Do some Operation*/
}
public void doConsultation(){
/* Do so Consultation*/
}
}
Here we have used the concept of Inheritance which is bringing some reusability in the code , Every Doctor will always be a HumanBeing first , so A Doctor will have Name,Age,Weight,Height which will be Inherited from HumanBeing instead of writing it again , note that we have just written a description of a doctor we have not yet created one , so let us create a Doctor in our class Birth
class Birth{
public static void main(String [] args){
Doctor firstDoctor = new Doctor("Strange",40,6,80);
.......
.......
/*Assume some method calls , use of behaviour*/
.......
.......
}
}
Case 2: Object and Instance are not Synonyms
In the above code we can visualise that we are Instantiating our category Doctor and bringing it to life i.e we are simply creating an Object of the category Doctor , As we already know Object are created on Heap Memory and firstDoctor holds a reference to that Object on the heap ;
This particular Object firstDoctor is as follows (please note firstDoctor holds a reference to the object , it is not the object itself)
firstDoctor is An Object of class Doctor And An Instance of A class Doctor
firstDoctor is Not An Object of class HumanBeing But An Instance of class HumanBeing
So a particular Object can be an instance to a particular class but it need not be an object of that given class
Conclusion:
An Object is said to be an Instance of a particular Category if it satisfies all the characteristic of that particular Category
Real world example will be as follows , we are first born as Humans so image us as Object of Human , now when we grow up we take up responsibilities and learn new skills and play different roles in life example Son, brother, a daughter, father ,mother now What are we actually?We can say that we are Objects of Human But Instances of Brother,daughter,...,etc
I hope this helps
Thank You
Objects are things in memory while instances are things that reference to them. In the above pic:
std(instance) -> Student Object (right)
std1(instance) -> Student Object (left)
std2(instance) -> Student Object (left)
std3(instance) -> no object (null)
An object is an instance of a class (for class based languages).
I think this is the simplest explanation I can come up with.
A class defines an object. You can go even further in many languages and say an interface defines common attributes and methods between objects.
An object is something that can represent something in the real world. When you want the object to actually represent something in the real world that object must be instantiated. Instantiation means you must define the characteristics (attributes) of this specific object, usually through a constructor.
Once you have defined these characteristics you now have an instance of an object.
Hope this clears things up.
"A class describes a set of objects called its instances." - The Xerox learning Research Group, "The Smalltalk-80 System", Byte Magazine Volume 06 Number 08, p39, 1981.
What is an Object ?
An object is an instance of a class. Object can best be understood by finding real world examples around you. You desk, your laptop, your car all are good real world examples of an object.
Real world object share two characteristics, they all have state and behaviour. Humans are also a good example of an object, We humans have state/attributes - name, height, weight and behavior - walk, run, talk, sleep, code :P.
What is a Class ?
A class is a blueprint or a template that describes the details of an object. These details are viz
name
attributes/state
operations/methods
class Car
{
int speed = 0;
int gear = 1;
void changeGear(int newGear)
{
gear = newGear;
}
void speedUp(int increment)
{
speed = speed + increment;
}
void applyBrakes(int decrement)
{
speed = speed - decrement;
}
}
Consider the above example, the fields speed and gear will represent the state of the object, and methods changeGear, speedUp and applyBrakes define the behaviour of the Car object with the outside world.
References:
What is an Object ?
What is a Class ?
I think that it is important to point out that there are generally two things. The blueprint and the copies. People tend to name these different things; classes, objects, instances are just some of the names that people use for them. The important thing is that there is the blueprint and copies of it - regardless of the names for them. If you already have the understanding for these two, just avoid the other things that are confusing you.
Lets compare apples to apples. We all know what an apple is. What it looks like. What it tastes like. That is a class. It is the definition of a thing. It is what we know about a thing.
Now go find an apple. That is an instance. We can see it. We can taste it. We can do things with it. It is what we have.
Class = What we know about something. A definition.
Object/Instance = Something that fits that definition that we have and can do things with.
In some cases, the term "object" may be used to describe an instance, but in other cases it's used to describe a reference to an instance. The term "instance" only refers to the actual instance.
For example, a List may be described as a collection of objects, but what it actually holds are references to object instances.
I have always liked the idea that equals the definition of a class as that of an "Abstract Data Type". That is, when you defined a class you're are defining a new type of "something", his data type representation, in terms of primitives and other "somethings", and his behavior in terms of functions and/or methods. (Sorry for the generality and formalism)
Whenever you defined a class you open a new possibility for defining certain entities with its properties and behavior, when you instantiate and/or create a particular object out of it you're actually materializing that possibility.
Sometimes the terms object and instances are interchangeable. Some OOP purists will maintain that everything is an object, I will not complain, but in the real OOP world, we developers use two concepts:
Class: Abstract Data Type sample from which you can derive other ADT and create objects.
Objects: Also called instances, represents particular examples of the data structures and functions represented by a given Abstract Data Type.
Object Oriented Programming is a system metaphor that helps you organize the knowledge your program needs to handle, in a way that will make it easier for you to develop your program. When you choose to program using OOP you pick up your OOP-Googles, and you decide that you will see the problem of the real world as many objects collaborating between themselves, by sending messages. Instead of seeing a Guy driving a Car you see a Guy sending a message to the car indicating what he wants the car to do. The car is a big object, and will respond to that message by sending a message to it's engine or it's wheel to be able to respond properly to what the Driver told him to do in the message, etc...
After you've created your system metaphor, and you are seeing all the reality as objects sending messages, you decide to put all the things your are seeing that are relevant to your problem domain in the PC. There you notice that there are a lot of Guys driving different cards, and it's senseless to program the behavior of each one of them separately because they all behave in the same way... So you can say two things:
All those guys behave in the same way, so I'll create a class called
Driver that will specify who all the Drivers in the world behave,
because they all behave in the same way. (And your are using class based OOP)
Or your could say Hey! The second Driver behaves in the same way as the first Driver, except he likes going a little faster. And the third Driver behaves in the same way as the first Driver, except he likes zigzagging when he drives. (And you use prototype based OOP).
Then you start putting in the computer the information of how all the Drivers behave (or how the first driver behave, and how the second and third differ from that one), and after a while you have your program, and you use the code to create three drivers that are the model you are using inside that PC to refeer to the drivers you saw in the real world. Those 3 drivers that you created inside the PC are instances of either the prototype ( actually the first one is the prototype, the first one might be the prototype himself depending on how you model things) or the class that you created.
The difference between instance and object is that object is the metaphor you use in the real world. You choose to see the guy and the car as objects (It would be incorrect to say that you see them as instances) collaborating between themselves. And then you use it as inspiration to create your code. The instance only exists in your program, after you've created the prototype or the class. The "objects" exist outside the PC because its the mapping you use to unite the real world with the program. It unites the Guy with the instance of Driver you created in the PC. So object and instance are extremely related, but they are not exactly the same (an instance is a "leg" of an object in the program, and the other "leg" is in the real world).
I guess the best answer has already been given away.
Classes are blueprints, and objects are buildings or examples of that blueprint did the trick for me as well.
Sometimes, I'd like to think that classes are templates (like in MS Word), while objects are the documents that use the template.
Extending one of the earlier given examples in this thread...
Consider a scenario - There is a requirement that 5 houses need to be built in a neighbourhood for residential purposes. All 5 houses share a common construction architecture.
The construction architecture is a class.
House is an object.
Each house with people staying in it is an instance.