Objective C Terminology Help - objective-c

So I know a bit of C, trying to jump into ObjC for Max apps. Trying to figure out the terms and just needed a guru to humor me.
So an object could be thought of as a house that holds operations and data together.
But there may be many different objects of the same kind, called an instance. This could be thought of as a trailer park (manufactured home community) with a bunch of object homes. Not sure how to give an example of a type however.
Following same example, the methods would be the way the data in the house is manipulated?
Trying to figure these definitions out in a very simple example for my brain :)

It sounds more like you need some education on Object Oriented Programming in general rather than Objective-C specifically. Do some googling for general OOP references. Here's some basics referring to your specific question:
Object: A general term for a combination of data and related operations
Class: A specific definition of an object, i.e. NSController
Instance: A specific object created from a Class definition
So, I could have an object Controller1, that is an instance of the NSController class. This could be referred to as an "NSController object" or an instance of "NSController".

Stop using these analogies, just start playing around with tutorials and the code, you will get the hang of what everything does in no time.
In my words I would call methods a collective of instructions that you can call on with the given method name.
But really, just start writing code, the rest will come :) (no copy pasting!!)

What you're asking has little to do with Objective-C specifically, and everything to do with Object-Oriented Programming. Read up on that before diving into the new language!

I know this topic is quite old, but I thought I'd try and help out in case anyone is coming here looking for answers.
Object
Blueprint for a house. It has the plans for building a house, and it will even supply the contractors to build the house for you, but it is not the house.
Instance
This is a house. It also keeps track of all of the characteristics of the house, and as a result it can be introspective. IE: You can ask the house how many rooms it has, what its dimensions are &etc.
Method
Most every object will define methods. Methods do stuff. Following the house analogy, a method would be the mechanism that would grab the dimensions for you and print them out, or it could be something that would modify the state of the house. IE: call a plumber to fix a leaky pipe on the house.

Related

Non-object-oriented game tutorials

I've been tasked with writing an essay extolling the virtues of object oriented programming and creating an accompanying game to demonstrate them.
My initial idea is to find a tutorial for a simple game written in a programming language which does not follow the OOP paradigm (or written in an OOP language but not in an OOP way) and recreate it in an OOP way using either C# or Java (haven't yet decided). This would then allow me to make concrete comparisons between the two.
The game doesn't have to be anything complex; Tetris, Pong, etc. that sort of thing. The problem I've had so far is finding a suitable tutorial, any suggestions?
Let's say that you found source code for a game not in OOP. There are some OOP virtues that you can point out in your essay:
Organization.
Since a game has many tasks, it is a good idea to assign a responsibility to one class. This means write one class that keeps score, one class that does file access (reading and writing game state, for example), classes to represent your characters, etc. Otherwise, you will have one huge text file with thousands of lines of code. It would be a nightmare to even look at it, let alone find what you need and fix it.
Encapsulation.
This is grouping together properties and functions for better organization. We used to have a different array to store each property - (example) one array for aircraft names, one array for firepower, another array for top speed, etc. That sucks because you need to make sure that the same index across all those arrays actually describes the correct aircraft. It's better to create an Aircraft object and give it those property names. You'll then have one array that holds aircraft - no need to keep track of too many arrays.
Reusability.
As you write more games (and even other apps), you will come across the need to reuse classes. For example, you would use the same Card class in your Solitaire game as any card game you'll write in the future.
Polymorphism/Inheritance.
Say that you want to display each character - both heroes and villains in some sort of a grid. You will want both Hero and Villain to inherit Character. Character will have common properties and even a[n abstract] Display() function. You would then write the custom Display() function for Character and Villain (that access class-specific data for drawing). You then create an array of Character objects, and you may store either a Villain or Hero in each slot. When the game goes through that list to display, each item.Display() call will automatically pick the correct Display() function based on the Character's actual type. Try to do this without OOP and you'll end up with a long if-else (and probably even nested) statement and all drawing routines in one place.
That's just from the type of my head from experience in general programming that you can definitely apply in game programming. There are probably more OOP aspects than mentioned, so you may want to research. Best of everything for your essay!
You can try grabbing a (simple) TI-Basic game from TICalc, Omnimaga, or most other calculator programming websites and try to understand its code.
Try a BASIC game from this site:
http://www.atariarchives.org/basicgames/

Is a class that manages multiple classes a "god object"?

Reading the wikipedia entry about God Objects, it says that a class is a god object when it knows too much or does too much.
I see the logic behind this, but if it's true, then how do you couple every different class? Don't you always use a master class for connecting window management, DB connections, etc?
The main function/method may know about the existence of the windows, databases, and other objects. It may perform over-arching tasks like introduce the model to the controller.
But that doesn't mean it manages all the little details. It probably doesn't know anything about how the database or windows are implemented.
If it did, it could be accused of being a God object.
A god object is an object that contains references, directly or indirectly, to most if not all objects within an application. As the question observes, it is almost impossible to avoid having a god object in an application. Some object must hold references to the various subsystems: UI, database, communications, business logic, etc. Note that the god object need not be application-defined. Many frameworks have built-in god objects with names like "application context", "application environment", "session", "activator", etc.
The issue is not whether a god object exists, but rather how it is used. I will illustrate with an extreme example...
Let's say that in my application I want to standardize how many decimal places of precision to show when displaying numbers. However, I want the precision to be configurable. I create a class whose responsibility is to convert numbers to strings:
class NumberFormatter {
...
String format(double value) {
int decimalPlaces = getConfiguredPrecision();
return formatDouble(value, decimalPlaces);
}
int getConfiguredPrecision() {
return /* what ??? */;
}
}
The question is, how does getConfiguredPrecision figure out what to return? One way would be to give NumberFormatter a reference to the global application context which it stores in a member field called _appContext. Then we could write:
return _appContext.getPreferenceManager().getNumericPreferences().getDecimalPlaces();
By doing this, we have just made NumberFormatter into a god object as well! Why? Because now we can (indirectly) reference virtually any object in the application through its _appContext field. Is this bad? Yes, it is.
I'm going to write a unit test for NumberFormatter. Let's set up the parameters... it needs an application context?! WTF, that has 57 methods I need to mock. Oh, it only needs the pref manager... WTF, I have to mock 14 methods! Numeric prefs!?! Screw it, the class is simple enough, I don't need to test it...
Let's say that the application context had another method, getDatabaseManager(). Last week we were using SQL, so the method returned an SQL database object. But this week, we've decided to change to a NoSQL database and the method now returns a new type. Is NumberFormatter affected by the change? Hmmm, I can't remember... yeah, it might be, I see it takes an application context in the constructor... let me open the source and take a look... nope, we're in luck: it only accesses getPreferenceManager()... now let's check the other 93 classes that take an application context as a parameter...
This same scenario occurs if a change is made to the preferences manager, or the numeric preferences object. The moral of the story is that an object should only hold references to the things that it needs to perform its job, and only those things. In the case of NumberFormatter, all it needs to know is a single integer -- the number of decimal places. It could be created directly by the application god object who knows the magic number (or the pref manager or better still, numeric prefs), without turning the formatter into a god object itself. Furthermore, any components that need to format numbers could be given a formatter instead of the god object. Wins all around.
So, to summarize, the problem is not the existence of a god object but rather the act of conferring god-like status to other objects willy-nilly.
Incidentally, the design principle that tackles this problem head-on has become known as the Law of Demeter. Or "when paying at a restaurant, give the server your money not your wallet."
In my experience this most often occurs when you're dealing with code that is the product of "Develop as you go" project management (or lack there of). When a project is not thought through and planned and object responsibilities are loose and not delegated properly. In theses scenarios you find a "god-object" being the catchall for code that doesn't have any obvious organization or delegation.
It is not the interconnectedness or coupling of the different classes that is the problem with god-objects, it's the fact that a god-object many times can accomplish most if not all responsibilities of it's derived children, and are fairly unpredictable (by anyone other than the developer) as to what their defined responsibilities are.
Simply knowing about "multiple" classes doesn't make one a God; knowing about multiple classes in order to solve a problem that should be split into several sub-problems does make one a God.
I think the focus should be on whether a problem should be split into several sub-problems, not on the number of classes a given object knows about (as you pointed out, sometimes knowing about several classes is necessary).
Gods are over-hyped.

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.

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.

Objective-C newbie: Does anyone know of diagrams that explain class, objects and methods?

As you may have guessed from the question - I am right at the beginning of the Obj-C journey.
I'm hoping that someone out there knows of some diagrams that depict the relationship between classes, objects and methods - and that they're willing to share.
The problem I'm having is that just looking at code in a textbook doesn't completely explain it - for me at least.
Thanks for reading!
Regards,
Spencer.
No diagrams, but this is the tutorial I wish I'd read before I started:
http://www.cocoadevcentral.com/d/learn_objectivec/
Simple English, all the basic concepts.
Classes are just like classes in any language. They are descriptions.
Objects are like nouns. They are an instance of a class. That is, if you had a description of a generic book (the class) and you made a thesaurus based on that description, the thesaurus would be the object.
Methods are more or less functions. If the objects are nouns, then the messages are verbs.
[ScienceBook getTableOfContents]; //this would like return a table of contents.
Here, the object ScienceBook is being sent a getTableOfContents message (method). So now, the science book would theoretically find, format and return the table of contents to whom ever sent the message.
To some extent, diagrams may not be that helpful to answer the questions you present.
It may help to think of things like this:
A "class" provides the prototype or definition for some thing. For example, a "Person" or a "Car". A common synonym for "class" is "type".
An "object" is a concrete example or instance of a class. For example, you are an instance of "Person", and your car is an instance of "Car".
A "method" is a behavior, action or property of a class. However, a method is normally only meaningful in the context of an object. "Person" -> "Eat" is not meaningful, but "you" -> "Eat" is.
These are fundamental Object-Oriented concepts that are not specific to Objective-C. If you are interested in a general overview that is language-agnostic, I recommend "Object Thinking" by David West. Even though it's from Microsoft Press, it covers the concepts rather than any specific language.
I come from a fairly strong C++ background, but I can definitely remember when I started, I had a hard time grasping at the concept until I found a way to associate it with physical objects.
The word class and object you can use almost interchangeably. Think of an object as a container, like a bucket. The word bucket would be your "class". It is the name you give to the type of object you have.
A bucket has a certain purpose...to carry something. It might be water...or perhaps sand. So perhaps you want to fill the bucket. This would be something you do to the bucket, so in objective-c, this would be your method. You might write something like:
- (void) fillWith:(elementType)something;
So in this case, "something" might be something that represents and object you wish to fill your bucket with.
Your class might look like the following:
typedef enum items {
CRAYONS,
MARKERS,
SAND,
WATER } elementType;
#class Bucket {
elementType item;
}
- (void) fillWith:(elementType)something;
#end
Here's one link to some objective-c samples. Also try the apple development center.
If you're after information on Object Orientated Programming (ie the meaning of classes, objects, methods etc) then I'd advise against Objective-C. Objective-C on the Mac relies heavily on the Cocoa framework. The Cocoa framework is vast and performs a lot of 'magic' which will make it harder to understand the fundamentals of OOP.
An easier place to start would be a language used for web development. It's easier to get to the nuts and bolts of OOP with these languages.