7 ms·
Cargo-cult typing, or: Objective-C's default type is id
- deleted 13y ago[deleted]
- AlexanderDhoore 13y agoYou haven't actually explained why you think static typing is such a problem... `Id` is still there. Use it when you want. But if I want to call "setText:" on a UILabel and documentation says it needs an NSString... That's pretty handy.
- mpweiher 13y agoThe reason I haven't explained why static typing is such a problem is because I don't think it is, for example I agree with what you write. The problem is the stricter enforcement, which I explain near the end "A dynamic language": explorative programming, where you are still figuring out what exactly to do, has become much more onerous, widening the gap between Objective-C and other dynamic languages such as Ruby or Python. Previously, the compiler would warn you that you hadn't gotten the types yet, but as long as you were in the id subset (an extended subset, actually) that didn't matter and you could continue exploring until you got it right...and THEN write down all the types in order to have the positive effects of machine-checkable documentation. With the changes, this is no longer possible, so you have to alway juggle (a) the site of the client (b) the implementation of the method and (c) the header with the method. That gets old fast.
- Greenisus 13y agoI've been developing in Objective-C for years now and I didn't know you could declare a method without explicitly stating a return type. I imagine many other people don't know that either, so I'd argue that saying -(id)doSomething; is more readable. Now that I know, though, it has become syntactic noise for me.
- seanalltogether 13y agoIt seems though that if you're writing a book that is used as a documentation reference, you should be fitting with the coding standards that Apple uses for their own documentation. You would be hard pressed to find any framework header or apple doc that doesn't use -(id)mymethod
- mpweiher 13y agoWhy? (Hint: the book demonstrates that quite a few things that Apple recommends are, how shall I say it, not entirely optimal)
- seanalltogether 13y agoBecause Apple is constantly evolving the language, and you could genuinely find that they change the compiler to deprecate this "feature" down the road.
- coldtea 13y agoOr they could enforce this feature. Generally writing a book about a language, you should not be occupied with what a FUTURE version of a language noone has announced MIGHT be.
- deleted 13y ago[deleted]
- bennyg 13y agoOr you could write idiomatic Objective-C and maybe save a chapter or section for being clever.
- kenferry 13y agoWell that was a tease. :-) Any examples?
- mpweiher 13y ago
- slavoingilizov 13y agoStatic typing is easy for newbie developers. It sets hard boundaries, and when you remember those rules, it's easy to follow what the code does. You don't have to step through it in your head and think about it much to figure it out. With that said, I think Apple are pushing the language in that direction, because recently everyone started developing for iOS, even people who didn't program at all. Apple is trying to make it easy for them. I see nothing wrong with that. It may not be the best from a programmer viewpoint, but I can understand it. P.S. I think this is why Microsoft has embraced static typing throughout its developer ecosystem. It makes learning from scratch much easier and developers (although not very experienced ones) flock to your platform. Of course this same thinking created ASP.NET and shortened the lives of many good men. But you cannot judge them, really.
- bsaul 13y agoI really don't see how static typing can be associated to "newbie" coding in any way. Haskell, Golang, Ocaml, and even Scala, clearly aren't aimed at newbies "let's code an app cause that's cool" kind of developers, and they both embrace static typing. The only reason i see why you wouldn't want the "compiler" to understand what data structure your function is accepting or returning is when this data structure is far too complex to be represented as a single type in a meaningful way (such as json deserialization returning "Array Or Dictionary" kinds of types). But apart from that, i can only see advantages in terms of IDE assist (autocompletion, refactoring), code clarity and safety.
- chc 13y agoI think what slavoingilizov is that it makes it easier for companies to make use of inexperienced programmers, not that it helps non-programmers get up and running quickly. The additional automatic checks and IDE assistance enabled by static analysis can help partially paper over a novice's shortcomings.
- to3m 13y agoEasily comprehensible code? Hard boundaries, and the ability to figure out what the code does without having to mentally step through it? Perhaps you can even click a button when the cursor is on an identifier, and be taken to the definition of the entity of that name, or the small subset of possible entities of that name that this identifier could refer to? Possibly the computer could check your work without your even having to run it, and actually prove that certain types of error cannot possible occur? That actually sounds really helpful and I'm not sure why people don't embrace it. (One point you do make that is quite correct is that static typing is helpful for novices. And yet so many languages designed for beginners' use try to make things "easier" by turning typos into new variables, letting variables switch type, and generally poking their user in the eye. Never figured this one out - though I suppose this is good training for the novice programmer, because programming is such a straightforward activity and without having the language itself to keep them on their toes they might find it insufficiently exacting, not demanding enough, and requiring basically nothing in the form of concentration, thought and precision.)
- chc 13y agoThis article is technically correct, which I'm told is the best kind of correct. However, it's also missing the forest for the trees. It is true that we can omit id and still satisfy the compiler. This is the same way that we can leave out the int type in C function declarations, or completely leave out function declarations altogether if we're dealing only in ints. In both cases, though, nobody does this — and if you do this, your code will read as a mistake to anybody who has read any other Objective-C code from the past decade. We include these "extraneous" types not for the compiler, but to make our intentions clear to the reader. This is the same reason many people and style guides use one-line compound statements or typedefs that make the token longer but more descriptive — at the same time we sacrifice a little brevity, we also sacrifice ambiguity. It probably isn't always true that explicit is better than implicit, but it's a very good rule of thumb. If you have to choose one for a default mode, "explicit" is definitely the better choice. As for the larger point about dynamic types, I and a lot of other old-timey Objective-C programmers felt the same way. It seems to me that powerfully dynamic languages like Smalltalk are good, and powerfully static languages like OCaml are good, but C's type system is just anemic and more bureaucratic than anything else. However, in practice, all these static facilities in Objective-C have proven really useful for writing real programs. The static analyzer can catch all sorts of errors. A combination of very consistent conventions and sophisticated static constraints has even allowed memory management to be handled for us completely through static analysis — that is just amazing, and the benefits of being rid of that responsibility are huge. Apple keeps moving in the static direction because those are the additions that Objective-C programmers are finding useful in practice. I agree, the more loosey-goosey dynamic and implicit style works better for exploratory programming. I'll sometimes write spikes that way. But a book teaching how to write code in the language is not a throwaway spike solution, and in that environment you should either explicitly tell readers you're teaching them a style that nobody else uses in production code or — and this is my preference — just write idiomatic code.
- McUsr 13y agoI agree totally. I must say, that I have seen typeless declarations in code, but I do find them to be a nuisance. Adding (id) to a declaration isn't really that hard, and makes the code a lot more radable. Why raise the treshold for the ability to read Objective-C?
- deleted 13y ago[deleted]
- vor_ 13y ago- (id)foo tells me that the method returns an object rather than simply performs an action. The article doesn't explain why this makes Objective-C harder or less fun. It reminds me of the anal-retentive complaints from long-time NeXTStep developers that I used to see on the Objective-C mailing list before I unsubscribed. Those guys don't even want you saying "call a method" instead of "send a message".
- chc 13y ago-foo would just as definitively indicate that it returns an object. The return type defaults to id, not void. Also, the "call a method"/"send a message" distinction is useful. I don't usually criticize people for using the "method call" terminology, but I almost always use the latter since the idea of messages is central to a lot of Objective-C idioms (e.g. the responder chain in Cocoa). It's helpful to think in terms of messages.
- mikeash 13y agoHow is the call/send distinction useful, exactly? You call a method by sending a message. When you send a message, it calls a method. They're two aspects of the same thing, and using one rather than the other never gives you any additional information.
- chc 13y agoForwarding and dynamic resolution make the relationship between a message send and a method call less than completely straightforward in Objective-C. You do ultimately end up calling some method, but it's not necessarily the method you think you're going to call. I mean, remember: Roughly every Cocoa program in existence routinely calls an unknown method of an unknown object by sending a known message to a known object and having the objects work it out amongst themselves (like I mentioned earlier, the responder chain). Beyond that, I find that mentally framing your program as objects sending messages to each other and responding as they see fit just leads more naturally to good OO designs. It implies a lack of coupling that is absent from the semantics of a "method call."
- seivan 13y agoYou could always use instancetype to indicate that you're getting an instance of the class back. @interface NSArray (XXHelpers) -(instancetype)reverse; @end or even better @protocol XXReversing <NSObject> @required -(instancetype)reverse; @end @interface NSArray (XXHelpers) <XXReversing> @end @interface NSOrderedSet (XXHelpers) <XXReversing> @end
- overcyn 13y agoThis is equivalent to the semicolons in javascript debate. Pointless bike-shedding. You save 4 characters, big deal.
- jayvanguard 13y agoI agree. Putting in the id return or not is irrelevant. I also think his larger point is important though. The general trend towards more explicit typing being the default is a move away from Objective-C's Smalltalk roots and this is a bad trend. I suspect it is somewhat influenced by Java programmers invading the Objective-C space and spreading their rigid typing, pattern-itis cancer.
- mpweiher 13y agoYou are right about your suspicion. In fact, one of the central characters came out an flatly stated that Java was a better language. He had a hand in the "modern syntax" (anyone remember that?), property dot notation and the GC implementation that ultimately failed. He also once said to me that Objective-C being a statically typesafe language was a fact that could not be argued about. Hmm. Also agreed that whether the (id) is there or not doesn't matter (much). I myself have been happily reading over it without really noticing for upwards of two decades now. What bugs me is the claim that it has to be there.
- mpweiher 13y agoThanks for the feedback. I thought I was fairly clear in the article that I don't really care whether you add the (id) or not, as long as you know why you are doing it, but it appears I wasn't. I've amended the article to be better about this. If you think it increases readability for you, OK. If you want to conform to whatever Apple recommends, OK. What worries me is that apparently (the discussion confirms this), Apple has managed to push the notion that there always have to be types, that Objective-C is not an optionally statically typed language. Both parts of "optionally statically typed" are useful, the static typing and the fact that it is optional.
- btown 13y agoI'd argue that typing (id) explicitly is actually good, because it gets the programmer and any readers of the code in the habit of seeing that there is a space to notate return types. Lowering the cognitive barrier to static typing can only be a good thing.
- dasil003 13y agoThe semicolon debate is even more substantive because that potentially leads to real bugs of the difficult-to-debug variety.
- krazydad 13y agoThe more vociferously a language-feature is debated on Hacker News, the less it matters.
- wsc981 13y agoSomewhat unrelated ... I wish Apple would add local type inference to Objective-C, perhaps using the existing id type or some keyword like var in C#. It would make the code so much more quicker to write, less verbose, a bit easier to change. I mean reading and writing something like: var color = [UIColor green]; var viewController = [[MyViewController alloc] initWithBackgroundColor:color]; Is so much more pleasant as: UIColor *color = [UIColor green]; MyViewController *viewController = [[MyViewController alloc] initWithBackgroundColor:color];
- mpweiher 13y agoYou could just write: id color = [UIColor green]; id viewController = [[MyViewController alloc] initWithBackgroundColor:color]; The UIColor* is largely there for your benefit, for the compiler it makes hardly a difference (pre ARC). If you don't find it a benefit, just leave it out.
- nextstep 13y agoSounds like this guy wishes Objective-C was Smalltalk with C-syntax.
- mikeash 13y agoWell, it pretty much is.
- nextstep 13y agoNo, it's not. That's what this guy is complaining about. Objective-C is dynamically typed, but allows for static typing; Smalltalk is always dynamically typed.
- mpweiher 13y agoIt's not Smalltalk with C syntax. It's C with C Syntax and an object system with Smalltalk syntax smashed together. It is having both that is the beauty of it, in more ways than one. Very expressive high level code and low-level bit banging when you need it. Dynamic, explorative programming that can be hardened to stricter typing regimes once a design stabilizes. What I am complaining about is not just that this duality seems to be getting lost, but that it is lost by apparently combining the worst of both worlds, the expressiveness and rigidity of statically typed language and the performance of a dynamic language. And what's worse, it appears that it's being done without even a conscious decision, but more by drifting aimlessly, picking up features and practices more or less haphazardly.
- jcizzle 13y agoYou can also define methods without labels: - (void):(int)arg :(int)anotherArg :(int)someArg { NSLog(@"%d %d %d", arg, anotherArg, someArg); } [self:1:2:3]; Try it. It compiles. It runs. How great is that? In fact, even Apple has done this! + (id)functionWithControlPoints:(float)c1x :(float)c1y :(float)c2x :(float)c2y; So does this make this the best option? Should we even name our methods? Of course, that is silly. Naming our methods appropriately tells us a lot. It means we don't have to check the documentation as much, which means we can effectively write faster. We're communicating with our code and our teammates more efficiently. The same holds true for explicitly typing method return values. So ask yourself this: what's the default storage mechanism for a property, assign or strong? Now what was it when ARC first was developed? That's right, it was different. So you could see how someone might be confused reading your code if you weren't explicit. They might spend time looking in the wrong places for a bug. So why not be explicit? It's not about you, it's about everyone else who is left with your code. So Brad Cox doesn't explicitly type his returns. Neither did Nextstep sometimes. That was 20+ years ago. We didn't have fancy IDEs with autocomplete; keystrokes were a luxury. That's probably why they couldn't put the 'e' on 'creat' in libc. Last couple of Objective-C articles making it to the top of Hacker News have been bad. Just a kind warning to any budding Objective-C developers: just because it made it onto Hacker News doesn't make it good.