http://feeds.boingboing.net/~r/boingboing/iBag/~3/l6Rl-x22u3c/story01.htm "developers who worked on Ultima Online [...] are creating a game called Shards Online over which players will have enormous control. Players will be able to run their own servers, change the code that the game runs on, and add their own challenges. The internal logic of this is a game set in a multiverse[...]"
http://feeds.boingboing.net/~r/boingboing/iBag/~3/yVN83zKFBA4/story01.htm "re-re-launched Amazing Stories, the very first science fiction magazine, founded 88 years ago by Hugo Gernsback. Through the month of April, they'll publish fiction and features, which will be collected as an ezine at the end of the month."
http://matociquala.tumblr.com/post/81284926274/everythingsbetterwithbisexuals-lucymontero "Mary Bowser, former slave of the Van Lew family, infiltrated [...] the household of Jefferson Davis. Bowser was assumed to be illiterate, and as a black woman was below suspicion. Practically invisible, she was able to listen to conversations between Confederate officials and read sensitive documents, gathering information that she handed over to the Union. (From National Woman’s History Museum Facebook Page)"
funny http://cheezburger.com/8129159936?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+SetPhasersToLol+%28Set+Phasers+To+LoL%29 "It's a Love/Rob Situation..." "He used to rob me three times a week, now I'm lucky if I get it once a month..."
C. Keith Ray
C. Keith Ray writes about and develops software in multiple platforms and languages, including iOS® and Macintosh®.
Keith's Résumé (pdf)
Keith's Résumé (pdf)
Monday, March 31, 2014
Link Blogging
http://www.neat.io/blog/app-developer-vs-seo.html "[three pages] shared the same common template and content." "these three pages (the most important pages to rank for due to their specificity), were not being ranked very highly on Google. Turns out search engines don't like duplicate content and heavily penalise your site for it" "Links which are in bold are also given more weight so each link to a service page is wrapped in strong tags" "Understanding how search engines crawl pages and how they interpret the semantic structure of your pages was eye-opening."
Two "Magnificent Seven" blogs today:
Two "Magnificent Seven" blogs today:
- http://feeds.boingboing.net/~r/boingboing/iBag/~3/iFXG2dI8ueA/story01.htm "Podcast: Collective Action - the Magnificent Seven anti-troll business-model" "The reason the victims [of patent trolls] don’t get together to fight back is that they don’t know each other and have no way to coordinate among each other. In economists’ jargon, they have a ‘‘collective action problem.’’"
- http://agiletng.org/2014/03/21/the-seven-samurai/ "A pattern language for enterprise agile transformation" "Continuous Assessment: Motivate Agile in terms of bottom line metrics." etc.
http://boingboing.net/2014/03/31/google-maps-spam-problem-pre.html "Google Maps' spam problem presents genuine security issues" "a Microsoft Engineer demonstrated an attack against Google Maps through which he was able to set up fake Secret Service offices in the company's geo-database, complete with fake phone numbers that rang a switch under his control and then were forwarded to real Secret Service offices, allowing him to intercept and record phone-calls made to the Secret Service" "this is a higher-stakes version of a common spam-attack on Google Maps practiced by locksmith, carpet cleaning, and home repair services" "Google’s basically getting a not insignificant amount of their income from scammers—if you look at locksmiths, 99 percent of them are scammers,” says Austin"
Repels the Cable-Chewing Cat
American Terminal SL250-100 1/4-Inch Split Loom Tubing, 100 feet "One of my cats likes to chew on cables -- particularly expensive ones belonging to Apple products. I've used this product to cover many of my cables, starting at least a year ago, and I haven't seen any evidence that my cat has chewed on them. So, I guess they work!"
Getting this tubing over the cables isn't easy, but you only have to do it once (per cable)."
Link Blogging
I am going to post links to "interesting" articles I encounter, with a short quote and/or tiny amount of explanation. Sometimes a short quote or explanation will be too long to tweet, and I don't want to fill my tweet streams with a hundred links per week.
http://letsworkshop.com "Workshop is a daily newsletter and community delivering the best freelance opportunities to your inbox" "100% freelance-friendly leads" 10 leads/day = $64/month 5 leads/day = $99/month
http://www.cheryl-morgan.com/?p=18787 "Origins of Feminist Transphobia" by Cheryl Morgan "Back in the 1970s, being a radical feminist often meant being a lesbian separatist..." "read Suzy McKee Charnas’s Holdfast Chronicles [which goes into lesbian separatism in depth]" "for lesbian separatists the idea of a lesbian trans woman can be even more horrifying, because it leads to thoughts of people who are “really men” stealing their girlfriends."
http://qualitycoding.org/xcode51-code-coverage/ "Code Coverage Fixed for Xcode 5.1" "The Xcode 5.1 update proved to be more exciting than I anticipated. And I mean “exciting” in the sense of “breaking the tools I use.” xctool stopped working, and so did my code coverage scripts." "go get the latest XcodeCoverage to get up & running again on Xcode 5.1. Enjoy"
http://buzzsumo.com/blog/pitch-journalist-tips-techcrunch-ny-times/?utm_source=hootsuite&utm_campaign=hootsuite "How To Pitch to Journalists: Expert Tips From Techcrunch, NYT and more" "I am appalled by how lazy PR people are and completely fed up with the BS they keep sending me."
http://letsworkshop.com "Workshop is a daily newsletter and community delivering the best freelance opportunities to your inbox" "100% freelance-friendly leads" 10 leads/day = $64/month 5 leads/day = $99/month
http://www.cheryl-morgan.com/?p=18787 "Origins of Feminist Transphobia" by Cheryl Morgan "Back in the 1970s, being a radical feminist often meant being a lesbian separatist..." "read Suzy McKee Charnas’s Holdfast Chronicles [which goes into lesbian separatism in depth]" "for lesbian separatists the idea of a lesbian trans woman can be even more horrifying, because it leads to thoughts of people who are “really men” stealing their girlfriends."
http://qualitycoding.org/xcode51-code-coverage/ "Code Coverage Fixed for Xcode 5.1" "The Xcode 5.1 update proved to be more exciting than I anticipated. And I mean “exciting” in the sense of “breaking the tools I use.” xctool stopped working, and so did my code coverage scripts." "go get the latest XcodeCoverage to get up & running again on Xcode 5.1. Enjoy"
http://buzzsumo.com/blog/pitch-journalist-tips-techcrunch-ny-times/?utm_source=hootsuite&utm_campaign=hootsuite "How To Pitch to Journalists: Expert Tips From Techcrunch, NYT and more" "I am appalled by how lazy PR people are and completely fed up with the BS they keep sending me."
"Pitching to a journalist isn’t rocket science. Assuming you have a compelling story, make sure you follow these simple tips:
- Don’t use buzzwords like “disruptive”
- Don’t write long introduction – cut to the chase.
- Make sure it’s relevant to the journalist.
- Make it short and sweet (lean and impactful)
- Tailor your pitch to each journalist
- Answer the question: Why does this matter today?"
Wednesday, March 5, 2014
Microblogged on Twitter
By the way, I recently micro-blogged a series of "straw-man" arguments against, and rebuttals for, unit-testing and TDD. Here they are somewhat expanded. Rebuttals are italic.
I am NOT making up these straw-men arguments. I’ve even heard them from people who should, 14 years after Extreme Programming Explained was published, have some understanding of incremental design and development, who should know both the differences and similarities between TDD and unit testing, and how refactoring fits into both small and big design activities.
1. straw-man: OO means you can't know what modified something's state.
That sounds like a global var bug. Objects can guard their state. Most people could learn a bit more about designing non-mutable classes, but OO doesn’t prevent you from knowing an object’s state.
2. straw-man: Always-passing tests are useless.
Yes, tautological tests are useless. Don't do that. You learn something when a rarely-failing unit test fails: something unexpected happened! Either some code (or data) has changed and it now violates a test’s description of how that code (or data) is supposed to work, or the programmers forgot to update their tests. If a test that has been passing for 10 months suddenly fails, you know something is wrong. The worser condition is that no problem is detected until 20 months have passed, and you have to trace changes back to 10-month old code to find out what code-change caused the problem.
Tests that fail frequently or seemingly randomly, indicate a “people” problem: members of the team don’t understand the requirements, or requirements keep changing due to activity outside of the team, or coding or testing not done well and better training is needed.
3. straw-man: without testing-hooks in code, you can't do white-box tests.
Try mock objects.
4. straw-man: to test a for-loop, you need as many tests as there are iterations in the loop.
Heard of boundary testing? See my Testing on the Toilet entry.
5. straw-man: changing code requires changing tests.
This isn't a big burden if DRY (“Don’t Repeat Yourself”) is applied to both code & tests. (See also “Once and Only Once.)
5. straw-man: you can't have nice OO because TDD tests are "procedural".
So not having no tests is required for nice OO?
6. straw-man: TDDing classes = bad design, because incrementally designing a class or classes while writing tests can’t be done well. And, refactoring the structure of the code (to improve the design) is can’t be done, either.
Really? refactoring is supported by TDD-tests. Do well-designed classes pop out of your head fully-formed?
6. straw-man: when implementing features one-at-a-time, user experience is a mess.
Before BDD, did you design entire UX in one second? It was incremental then, too.
7. straw-man: the object's state-space is big number (like 2**32) so we can't write enough unit tests, so don't even try.
Heard of boundary testing? See my Testing on the Toilet entry.
OTHER issues with Signed SSLVerifySignedServerKeyExchange ("goto fail" bug)
Mike Bland, whom I worked with at Google, teaching and spreading the word on how to write fast unit tests, find code smells and refactor them away, continuous integration, and TDD, has commented on the "goto fail" bug - and wants to direct your attention to other aspects of that code: the copy-paste code duplication that probably created the problem that the lack of unit tests didn't find:
Mike wrote:
He also wrote:
My response to Mike is:
Hi Mike. Yes I did write a Testing on the Toilet article titled "Too Many Tests", which was posted inside Google as well as on the public Google Testing blog. On of the commenters said "Good example of equivalence class partioning."
My personal blogging on the "goto fail" issue did just stick to the testable aspect of the code, because many people were saying it could not be tested at the unit level.
I could have also pointed out the need for code review and/or pair programming and the need for refactoring, based on a foundation of well-tested code, but I kept that blog entry focused only on the 'testable' topic.
[PS: Check out the "Real Programmers Write Tests" merchandise on my blog's home page.]
Mike wrote:
I still haven’t found any other articles that suggest, as mine did, that the same block of code cut-and-pasted six times in the same file was a problem, that it was ripe for factoring out, and that the resulting function was straightforward to test in isolation. That’s curious to me; it’s like people got stuck on the one stupid goto fail; line and started drawing conclusions without looking at the surrounding code, seeing the same algorithm copied immediately above it, and suspecting, as I did, that there was a classic code duplication problem which fixing would’ve likely avoided the bug to begin with, test or no.(Go read his whole blog entry, it is worth it, and lengthy. So much blogging is too short these days.)
He also wrote:
What’s more, if memory serves, Keith even wrote the Testing on the Toilet article that advocated for breaking larger chunks of logic into smaller, more testable functions to avoid having a combinatorial explosion of test inputs—the very concern that Bellovin had mentioned as rendering exhaustive system-level testing infeasible.5
My response to Mike is:
Hi Mike. Yes I did write a Testing on the Toilet article titled "Too Many Tests", which was posted inside Google as well as on the public Google Testing blog. On of the commenters said "Good example of equivalence class partioning."
In the movie Amadeus, the Austrian Emperor criticizes Mozart's music as having “too many notes.” How many tests are “too many” to test one function?
My personal blogging on the "goto fail" issue did just stick to the testable aspect of the code, because many people were saying it could not be tested at the unit level.
I could have also pointed out the need for code review and/or pair programming and the need for refactoring, based on a foundation of well-tested code, but I kept that blog entry focused only on the 'testable' topic.
[PS: Check out the "Real Programmers Write Tests" merchandise on my blog's home page.]
Tuesday, March 4, 2014
Next Product For Sizeography
As CTO and chief programmer of UpstartTechnology and the Sizeography division, I'd like announce our next product, already in progress.
This new app will allow you to place a common object on, or neat, another object, and find the approximate size of the unknown object. For example, if you place a quarter on a small table, snap a picture of it in our app, the app will compute the size of the table.
While the app won’t be ready right away, we want everyone to have a say, so after we get suggestions for the name, we’ll hold a vote to see which of the names wins.
Nominate a name for app in the comments to this blog (or our main company blog), and look for the poll to be put up after we’ve gotten some good suggestions for names. (G-rated names only, please).
How to enter: Leave a comment with your app name suggestion[s] and make sure we have your email so we can contact you if you win. We’ll take the best names and put up a poll, and the winner of the poll will get the prize.
The prize will probably be an Easter-egg hidden in the app, but if you’ve got a prize suggestion, be sure to let us know in the comments (G-rated only, please).
This new app will allow you to place a common object on, or neat, another object, and find the approximate size of the unknown object. For example, if you place a quarter on a small table, snap a picture of it in our app, the app will compute the size of the table.
While the app won’t be ready right away, we want everyone to have a say, so after we get suggestions for the name, we’ll hold a vote to see which of the names wins.
Nominate a name for app in the comments to this blog (or our main company blog), and look for the poll to be put up after we’ve gotten some good suggestions for names. (G-rated names only, please).
How to enter: Leave a comment with your app name suggestion[s] and make sure we have your email so we can contact you if you win. We’ll take the best names and put up a poll, and the winner of the poll will get the prize.
The prize will probably be an Easter-egg hidden in the app, but if you’ve got a prize suggestion, be sure to let us know in the comments (G-rated only, please).
Sunday, February 23, 2014
TDD and Signed SSLVerifySignedServerKeyExchange
Test-driven development (TDD) done consistently throughout a project results in near-100% logic coverage. That's better than just statement coverage. It also results in testable code, better modularity, better design (if you pay attention to code smells), and faster software development.
The heart of TDD is:
Badly-designed code is hard to test. Most developers who try to use TDD in a badly-designed, not-unit-tested project will find TDD is hard to do in this environment, and will give up. If they try to do "test-after" (the opposite of TDD's test-first practice), they will also find it hard to do in this environment and give up. And this creates a vicious cycle: untested bad code encourages more untested bad code.
If code is only written to make a test pass (as in TDD), you can't write an if statement until you have a test that requires it. You should end up with a test for the if statement being true, and a test for the if statement being false, possibly more than one test for each branch.
TDD in C is not terribly hard. I've taught people how to TDD in C and other languages. And the suites of tests created by TDD makes it possible to refactor with more confidence.
If one or more TDD tests (and other tests, like system tests) fail, someone broke something. The fine-grain testing that is part of TDD will usually pin-point where the new bug is. Undo the changes that broke the test, or fix things before doing anything else.
(Tests that fail unpredictably indicate something is non-deterministic either in the code-under-test or the test itself. That also needs to be fixed.)
landonf demonstrated that SSLVerifySignedServerKeyExchange() is unit-testable in isolation. See his code on github. I copied his unit test for a bad signature here:
@interface TestableSecurityTests : XCTestCase @end
@implementation TestableSecurityTests {
SSLContext _ctx;
}
- (void) setUp {
memset(_ctx.clientRandom, 'A', sizeof(_ctx.clientRandom));
memset(_ctx.serverRandom, 'B', sizeof(_ctx.serverRandom));
}
- (void) tearDown {
[super tearDown];
}
/* Verify that a bogus signature does not validate */
- (void) testVerifyRSASignature {
SSLBuffer signedParams;
SSLAllocBuffer(&signedParams, 32);
uint8_t badSignature[128];
memset(badSignature, 0, sizeof(badSignature));
OSStatus err;
err = SSLVerifySignedServerKeyExchange(&_ctx, true, signedParams, badSignature, sizeof(badSignature));
XCTAssertNotEqual(err, 0, @"SSLVerifySignedServerKeyExchange() returned success on a completely bogus signature");
}
@end
The heart of TDD is:
- Write a test. Running that test should fail. (Tests are often simpler than the code they test, so usually this step is pretty easy.)
- Make the test pass by writing just enough code. (All other tests should pass as well.)
- Refactor. (Not done every time through this loop; remove duplicate logic and look for other code smells.)
- Repeat until desired feature is implemented.
- NOTE: Checking into source-code-control can be done whenever all tests are passing. (A Continuous Integration (CI) server can also run tests: the "fast tests" created by TDD and slower system tests.)
Badly-designed code is hard to test. Most developers who try to use TDD in a badly-designed, not-unit-tested project will find TDD is hard to do in this environment, and will give up. If they try to do "test-after" (the opposite of TDD's test-first practice), they will also find it hard to do in this environment and give up. And this creates a vicious cycle: untested bad code encourages more untested bad code.
If code is only written to make a test pass (as in TDD), you can't write an if statement until you have a test that requires it. You should end up with a test for the if statement being true, and a test for the if statement being false, possibly more than one test for each branch.
TDD in C is not terribly hard. I've taught people how to TDD in C and other languages. And the suites of tests created by TDD makes it possible to refactor with more confidence.
If one or more TDD tests (and other tests, like system tests) fail, someone broke something. The fine-grain testing that is part of TDD will usually pin-point where the new bug is. Undo the changes that broke the test, or fix things before doing anything else.
(Tests that fail unpredictably indicate something is non-deterministic either in the code-under-test or the test itself. That also needs to be fixed.)
landonf demonstrated that SSLVerifySignedServerKeyExchange() is unit-testable in isolation. See his code on github. I copied his unit test for a bad signature here:
@interface TestableSecurityTests : XCTestCase @end
@implementation TestableSecurityTests {
SSLContext _ctx;
}
- (void) setUp {
memset(_ctx.clientRandom, 'A', sizeof(_ctx.clientRandom));
memset(_ctx.serverRandom, 'B', sizeof(_ctx.serverRandom));
}
- (void) tearDown {
[super tearDown];
}
/* Verify that a bogus signature does not validate */
- (void) testVerifyRSASignature {
SSLBuffer signedParams;
SSLAllocBuffer(&signedParams, 32);
uint8_t badSignature[128];
memset(badSignature, 0, sizeof(badSignature));
OSStatus err;
err = SSLVerifySignedServerKeyExchange(&_ctx, true, signedParams, badSignature, sizeof(badSignature));
XCTAssertNotEqual(err, 0, @"SSLVerifySignedServerKeyExchange() returned success on a completely bogus signature");
}
@end
Friday, February 14, 2014
A Key Aspect of Successful Projects
Rapid responses to questions is often a key to successful projects. Extreme Programming and other agile methods like Scrum consider this to be so important as to require the domain expert / product manager / business analyst / "product owner" / "Customer" to be co-located with the developers/testers.
Obviously some projects can be successful without co-location, but odds against success rise whenever developers can't quickly and easily communicate with the Customer.
Obviously some projects can be successful without co-location, but odds against success rise whenever developers can't quickly and easily communicate with the Customer.
Tuesday, January 28, 2014
Thanks to a lot of hard work
Thanks to a lot of hard work, Sizeography's first iOS app, myGraph, is now live in the app store. This app allows you to print completely customized grid or graph paper from your iPhone or iPad to any compatible AirPrint printer. For a 99¢ one-time purchase (no ads, ever), you will have as many or as few sheets of graph paper to your exact specifications, at home or away.
You can also use myGraph to send a pdf of your custom or predefined grid or graph paper to:
- AirDrop
- DropBox
- Evernote
- Message
- Save an image to your photo library.
- Copy an image to be pasted in another app.
- myGraph can send pdf files to apps that accept pdf files.
- and, myGraph can send png files to apps that accept png files.
We're working on a list of 101 uses for this app. Here are a few we have thought up so far:
- Planning and designing woodworking projects.
- Print a grid to help with sewing patterns.
- Tailoring.
- Scrap-booking.
- Science class: plotting lab results.
- Math class: graphing equations.
- Geometry class.
- Trigonometry class.
- Practicing writing Chinese, Japanese, Korean, and other languages.
Monday, January 27, 2014
Some thoughts on C, OO, ObjC, C++
C allows structs to be copied "by value" but C doesn't allow array types to be copied—directly. The following code will not compile:
struct Writer;
typedef int (* PrintFunc)(struct Writer * w, char const * format, ...);
// pointer to function that returns int
// and has Writer* as the type of its first argument.
typedef void (* CloseWriterFunc)(struct Writer * w);
// close and de-allocate
typedef struct Writer {
PrintFunc Print;
// ...other function pointers
CloseWriterFunc Close;
} Writer;
Writer * NewFileWriter(const char *restrict filename);
Writer * NewNetworkWriter(const char *restrict serverName);
int main(int argc, char*argv[])
{
Writer * w;
int useFile = 1;
if ( useFile )
w = NewFileWriter("someFile.txt");
else
w = NewNetworkWriter("someServer");
w->Print(w, "etc.");
w->Close(w);
w = NULL;
}
So there it is.
typedef int FiveIntsArray[5];
FiveIntsArray function5ints( FiveIntsArray arrIn )
{
FiveIntsArray ret:
ret = arrIn;
return ret;
}
int main(int argc,char*argv[])
{
FiveIntsArray arr = {1,2,3,4,5};
FiveIntsArray bar;
bar = function5ints(arr);
printf("%d, %d, %d, %d, %d\n", bar[0], bar[1], bar[2], bar[3], bar[4]);
}
Yes, it does not compile:
FiveIntsArray function5ints( FiveIntsArray arrIn )
{
FiveIntsArray ret:
ret = arrIn;
return ret;
}
int main(int argc,char*argv[])
{
FiveIntsArray arr = {1,2,3,4,5};
FiveIntsArray bar;
bar = function5ints(arr);
printf("%d, %d, %d, %d, %d\n", bar[0], bar[1], bar[2], bar[3], bar[4]);
}
Yes, it does not compile:
But put all this inside a struct, and it all works!
typedef struct FiveIntsStruct {
int arr[5];
} FiveIntsStruct;
FiveIntsStruct function5ints( FiveIntsStruct arrIn )
{
FiveIntsStruct ret;
ret = arrIn;
return ret;
}
int main(int argc,char*argv[])
{
FiveIntsStruct arr = {{1,2,3,4,5}};
FiveIntsStruct bar;
bar = function5ints(arr);
printf("%d, %d, %d, %d, %d\n", bar.arr[0], bar.arr[1], bar.arr[2], bar.arr[3], bar.arr[4]);
}
int arr[5];
} FiveIntsStruct;
FiveIntsStruct function5ints( FiveIntsStruct arrIn )
{
FiveIntsStruct ret;
ret = arrIn;
return ret;
}
int main(int argc,char*argv[])
{
FiveIntsStruct arr = {{1,2,3,4,5}};
FiveIntsStruct bar;
bar = function5ints(arr);
printf("%d, %d, %d, %d, %d\n", bar.arr[0], bar.arr[1], bar.arr[2], bar.arr[3], bar.arr[4]);
}
And I get this output:
1, 2, 3, 4, 5
Program ended with exit code: 0
Program ended with exit code: 0
Ta-da!
However, struct-copying, at least in the early days of C, was thought to be not very efficient, and was often avoided in C code. This tradition is so ingrained in C programmers that I have met
some programmers who didn't know that struct-copying is allowed in C.
For small structs, and under modern compilers, struct-copying can be just as efficient as passing a single value, and more efficient than passing a pointer to a struct, which requires dereferencing the pointer to access its members. A 64-bit CPU can hold an entire FiveiIntsStruct in a single register.
If you want to do object-oriented programming in C, one way to do that is to start with structs. We can associate functions and structs, and we already have an example of something object-like in the C standard library: the file io functions.
typedef struct FILE {
// we don't care what's in here--consider it private.
} FILE;
FILE * fopen(const char *restrict filename, const char *restrict mode);
// fopen allocates & initializes, kind of like a C++ constructor.
int fprintf(FILE * restrict stream, const char * restrict format, …);
// functions taking a FILE* arguments are methods of the FILE "class".
int fclose(FILE *stream);
// cleans up and deallocates, kind of like a C++ destructor.
But a big part of OO is polymorphism. How can we accomplish that? Let's say we want a file-writer, and a network-writer, but the majority of the code should work with both kinds of writer. We can do it a bit like this:
typedef int (* PrintFunc)(struct Writer * w, char const * format, ...);
// pointer to function that returns int
// and has Writer* as the type of its first argument.
typedef void (* CloseWriterFunc)(struct Writer * w);
// close and de-allocate
typedef struct Writer {
PrintFunc Print;
// ...other function pointers
CloseWriterFunc Close;
} Writer;
Writer * NewFileWriter(const char *restrict filename);
Writer * NewNetworkWriter(const char *restrict serverName);
int main(int argc, char*argv[])
{
Writer * w;
int useFile = 1;
if ( useFile )
w = NewFileWriter("someFile.txt");
else
w = NewNetworkWriter("someServer");
w->Print(w, "etc.");
w->Close(w);
w = NULL;
}
Implementing this in one or more .c files:
typedef struct {
Writer wpart;
// file-writer specific data members go here.
} FileWriter;
typedef struct {
Writer wpart;
// network-writer specific data members go here.
} NetworkWriter;
// must match function-pointers...
static int FileWriterPrint(Writer * w, char const * format, ...)
{
FileWriter * fw = (FileWriter *) w;
// real code goes here.
return 0;
}
static void FileWriterClose(struct Writer * w)
{
FileWriter * fw = (FileWriter *) w;
// real code goes here.
free(fw);
}
static int NetworkWriterPrint(Writer * w, char const * format, ...)
{
NetworkWriter * fw = (NetworkWriter *) w;
// real code goes here.
return 0;
}
// other NetworkWriter functions...
static void NetworkWriterClose(struct Writer * w)
{
NetworkWriter * fw = (NetworkWriter *) w;
// real code goes here.
free(fw);
}
Writer * NewFileWriter(const char *restrict filename)
{
FileWriter * fw = malloc( sizeof( FileWriter) );
fw->wpart.Print = FileWriterPrint;
fw->wpart.Close = FileWriterClose;
// real code goes here.
return (Writer *) fw;
}
Writer * NewNetworkWriter(const char *restrict filename)
{
NetworkWriter * nw = malloc( sizeof(NetworkWriter) );
nw->wpart.Print = NetworkWriterPrint;
nw->wpart.Close = NetworkWriterClose;
// real code goes here.
return (Writer *) nw;
}
Writer wpart;
// file-writer specific data members go here.
} FileWriter;
typedef struct {
Writer wpart;
// network-writer specific data members go here.
} NetworkWriter;
// must match function-pointers...
static int FileWriterPrint(Writer * w, char const * format, ...)
{
FileWriter * fw = (FileWriter *) w;
// real code goes here.
return 0;
}
static void FileWriterClose(struct Writer * w)
{
FileWriter * fw = (FileWriter *) w;
// real code goes here.
free(fw);
}
static int NetworkWriterPrint(Writer * w, char const * format, ...)
{
NetworkWriter * fw = (NetworkWriter *) w;
// real code goes here.
return 0;
}
// other NetworkWriter functions...
static void NetworkWriterClose(struct Writer * w)
{
NetworkWriter * fw = (NetworkWriter *) w;
// real code goes here.
free(fw);
}
Writer * NewFileWriter(const char *restrict filename)
{
FileWriter * fw = malloc( sizeof( FileWriter) );
fw->wpart.Print = FileWriterPrint;
fw->wpart.Close = FileWriterClose;
// real code goes here.
return (Writer *) fw;
}
Writer * NewNetworkWriter(const char *restrict filename)
{
NetworkWriter * nw = malloc( sizeof(NetworkWriter) );
nw->wpart.Print = NetworkWriterPrint;
nw->wpart.Close = NetworkWriterClose;
// real code goes here.
return (Writer *) nw;
}
The syntax isn't that nice, but a preprocessor could automate much of this.
And, in fact, both Objective-C and C++ started out as preprocessors generating C code.
There is one problem with this implementation besides its awkward syntax. Each instance of this struct contains copies of the function-pointers. This overhead can be eliminated by another level of indirection.
// there will be one instance of this struct per "class"
typedef struct WriterFunctions {
PrintFunc Print;
// ...other function pointers
CloseWriterFunc Close; // close and de-allocate
} WriterFunctions;
typedef struct Writer {
// writer data
WriterFunctions* methods;
} Writer;
static WriterFunctions FileWriterFunctions = {
FileWriterPrint, FileWriterClose
};
static WriterFunctions NetworkWriterFunctions = {
NetworkWriterPrint, NetworkWriterClose
};
Writer * NewFileWriter(const char *restrict filename)
{
FileWriter * fw = malloc( sizeof(FileWriter) );
fw->methods = FileWriterFunctions;
// real code goes here.
return (Writer *) fw;
}
Writer * NewNetworkWriter(const char *restrict filename)
{
NetworkWriter * nw = malloc( sizeof(NetworkWriter) );
nw->methods = NetworkWriterFunctions;
// real code goes here.
return (Writer *) nw;
}
This is probably not that far from the implementation that C++ uses, where polymorphic ("virtual") function-pointers are kept in "vtables".
C++ contorts the C language into pretending classes are just "special" structs. But a C++ class or struct may have many hidden things: a vtable pointer, an implicitly-defined default constructor calling constructors on its member variables, an implicitly-defined copy constructor calling copy constructors of its member variables, an implicit-defined assignment operator calling assignment-operators on its member variables, and an implicitly-defined non-virtual destructor calling the destructors of its member variables.
And C++ has some gotchas: if the base class in a class hierarchy has an implicitly-defined non-virtual destructor, calling delete on a pointer of the base-class type (but it is pointing to a derived-class object), the derived-class destructor does not get called, which may destroy the correctness of the system.
And C++ has some gotchas: if the base class in a class hierarchy has an implicitly-defined non-virtual destructor, calling delete on a pointer of the base-class type (but it is pointing to a derived-class object), the derived-class destructor does not get called, which may destroy the correctness of the system.
Objective-C adds classes and objects as something different from structs, adding some pretty self-contained Smalltalk-like syntax to C. Without operator overloading and other contortions of syntax, what you see in Objective-C code is generally what you get. Not much invisible or implicit stuff in the language itself (though the implementation of method-lookup isn't normally invisible). With ARC, retain, release, and autorelease are mostly invisible/implicit, and I'm pretty sure Apple has done some very interesting things at run-time for certain technologies like Core Data.
If you know where the sharp edges are, C++ can be pretty cool. And you can blend C++ and Objective-C if you want to. C++ constructors and destructors will be invoked (invisibly/implicitly) for you in Objective-C's equivalents of constructors and destructors.
Most of the functionality of ARC could have been implemented with appropriate C++ smart pointer template classes, but I'm sure most Objective-C programmers would not want to sweat the details of the required syntax.
So there it is.
Subscribe to:
Posts (Atom)


