Why the different NSFileHandle flavors and how are they implemented? - objective-c

Relatively new to Cocoa here.
This question is about NSFileHandle, but I got a feeling the answer may be relevant in a broader Cocoa programming context.
I'm just wondering:
why there are different NSFileHandle constructor flavors (ie: one each for reading, writing and both).
how the control of access to these file manipulation functions is implemented, especially given that all of these constructors return generic (id) that don't give away at all whether they are of R/W/RW type.
Thanks!

1) Because on most operating systems (Mac OS X/iOS included), reading and writing are two separate operations, and a file handle that can do one is generally not able to do the other (unless explicitly opened with both access types.)
2) We don't know how NSFileHandle is implemented. :) Or maybe we do know, but it's an implementation detail, so even if we know we should pretend we don't.

Related

Deciding extent of coupling

I have a Component which has API exposed with some 10 functionality in all. I can think of two ways to achieve it:
Give out all these functionality as separate functions.
Expose only one function which takes an XML as input. Based on request_Type specified and the parameters passed in the XML, I internally call one of the respective functions.
Q1. Will the second design be more loosely coupled than the first ?
I always read about how I should try my components to be loosely coupled, should I really go to this extent to achieve lose coupling ?
Q2. Which one of these would be a better design in terms of OOP and why?
Edit:
If I am exposing this API over D-Bus for others to use, will type checking still be a consideration to compare the two approaches? From what I understand type checking is done at compile time, but in case when this function is exposed over some IPC, issue of type checking comes into picture ?
The two alternatives you propose do not differ in the (obviously quite large) number of "functions" you want to offer from your API. However, the second seems to have many disadvantages because you are loosing any strong type checking, it will become much harder to document the functionality etc. (The only advantage I see is that you don't need to change your API if you add functionality. But at the disadvantage that users will not be able to figure out API changes like deleted functions until run-time.)
What is more related with this question is the Single Responsiblity Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle). As you are talking about OOP, you should not expose your tens of functions within one class but split them among different classes, each with a single responsibility. Defining good "responsibilities" and roles requires some practice, but following some basic guidelines will help you to get started quickly. See Are there any rules for OOP? for a good starting point.
Reply to the question edit
I haven't used D-Bus, so this might be totally wrong. But from a quick look at the tutorial I read
Each object supports one or more interfaces. Think of an interface as
a named group of methods and signals, just as it is in GLib or Qt or
Java. Interfaces define the type of an object instance.
DBus identifies interfaces with a simple namespaced string, something
like org.freedesktop.Introspectable. Most bindings will map these
interface names directly to the appropriate programming language
construct, for example to Java interfaces or C++ pure virtual classes.
As far as I understand, D-Bus has the concept of differnt objects which provide interfaces consisting of several methods. This means (to me) that my answer above still applies. The "D-Bus native" way of specifying your API would mean to exhibit interfaces and I don't see any reason why good OOP design guidelines shouldn't be valid, here. As D-Bus seems to map these even to native language constructs, this is even more likely.
Of course, nobody keeps you from just building your own API description language in XML. However, things like are some kind of abuse of underlying techniques. You should have good reasons for doing such things.

What's the point of creating classes at runtime in Objective-C?

I've recently reread the interesting tutorial from Mike Ash about How to create classes at Objective-C Runtime
I has been a long time I am wondering where to apply this powerful feature of the language. I always see an overkill solution to most of the ideas that come to my mind, and I eventually proceed with NSDictionary. What are your cases of use of creating classes at runtime? The only one I see is an Obj-C interpreter... More ideas?
There's some possible options I see, when someone need to create class in runtime
To hide information about it (It won't help in most cases, but... you can)
To perform multiple-inheritance (If you really need it :)
Using your own language(i.e. some XML-like), that can be interpreted by your program, writted in Obj-C (Something like NSProxy, but even better.)
Creating some Dynamic-Class that can change it's behavior in runtime
In general.. There is some possible usages of this. But in real world, in default service applications there's no need to do this, actually:)
It could be used for example along Core Data or any API related to a database to create new classes of objects unknown at compilation time. However, I doubt this is used often, it's mostly the mechanism the system uses itself when it runs a program...
KVO, in the Cocoa frameworks, is implemented by dynamically creating "notifying" versions of your classes. See http://www.mikeash.com/pyblog/friday-qa-2009-01-23.html

OOP vs procedural in run-time

I have very simple question I cant find answer anywhere on the internet.
So, my question is, in procedural programming, code is in code section, which goes into Read Only memory area. Variables are either on stack or heap.
But OOP says that object are created in memory. So, does it mean even functions are written into R/W memory area?
And, does Os have to have some inbuilt OOP programs support? For example if OS doesent allowed to read instruction outside Read only code section. Thanks.
Generally, both OOP and procedural programming are abstractions which exist only at the source-code level. Once a program is compiled into executable machine-code, these abstractions cease to exist. So whether or not a particular language is OOP or procedural has no bearing on what regions of memory it uses, or where instructions are placed during execution.
The OS itself usually doesn't know or care whether a particular executable was written in an OOP or procedural language. It only cares that the executable uses binary op-codes compatible with its native instruction set, and that the executable has an ABI (binary interface) that it understands.
This is a good question.
Whereas as object constitutes functions and data as being placed in the same spot theoretically, most implementations split it. The way you do it, is that code is split out and stored into the RO segment. An object in the RW area then have a way to refer back to that code in the RO area. The coupling of code and data is only used conceptually by the human programmer and the type checker to ensure that you do not violate the rules and principles.
A Java/C#-like language will usually be made such that each object has a tag identifying the type of the object. The object itself is simply a struct containing all the fields laid out in a prespecified order. This tag can then be used to look up which function in the RO-area to call. The function in the RO-area is altered to take an extra parameter, called this or self through which the contents of said object can be reached. When the method needs to refer to fields, it knows the pre-specified order, so it can do that correclty. Note that there are some tricks needed to solve inheritance, but this is the crux of the idea.
A Python/Ruby-like language will usually make an object be a hash-table where a method is a pointer to the code in the RO-area (provided that the language is compiled and not run through a bytecode interpreter). Function calls are made by looking up the hash-table contents and following the code pointer. Fields are also looked up in the same hash table.
With those basics down, most implementations make tricks to avoid the part where a pointer is followed to find the function to call. They try to figure out and narrow down the possible call to a single function. Then they can replace the lookup with a direct call to the right function, a much faster solution.
the tl;dr version: The language semantics views fields and methods as part of an object. The implementation split them into RO and RW segments. As such no OS support is needed.
OOP doesn't say this. I have no idea where you read it, if you add a quote that would help.
Objects are variables, so what you know about variables is correct for objects. In languages like C# (.net framework actually) objects can only be stored in heap, because they are so called reference types. In C++ they can live anywhere.
But OOP says that object are created in memory. So, does it mean even functions are written into R/W memory area?
From this i concluded that you think that functions are objects. That is true in far not every OOP language. It is from functional languages where functions are first class objects. Functions are in majority of cases immutable and are placed in read only sections.
Common OSes like Windows, Linux and MacOsx are unaware of objects. This is purely program concept. .net framework and java vm provide layer of abstraction. They are execution environments that have build in object support.

Too much C-Style in Objective-C programs?

Hi I'm writing this question because I'm a newbie in ObjC and a lot of doubts came to my mind when trying to make my fist training app. The thing is that I have a strong background in C, I've been programming in Java for the last year and I've done some collage stuff with Smalltalk (I mencione this because those are my programming references and those are the languages I'm comparing ObjC with).
The first problem I've encountered is that I don't know where to draw a line between ObjC and C, for example when dealing with math operations, Should I use math.h or there is a more "object-way" like you can do in Smalltalk (aNumber raisedTo: 3) ? How does a person with no background at all in C learns ObjC?.
Another thing that I couldn't find was a collection's protocol (I've looked over the Foundation Framework documentation given by Apple). Because I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Smalltalk or Java) or I gotta check by hand every collection and see if there is a cool method that my new collection should have.
I don't know if I'm being too stupid or I'm searching for features that the language/framework doesn't have. I want to program in ObjC with the ObjC style not thinking in C, Java or Smalltalk.
Sorry if the question was too long.
Absolutely use <math.h>. You don't way to pay message sending overhead for functions that run in 30 cycles. Even function call overhead seems pretty steep at that point.
More generally, use as much or as little of C-style as you want to. I've seen Objective-C that was nothing but a couple C modules glued together with objective C messages, and I've seen Objective-C that essentially zero lines of code without the square brackets. I've seen beautiful, effective code written both ways. Good code is good code, however you write it.
In general, you'll use C features for numerical calculations. You'll generally use objects for most other things. The reason for this is that objects are way heavier than a simple scalar — there's just no benefit to it. Why would you ever write [[NSNumber numberWithInteger:1] numberByAddingNumber:[NSNumber numberWithInteger:2]] when you can just write 1+2? It's not only painful to read, it's far slower and it doesn't gain you anything.
On the other hand, Cocoa has rich object libraries for strings, arrays, networking and many other areas, and using those is a big win.
Knowing what's there — and thus what the easiest way to do something is — is just a matter of learning. If you think something should be there and you can't find it, you can ask either here or on Apple's Cocoa-Dev mailing list.
As for a collection protocol — there really isn't one. The closest thing to it is the NSFastEnumeration protocol, which defines precisely one method: countByEnumeratingWithState:objects:count:. This lets you use the for (id someObject in someCollection) syntax to enumerate the objects in a collection. Otherwise, all the collections define their own independent interfaces.
The first problem I've encountered is that I don't know where to draw a line between ObjC and C.
My rule is to use C wherever it makes sense to you. Objective-C has the benefit of letting you choose when to be procedural and when to be object-oriented. Go with what fits best with the code you're writing.
Another thing that I couldn't find was a collection's protocol [...] I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Java) or I gotta check by hand every collection and see if there is a method that my collection should have.
Unlike Java, Objective-C does not have a master protocol for collections like the java.util.Collection interface. Also, there aren't a proliferation of specific container implementations as in Java. However, that gives you the freedom to implement a collection in a way that makes sense for your code.
For building a tree-like structure, you might take a look at NSTreeNode to see if it might be useful to leverage. (It may be more than you're need or want, but might be worth a shot.)
As far as rolling your own collection, I've learned a lot while creating CHDataStructures.framework, and you're welcome to use whatever you like from that code, or just look at my attempts at creating Cocoa-like structures, designed to complement the Foundation collections and operate similarly. Good luck!
Try to use each language for what it's good at. IMHO, this would include Obj-C objects but C-like code implementing methods. So use math.h and concise C code to implement logic, but don't be shy about using Obj-C classes to organize your larger blocks of functionality into something that makes sense.
Also, try to interact with the frameworks using their style so you're not running upstream.
As has been mentioned, there’s no real protocol for abstract collection classes (aside from the NSFastEnumeration protocol which provides the for(id item in collection) syntax when implemented), but there are conventions to follow.
Apple’s Introduction to Coding Guidelines for Cocoa covers some of this, and there is in fact a section on naming collection methods which covers the general cases (though note that generic container classes such as NSArray use the term “Object” as opposed to “Element” listed in the examples there – i.e. addObject:, removeObject:, and so on).
Following the patterns listed here (among others) is actually crucial when you want your classes to be KVC-compliant, which allows other users to observe changes in your object’s properties.

Could you imagine any other way to have OO implemented than the classic class-based approach?

I've lately been thinking a lot about alternatives to the class-based approach to object-orientation.
One thing which bugs me in today's languages is that we often use static classes / singletons to design single (global) objects because there isn't any other way to do it, so in my opinion it's rather a hack than a feature.
Another thing is that Java for instance allows the programmer to have enums with additional data (global state) and functionality which make them kind of object in my eyes, too.
Anyway, what I'd like to know is whether you have any ideas for a different approach to object-orientation in a compiled and efficient language (therefore, creating objects by prototyping is probably not a good idea) or, if you don't have any, whether there're things in the classic OO approach which bug you a lot, too.
[EDIT]:
Just to make things clear. As indicated above I already know prototype-based programming.
Check out prototype-based programming.
Take a look at the Actor Model. It's something like classes except for being asynchronous. If each actor is a Finite-State-Machine, you would have a potentially powerful system.
Erlang uses something like that, I'm told... at least similar. The point with the actor model is that it doesn't need to be implemented purely, and so does not need to be part of Erlang.
I started a small language that used that model once a few years ago. I might try it again sometime.
Now that my flame retardent suit is safely secured, I can say it: I dislike OOP.
The central problem I have with it is that it tries to come up with a single taxonomy in which every unit of functionality truly belongs.
There are a couple of problems with this. First, producing a good taxonmy is hard. People suck at creating them. Secondly, I am not convinced that you can actually structure a sensible, maintainable, hierarchy that will withstand change in a project containing a lot of entities; the whole practice of refactoring is basically acknowledging the difficulty of creating large, all incompassing taxanomies.
Actually, I think that OOP is over-engineered. Everything you can do with OOP can be done with higher-order functions (HOFs). HOFs are much more elegant, much more flexible solution to the same problems that OOP tries to address.
So if you're asking of another way to do OOP style stuff, HOFs are probably the closest alternative technology that has a similiar level of flexibility.
I think you are having trouble defining the "classical OO" approach. Is the signal method in Objective-C classical or the static method in standard C++?
In functional languages, it's easy enough to have non-object functions that, in a sense, act like objects because they return functions whose implementations are opaque. For example, the following code in Scheme
(define (create-ball color)
(lambda (attribute-name)
(if (equal? attribute-name "color")
color
"method-not-supported"))))
will output a function which isn't officially an "object" but it can act like one since it stores state, but you're not very clear about what exactly is wrong with the object-oriented paradigms you have been exposed to.
take a deep look at javascript which has the prototype based model or check out lua which has a some strange way to implement object orientation
Take a look at CLOS, which is basically function/method based.
Google's Go language takes a decidedly different approach to object orientation, maybe worth a look.