Methods, Functions and Messaging.

Nice Post .. Nikhil

Cocoa Puff

Objective C programs interact with run time systems at three distinct levels

  • Through objective C source code – When an objective C code is compiled then the compiler creates the data structures and function calls that implement the dynamic behaviour of the language. The data structures capture information found in class and category definitions and in protocol declarations.
  • Through methods of NSObject class found in Foundation Framework.
  • Through direct calls to runtime functions. – A dynamic shared library with a public interface consisting of a set of functions and data structures in the header files located in the /usr/include/objc.

obj_msgSend :

In objective C methods are not bound to a function until runtime. The compiler converts a message expression [receiver message] into a call on a messaging function obj_msgSend. This function is of the following form:

objc_msgSend(receiver, selector, arg1, arg2, …)

receiver – Receiver…

View original post 341 more words

Advertisements

iDiscussion : Writing Apps? Juggling Multiple Platforms and the Bumpy Road Ahead

Targeting multiple operating systems has been an industry goal or non-goal depending on your perspective since some of the earliest days of computing. For both app developers and platform builders, the evolution of their work follow typical patterns—patterns where their goals might be aligned or manageable in the short term but become increasingly divergent over time.

While history does not always repeat itself, the ingredients for a repeat of cross-platform woes currently exist in the domain of mobile apps (mobile means apps developed for modern sealed-case platforms such as iOS, Android, Windows RT, Windows Phone, Blackberry, etc.) The network effects of platforms and the “winner take all” state that many believe is reached (or perhaps desirable) influences the behavior and outcome of cross-platform app development as well as platform development.

Today app developers generally write apps targeting several of the mobile platforms. If you look at number of “sockets” over the past couple of years there was an early dominance of iOS followed by a large growth of Android. Several other platforms currently compete for the next round of attention. Based on apps in respective app stores these are two leaders for the new platforms. App developers today seeking the most number of client sockets target at least iOS and Android, often simultaneously. It is too early to pick a winner.

Some would say that the role of the cloud services or the browser make app development less about the “client” socket. The data, however, suggests that customers prefer the interaction approach and integration capability of apps and certainly platform builders touting the size of app stores further evidences that perspective. Even the smallest amount of “dependency” (for customers or technical reasons) on the client’s unique capabilities can provide benefits or dramatically improve the quality of the overall experience.

In discussions with entrepreneurs I have had, it is clear the approach to cross-platform is shifting from “obviously we will do multiple platforms” to thinking about which platform comes first, second, or third and how many to do. Chris Dixon recently had some thoughts about this in the context of modern app development in general (tablets and/or phones). I would agree that tablets drive a different type of app over time simply because the scenarios can be quite different even with identically capable devices under the hood. The cross-platform question only gets more difficult if apps take on unique capabilities or user experiences for different sized screens, which is almost certainly the case.

History

The history of cross-platform development is fairly well-known by app developers.

The goal of an app developer is to acquire as many customers as possible or to have the highest quality engagement with a specific set of customers. In an environment where customers are all using one platform (by platform we mean set of APIs, tools, languages that are used to build an app) the choice for a developer is simple, which is to target the platform APIs in a fully exploitive manner.

The goal of being the “best” app for the platform is a goal shared by both app and platform developers. The reason for this is that nearly any app will have app competitors and one approach to differentiation will be to be the app that is best on the platform—at the very least this will garner the attention of the platform builder and result in amplification of the marketing and outreach of a given app (for example, given n different banking apps, the one that is used in demonstrations or platform evangelism will be the one that touts the platform advantages).

Once developers are faced with two or more platforms to target, the discussion typically starts with attempting to measure the size of the customer base for each platform (hence the debate today about whether market share or revenue define a more successful platform). New apps (at startups or established companies) will start with a dialog that depending on time or resources jumps through incredible hoops to attempt to model the platform dynamics. Questions such as which customers use which platforms, velocity of platform adoption, installed base, likelihood of reaching different customers on platforms, geography of usage, and pretty much every variable imaginable. The goal is to attempt to define the market impact of either support multiple platforms or betting on one platform. Of course none of these can be known. Observer bias is inherent in the process only because this is all about forecasting a dynamic system based on the behavior of people. But basing a product plan on a rapidly evolving and hard to define “market share” metric is fraught with problems.

During this market sizing debate, the development team is also looking at how challenging cross platform support can be. While mostly objective, just as with the market sizing studies, bias can sneak in. For example, if the developers’ skills align with one platform or a platform makes certain architectural assumptions that are viewed favorably then different approaches to platform choices become easy or difficult.

Developers that are fluent in HTML might suggest that things be done in a browser or use a mobile browser solution. Even the business might like this approach because it leverages an existing effort or business model (serving ads for example). Some view the choices Facebook made for their mobile apps as being influenced by these variables.

As the dialog continues, developers will tend to start to see the inherent engineering costs in trying to do a great job across multiple platforms. They will start to think about how hard it is to keep code bases in sync or where features will be easier/harder or appear first or even just sim-shipping across platforms. Very quickly developers will generally start to feel pulled in an impossible direction by having to be across multiple platforms and that it is just not viable to have a long-term cross-platform strategy.

The business view will generally continue to drive a view that the more sockets there are the better. Some apps are inherently going to drive the desire or need for cross-platform support. Anything that is about communications for example will generally argue for “going where the people are” or “our users don’t know the OS of their connected endpoints” and thus push for supporting multiple platforms. Apps that are offered as free front ends for services (online banking, buying tickets, or signing up for yoga class) will also feel pressures to be where the customers are and to be device agnostic. As you keep going through scenarios the business folks will become convinced that the only viable approach is to be on all the popular platforms.

That puts everyone in a very tense situation—everyone is feeling stressed about achieving success. Something has to give though.

We’ve all been there.

Pattern

The industry has seen this cross-platform movie several times. It might not always be the same and each generation brings with it new challenges, new technologies, and potentially different approaches that could lead to different outcomes. Knowing the past is important.

Today’s cross-platform challenge can be viewed differently primarily because of a few factors when looking at the challenge from an app developer / ISV:

  • App Services. Much of the functionality for today’s apps resides on software as a service infrastructure. The apps themselves might be viewed as fairly lightweight front ends to these services, at least for some class of apps or some approaches to app building. This is especially true today as most apps are still fairly “first generation”.
  • Languages and tools. Today’s platforms are more self-contained in that the languages and tools are also part of the platform. In previous generations there were languages that could be used across different platforms (COBOL, C, C++) and standards for those languages even if there were platform-specific language extensions. While there are ample opportunities for shared libraries of “engine” code in many of today’s platforms, most modern platforms are designed around a heavy tilt in favor of one language, and those are different across platforms. Given the first point, it is fair to say that the bulk of the code (at least initially) on the device will be platform specific anyway.
  • Integration. Much of what goes on in apps today is about integration with the platform. Integration has been increasing in each generation of platform shifts. For example, in the earliest days there was no cross-application sharing, then came the basics through files, then came clipboard sharing. Today sharing is implicit in nearly every app in some way.

Even allowing for this new context, there is a cycle at work in how multiple, competing platforms evolve.

This is a cycle so you need to start somewhere.

Initially there is a critical mass around one platform. As far as modern platforms go when iOS was introduced it was (and remains) unique in platform and device attributes so mobile apps had one place to go and all the new activity was on that platform. This is a typical first-mover scenario in a new market.

Over time new platforms emerge (with slightly different characteristics) creating a period of time where cross-platform work is the norm. This period is supported by the fact that platforms are relatively new and are each building out the base infrastructure which tends to look similar across the new platforms.

There are solid technical reasons why cross-platform development seems to work in the early days of platform proliferation. When new platforms begin to emerge they are often taking similar approaches to “reinventing” what it means to be a platform. For example, when GUI interfaces first came about the basics of controls, menus, and windows were close enough that knowledge of one platform readily translated to other platforms. It was technically not too difficult to create mapping layers that allowed the same code to be used to target different platforms.

During this phase of platform evolution the platforms are all relatively immature compared to each other. Each is focused on putting in place the plumbing that approaches platform design in this new shared view. In essence the emerging platforms tend to look more similar that different. The early days of web browsers–which many believed were themselves platforms–followed this pattern. There was a degree of HTML that was readily shared and consistent across platforms. At least this was the case for a while.

During this time there is often a lot of re-learning that takes place. The problems solved in the previous generation of platforms become new again. New solutions to old problems arise, sometimes frustrating developers. But this “new growth” also brings with it a chance to revisit old assumptions and innovate in new ways, even if the problem space is the same.

Even with this early commonality, things can be a real challenge. For example, there is a real desire for applications to look and feel “native”. Sometimes this is about placement of functionality such as where settings are located. It could be about the look or style of graphical elements or the way visual aspects of the platform are reflected in your app. It could also be about highly marketed features and how well your app integrates as evidence for supporting the platform.

Along the way things begin to change and the platforms diverge because of two factors. First, once the plumbing common to multiple early platforms is in place, platform builders begin to express their unique point of view of how platform services experiences should evolve. For example, Android is likely to focus on unique services and how the client interacts with and uses those services. To most, iOS has shown substantially more innovation in client-side innovation and first-party experiences. The resulting APIs exposed to developers start to diverge in capabilities and new API surface areas no longer seem so common between platforms.

Second, competition begins to drive how innovation progresses. While the first mover might have one point of view, the second (or third) mover might take the same idea of a service or API but evolve it slightly differently. It might integrate with backends differently or it might have a very different architecture. The role of voice input/reco, maps, or cloud storage are examples of APIs that are appearing on platforms but the expression of those APIs and capabilities they support are evolving in different ways that there are no obvious mappings between them.

Challenges

As the platforms diverge developers start to make choices about what APIs to support on each platform or even which platforms to target. With these choices come a few well known challenges.

  • Tools and languages.Initially the tools and languages might be different but things seem manageable. In particular, developers look to put as much code in common languages (“platform agnostic code”) or implement code as a web service (independent of the client device). This is a great strategy but does not allow for the reality that a good deal of code (and differentiation) will serve as platform-specific user experience or integration functionality. Early on tools are relatively immature and maybe even rudimentary which makes it easier to build infrastructure around managing a cross-platform project. Over time the tools themselves will become more sophisticated and diverge in capabilities. New IDEs or tools will be required for the platforms in order to be competitive and developers will gravitate to one toolset, resulting in developers themselves less able to context switch between platforms. At the very least, managing two diverging code bases using different tools becomes highly challenging–even if right now some devs think they have a handle on the situation.
  • User interaction and design (assets). Early in platform evolution the basics of human interaction tend to be common and the approaches to digital assets can be fairly straight forward. As device capabilities diverge (DPI, sensors, screen sizes) the ability for the user interaction to be common also diverges. What works on one platform doesn’t seem right on another. Tablet sized screens introduce a whole other level of divergence to this challenge. Alternate input mechanisms can really divide platform elements (voice, vision, sensors, touch metaphors).
  • Platform integration. Integrating with a platform early on is usually fairly “trivial”. Perhaps there are a few places you put preferences or settings, or connect to some platform services such as internationalization or accessibility. As platforms evolve, where and how to integrate poses challenges for app developers. Notifications, settings, printing, storage, and more are all places where finding what is “common” between platforms will become increasingly difficult to impossible. The platform services for identity, payment, and even integration with third party services will become increasingly part of the platform API as well. When those APIs are used other benefits will accrue to developers and/or end-users of apps—and these APIs will be substantially different across platforms.
  • More code in the service. The new platforms definitely emphasize code in services to provide a way to be insulated from platform changes. This is a perfect way to implement as much of your own domain as you can. Keep in mind that the platforms themselves are evolving and growing and so you can expect services provided by the platform to be part of the core app API as well. Storage is a great example of this challenge. You might choose to implement storage on your own to avoid a platform dependency. Such an approach puts you in the storage business though and probably not very competitively from a feature or cost perspective. Using a third party API can pose the same challenge as any cross-platform library. At the same time, the platforms evolve and likely will implement storage APIs and those APIs will be rich and integrate with other services as well.
  • Cross-platform libraries. One of the most common approaches developers attempt (and often provided by third parties as well) is to develop or use a library that abstracts away platform differences or claims to map a unique “meta API” to multiple platforms. These cross—platform libraries are conceptually attractive but practically unworkable over time. Again, early on this can work. Over time the platform divergence is real. There’s nothing you can do to make services that don’t exist on one platform magically appear on another or APIs that are architecturally very different morph into similar architectures. Worse, as an app developer you end up relying on essentially a “shadow” OS provided by a team that has a fraction of the resources for updates, tooling, documentation, etc. even if this team is your own dev team. As a counter example, games commonly use engines across platforms, but they rely on a very narrow set of platform APIs and little integration. Nevertheless, there are those that believe this can be a path (as it is for games). It is important to keep in mind that the platforms are evolving rapidly and the customer desire for well-integrated apps (not just apps that run).
  • Multiple teams. Absent the ability to share app client code (because of differing languages), keeping multiple teams in sync on the same app is extremely challenging. Equally challenging is having one team time slice – not only is that mentally inefficient, maintaining up to date skills and knowledge for multiple platforms is challenging. Even beyond the basics of keeping the feature set the same, there are problems to overcome. One example is just timing of releases. It might be hard enough to keep features in sync and sim ship, but imagine that the demand spike for a new release of your app when the platform changes (and maybe even requires a change to your app). You are then in a position to need a release for one platform. But if you are halfway done with new features for your app you have a very tricky disclosure and/or code management challenge. These challenges are compounded non-linearly as the number of platforms increases.

These are a few potential challenges. Not every app will run into these and some might not even be real challenges for a particularly app domain. By and large, these are the sorts of things that have dogged developers working cross-platform approaches across clients, servers, and more over many generations.

What’s next?

The obvious question will continue to be debated, which is if there is a single platform winner or not. Will developers be able to pick a platform and reach their own business and product goals by focusing on one platform as a way of avoiding the issues associated with supporting multiple platforms?

The only thing we know for sure is that the APIs, tools, and approaches of different platforms will continue to evolve and diverge. Working across platforms will only get more difficult, not easier.

The new platforms moved “up the stack” and make it more difficult for developers to isolate themselves from the platform changes. In the old days, developers could re-implement parts of the platform within the app and use that across platforms or even multiple apps. Developers could hook the system and customize the behavior as they saw fit. The more sealed nature of platforms (which delivers amazing benefits for end-users) makes it harder for developers to create their own experience and transport it across platforms. This isn’t new. In the DOS era, apps implemented their own printing subsystems and character-based user models all of which got replaced by GUI APIs all to the advantage of developers willing to embrace the richer platforms and to the advantage of customers that gained a new level of capabilities across apps.

The role of app stores and approval processes, the instant ability for the community to review apps, and the need to break through in the store will continue to drive the need to be great apps on the chosen platforms.

Some will undoubtedly call for standards or some homogonization of platforms. Posix in the OS world, Motif in the GUI world, or even HTML for browsers have all been attempts at this. It is a reasonable goal given we all want our software investments to be on as many devices as possible (and this desire is nothing new). But is it reasonable to expect vendors to pour billions into R&D to support an intentional strategy of commoditization or support for a committee design? Vendors believe we’re just getting started in delivering inovation and so slowing things down this way seems counter-intuitive at best.

Ultimately, the best apps are going to break through and I think the best apps are going to be the ones that work with the platform not in spite of it and the best apps won’t duplicate code in the platform but work with platform.

It means there some interesting choices ahead for many players in these ecosystems.

BY: Steven Sinofsky

Reference : Here

SolutionPointLogo

iAndroid: Using SQLite on Android Application

iAndroid: Using SQLite on Android Application
Reference Source : Here
With a little care, SQLite can be used as a data store or full database on Android devices
As with most platforms, Android gives us a few options to store data so that it persists even after we’ve terminated the application. Of the various ways we can do this, text files — either stored in the application’s own files directory or to the phone’s SD card — represent one approach. Preferences are also frequently used to store data because they can be both hidden from the user and persist as long as the application is installed. And while not strictly speaking in the same category, Assets can be useful for storing read-only data, too. Assets are essentially files that you bundle into the application package prior to compilation in the project assets folder, which can be accessed at runtime. I will take a closer look at these later.Sometimes, however, we need to be able to carry out complex operations on persistent data, or the volume of data requires a more efficient method of management than a flat text file or preference entry will allow. This is where a mobile database comes in.

Android comes with SQLite (version 3.5.9+), which has been available on the platform since release 1.5 of the OS (the “Cupcake” release). For readers unfamiliar with SQLite, it is a self-contained, server-less, transactional SQL database. While it has its limitations, SQLite serves as a powerful tool in the Android developer’s arsenal.

What I’ll principally cover here is one way to use a SQLite database in Android, concentrating on its management; specifically, creation and update, rather than all the runtime operations.

Managing SQLite

To begin with, we can manage SQLite using a class that extends SQLiteOpenHelper, which comes with a constructor and two required methods; onCreate and onUpgrade.

Naturally, the first of these is executed when the constructor is instantiated; it is here that, via the superclass, we provide four important pieces of data:

  • Context. This is the context of the application. It can be useful to set this in the constructor and store it locally for later use in other methods.
  • Database name. This is the filename (as a String) of the physical database file being accessed.
  • Cursor factory. The cursor factory in use, if any.
  • Database Version. This is the version of your database (as an integer), which I’ll discuss in more detail later. Your initial version should be 1.

For our example, we put these four pieces together and get the following:

1
2
3
4
5
6
7
8
9
10
11
class DB extends SQLiteOpenHelper {
    final static int DB_VERSION = 1;
final static String DB_NAME = "mydb.s3db";
    Context context;
    
    public DB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // Store the context for later use
        this.context = context;
    }

The constructor does two things. First, it checks whether the database exists and, if not, will call the onCreate method. Second, if the database does exist, it will check whether the existing database version number differs from the one implemented in the constructor, so as to determine if the database has been updated. If it has, the onUpgrade method will be called.

Additionally, as we now know that the onCreate method is called only when the database does not exist, it can be used as a handy way to determine if you’re dealing with a first run of the application following installation. As such, you can use this method to call any other methods that you need executed only on the first run, such as EULA dialogs.

Let’s look at the database itself. For the purposes of this article, I’m just going to use a very simple employee database with a SQL creation script as follows:

1
2
3
4
5
6
7
CREATE TABLE employees (
 _id INTEGER PRIMARY KEY AUTOINCREMENT,
 name TEXT NOT NULL,
 ext TEXT NOT NULL,
 mob TEXT NOT NULL,
 age INTEGER NOT NULL DEFAULT '0'
);

We can easily construct this by hard-coding and executing the creation SQL, line by line, in our code as follows:

1
2
3
4
5
6
@Override
public void onCreate(SQLiteDatabase database) {
    database.execSQL(
        "CREATE TABLE employees ( _id INTEGER PRIMARY KEY "
    + "AUTOINCREMENT, name TEXT NOT NULL, ext TEXT NOT NULL, "
    + "mob TEXT NOT NULL, age INTEGER NOT NULL DEFAULT '0')");
}

As you can see, this can get quite unwieldy once the database reaches a certain size and complexity, so the ideal solution would be to bundle a SQL creation script as an asset file. To use this approach, you need to write a method that takes in a SQL script from the assets directory and parses it, executing it line by line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Override
public void onCreate(SQLiteDatabase database) {
executeSQLScript(database, "create.sql");
}
private void executeSQLScript(SQLiteDatabase database, 
                              String dbname) {
ByteArrayOutputStream outputStream = new  
                              ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;
        AssetManager assetManager = context.getAssets();
    InputStream inputStream = null;
        
    try{
        inputStream = assetManager.open(dbname);
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
            
        String[] createScript = 
                   outputStream.toString().split(";");
        for (int i = 0; i < createScript.length; i++) {
                String sqlStatement = createScript[i].trim();
            // TODO You may want to parse out comments here
            if (sqlStatement.length() > 0) {
                    database.execSQL(sqlStatement + ";");
                }
        }
    } catch (IOException e){
        // TODO Handle Script Failed to Load
    } catch (SQLException e) {
        // TODO Handle Script Failed to Execute
    }
}

While this is a more complex approach than simply executing each SQL statement for very simple databases, it quickly pays dividends once the database becomes more complex or you need to pre-populate it. You’ll also see that I abstracted the creation into a separate method called executeSQLScript so that it can be reused in other situations.

Interacting with the Database

Now that the database is created, I want to be able to interact with it. Here’s a brief rundown:

The first step is to open the database and there are two ways to do this: usinggetReadableDatabase() and getWritableDatabase(). The former is faster and uses fewer resources. It should be used for anything that does not require writing or changing the database. The latter call is better suited to INSERTs, UPDATEs, and the like.

In Android, recordsets are returned from queries as Cursor objects. To carry out a query, use either the query() or rawQuery() method. For example, the following two calls return exactly the same data:

1
2
3
4
DB db = new DB(this);
SQLiteDatabase qdb = db.getReadableDatabase();
Cursor recordset1 = 
     qdb.query("mytable", null, null, null, null, null, null);
Cursor recordset2 = qdb.rawQuery("SELECT * FROM mytable", null);

The first call uses a bewildering number of parameters. They are the table name, a string array of the column names, the WHERE clause, the selection arguments, the GROUP BY clause, the HAVING clause, and the ORDER BY clause, respectively. You’ll note that setting many of these as null has the effect of their being treated as wildcards or omitted altogether.

Most of these parameters are fairly straightforward to anyone familiar with SQL. The selection arguments, however, require a little more explanation because they form a string array that interacts with the WHERE parameter, systematically replacing any “?” characters in the clause with a value from the array.

With the rawQuery() approach, there are only two parameters: the first is the SQL query, and the second is the selection argument — akin to those used in the query method. Selection arguments may be preferable to use with complex queries, such as those that use JOINs.

Similarly, INSERTUPDATEDELETE, and a range of other common operations are handled with methods similar to query(); or, as with rawQuery(), they can be executed as raw SQL code using execSQL().

Database Upgrades

Returning to management of the database, let’s look at the tricky scenario of database upgrades. Over time, an app will likely change. New functionality may be added, or it may be better optimized. These changes, in turn, may lead to a requirement to upgrade the database schema and change the value for DB_VERSION in the updated application code to reflect this.

One potential problem is that replacing our database with a new version will end up invalidating the previous version and lead to the loss of data that was present in existing user installations. A second problem is that, once our application has reached a point whereby more than two versions have been released, we cannot presume that the user has been diligently upgrading all along, so a simple upgrade from one version to the next may no longer work.

To deal with this, we already know that if we introduce a new database version, theonUpgrade() method will be called. So ideally, we can use our SQL script parser method and execute one or more update scripts.

Let’s look at what we intend to change in Version 2 of our database in the example:

  • Normalize the phone number data (extension, mobile) into a separate “numbers” table, which includes a numeric field to denote the type of phone number.
  • Add a salary field to the employee table.

Using the Version 1 schema as a starting point, this can be handled by writing a SQL script that updates the schema and then populates it with the data from the older version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE TABLE numbers (
   _id INTEGER PRIMARY KEY AUTOINCREMENT,
   employid INTEGER NOT NULL,
   number TEXT NOT NULL,
   ntype INTEGER NOT NULL DEFAULT '0'
);
CREATE INDEX employid ON numbers(employid);
INSERT INTO numbers (employid, number, ntype) SELECT _id, ext, 0
    FROM employees;
INSERT INTO numbers (employid, number, ntype) SELECT _id, mob, 1
    FROM employees;
CREATE TABLE temp (
     _id INTEGER PRIMARY KEY AUTOINCREMENT,
     name TEXT NOT NULL,
     salary INTEGER NOT NULL DEFAULT '0'
);
INSERT INTO temp (_id, name) SELECT _id, name FROM employees;
DROP TABLE employees;
ALTER TABLE temp RENAME TO employees;

Naturally, the more complex the changes in your database schema, the more complex the script you’ll need to write to handle this. SQLite has more limited support for SQL than many databases, so sometimes you’ll need to devise workarounds for these limitations. For example, in the aforementioned update script, I had to employ a temporary table as a workaround for the lack of DROP COLUMN functionality.

Now that I have the SQL upgrade script, I need to handle how it is executed when theonUpgrade method is called. One approach is to do the following:

1
2
3
4
5
6
7
8
9
10
11
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {     
if (newVersion > oldVersion) {
    switch (oldVersion) {
        case 1:
            executeSQLScript(database, "update_v2.sql");
        case 2:
            executeSQLScript(database, "update_v3.sql");
    }
}
}

There are two things to note in this code. The first is that I check to see whether the new database version is greater than the old one. I wrote the code this way because theonUpgrade() method will be called any time these two versions are different, leading to a situation in which version downgrades are also possible. Our code does not envisage this ever occurring, but an else clause and accompanying code could be added to handle this.

The second thing is that there are no break statements between the cases in our switch. This is because each script simply updates from one version to the next, meaning that an upgrade from Version 1 to 3 will first run the upgrade script from Version 1 to 2, then continue on to run the upgrade script from Version 2 to 3. If the database is already at Version 2, it will simply skip the first script and only run the upgrade script from Version 2 to 3.

Thus, each time you upgrade the database, you will only need to replace the create script with one that reflects the new schema (for new installs), and an update script (that handles only an update from the previous version) to handle all possible upgrades. Meanwhile, in our Java code, we need to update the value for DB_VERSION and, naturally, any operations that may be affected by the new database schema.

Conclusion

SQLite can be a very useful means to store and manage data in a persistent manner on Android devices. However, as with any database, care needs to be taken to administer it correctly, particularly with regard to version changes.

Using the script parser solution and saving this part of the application logic as a series of SQL scripts is an efficient and simple management technique to avoid having to write complex methods to the core application to handle each upgrade, thus allowing you to concentrate on the application’s business logic instead.

Thanks 🙂 Keep Coding 🙂

SolutionPointLogo

iConcept : Basic MVVM with Re-Active COCOA

Basic MVVM with Reactive Cocoa

MVC – One Pattern to Rule them all

The MVC design pattern has existed since the late 1970s and has been in use in the Foundation, AppKit & UIKit Frameworks for a long time now. At its heart is a very simple design and a good idea. The Design is this

As you can see we have 3 components

  • Model – The Data model our view is managing
  • View – The User Interface on screen consisting of things such as text fields, buttons, etc.
  • Controller – The Controller in MVC exists to decouple the view from the model.

In the MVC design pattern, the controller separates the model from the view so that each can change independently. If we didn’t have such a decoupling then every time the model changed, the view would need to change as well. In this design pattern interactions happen like this

  1. A view triggers an action to happen on the Controller
  2. The Controller executes said action and updates the model
  3. The controller may receive a notification from the model that it was updated.
  4. The Controller updates the view

This is the MVC waltz that we do when working with this design pattern, overall it works fairly well. The reason we use this is because this pattern decouples the view from the data model, letting the controller be an intermediary between the 2. This allows the controller to access the parts of the data model that need to be accessed and allows for the controller to do things like properly format the data for the view.

MVVM – For a Better World

MVVM stands for Model-View-ViewModel, and comes from Microsoft and is based off of the MVC design pattern. To be more precise, it is based off of Martin Fowlers Presentation Model. To some people at first it looks very similar to the MVC design pattern and people become confused as to how its different. So let me show you the pattern and then we’ll see how its different

In this pattern we still have 3 components, the same as MVC however there are differences. In MVVM I and others tend to group the View Controller in with the View so that those 2 things are treated as 1 component. The most important part is that we’ve introduced the View Model and that the view gets updates pushed at it from the view model through some sort of observer. In this article ReactiveCocoa will be that observer.

In the MVVM pattern the View Model encapsulates data/properties that the view can bind to, any validation logic and actions that can be performed. For Instance if you had a button that needs to change its title text you would have a property on the view model that the button can bind its title property to. The same goes if you need to change the color of a control or enable and disable the control. In this pattern we are essentially taking the state of our app and putting it into a view model. Its also good to note that as far as the View Model is concerned it doesn’t care where it gets this state from. It doesn’t matter if it gets it from its init method, a file on disk, Core Data, a database, etc.

Because we are encapsulating the state of our view in such a way this has several benefits.

We don’t need to test the UI

In terms of standard controls we don’t need to test our UI’s at all since the controls are just binding their state to the view model. Apple should be testing the controls that we are using, and you should be testing the custom controls you create. This means that as we bind our controls state to the view model we don’t need to query the controls for their state as we should be able to access it within the view model itself. This feature tends to lending itself well to the next feature…

We can easily Unit Test the View Model

The View model has access to all the properties the views are binding to, and because of this we can have validation logic on the view model. This also makes it extremely easy to unit test the model and unit test the various states our UI can get into. I think Justin actually phrased this excellently “A good litmus test for MVVM is whether you’re able to write automated tests for your UI behavior without actually having a live UI.” I completely agree with this and think it excellently encapsulates the core idea of MVVM.

Its easier to change the UI

Because the UI is just binding to the view model, this means you should be able to swap components out and just bind the apppropriate properties to the view model and your UI should work the same as before. This should also make it easier for UI designers to experiment around with different views in your app.

ReactiveCocoa: An introduction

As I mentioned ReactiveCocoa is an implementation of Reactive Extensions .NET for Cocoa. The API is not an exact mapping of the API from Rx to Cocoa as explained in the project docs. ReactiveCocoa is also built using the concept of Functional Reactive Programming.

Functional Reactive Programming (FRP) is a programming paradigm for writing software that reacts to change.

FRP is built on the abstraction of values over time. Rather than capturing a value at a particular time, FRP provides signals that capture the past, present, and future value. These signals can be reasoned about, chained, composed, and reacted to.

By combining signals, software can be written declaratively, without the need for code that continually observes and updates values. A text field can be directly set to always show the current timestamp, for example, instead of using additional code that watches the clock and updates the text field every second.

Signals can also represent asynchronous operations, much like futures and promises. This greatly simplifies asynchronous software, including networking code.

One of the major advantages of FRP is that it provides a single, unified approach to dealing with different types of reactive, asynchronous behaviors.

Lets jump right into ReactiveCocoa through a couple examples and explain what is going on.

[RACAble(self.name) subscribeNext:^(NSString *newName){
    NSLog(@"Name changed to %@",newName);
}];
self.name = @"Hypnotoad";
self.name = @"Nibbler";

When this runs it’ll give the output “Name changed to Hypnotoad” and then “Name changed to Nibbler”. What we did was create a signal around a key path in self, and then subscribed to that signal and received events on the stream from that signal. Think of it this way, once we create a signal around a key path in this manner anytime the value of that key path changes the signal will see this and send a -next signal with the updated value. We automatically subscribed to this signal when we called -subscribeNext on it.

Signals only send 3 types of messages

  • next : This is how we get updated values from the stream
  • error : This is sent anytime the signal could not complete
  • competed : Sent to let you know that there will be no more signals on the stream

Lets create a signal of our own so you can see what is going on here

-(RACSignal *)urlResults {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    NSError *error;
    NSString *result = [NSString stringWithContentsOfURL:
                  [NSURL URLWithString:@"http://www.google.com"]
     encoding:NSUTF8StringEncoding
        error:&error];
    if (!result) {
        [subscriber sendError:error];
    } else {
        [subscriber sendNext:result];
        [subscriber sendCompleted];
    }
    return nil;
 }];
}

Although we could achieve this through other means, I wanted to create this manually. This method returns a signal which was created to get the string contents of a URL address and then return them to us. For this I used NSStrings built in method to retrieve a string from a URL. All we need to do is check to see if we have a result and if we don’t then we can send -next and then -completed because we don’t intend to send anymore messages.

Besides receiving updated values which we’ll likely use for assignment to variables, signals also can be used in validation.

NSCharacterSet *charSet = 
   [NSCharacterSet characterSetWithCharactersInString:@" "];
RACSignal *nameFieldValid = [RACSignal combineLatest:
 @[ self.usernameField.rac_textSignal, 
  self.passwordField.rac_textSignal ]
 reduce:^(NSString *username, NSString *password) {
    return @((username.length > 0) && (password.length > 0) &&
            ([username rangeOfCharacterFromSet:charSet].location 
              == NSNotFound));
 }];

This particular example would work on iOS if you had a Username field, password field and you wanted to know if it was filled out correctly. For the purposes of this example we will only concern ourselves with making sure the username & password has a length greater than 0 and doesn’t have any spaces in the user name. The combineLatest part of the method makes sure that we get the latest values from the textfield signal, then in the reduce section we are simply returning a number (0 or 1) to indicate if this is valid. When we hook this up to the enabled property of a control we get…

RAC(self.loginButton.enabled) = nameFieldValid;

and from there on out we get a button that is automatically enabled & disabled when the correct conditions arise from the signal we binded it to. Similarly we can bind controls to a view model like so…

RAC(self.textField.text) = RACAble(self.viewModel.title);

What is going on here is that ReactiveCocoa is implicitly setting up all the necessary infastructure to bind a field to a signal. If you expand the RAC fields you get something like…

[RACSubscriptingAssignmentTrampoline trampoline][ 
[[RACSubscriptingAssignmentObjectKeyPathPair alloc] initWithObject:self 
keyPath:
@(((void)(__objc_no && ((void)self.self.resultLabel.string, __objc_no)),
 "self.resultLabel.string"))] ] = 
 [self rac_signalForKeyPath:@(((void)(__objc_no && 
 ((void)self.self.aTitle, __objc_no)), 
  "self.aTitle"))observer:self];

Be thankfull you don’t have to write all that every time you wanted to bind properties in your code.

What is the ViewModel?

So i mentioned the View Model earlier as being the thing that our user interface binds its properties to as well as containing the actions that can be done to the view model and any validation logic. Lets show a simple example and get started figuring out how the VM in MVVM works. Here is a screenshot of the UI we’ll work with…

And here is the ViewModel interface…

#import <Foundation/Foundation.h>

@interface CDWPlayerViewModel : NSObject

@property(nonatomic, retain) NSString *playerName;

@property(nonatomic, assign) double points;
@property(nonatomic, assign) double stepAmount;
@property(nonatomic, assign) double maxPoints;
@property(nonatomic, assign) double minPoints;

@property(nonatomic, readonly) NSUInteger maxPointUpdates;

-(IBAction)resetToDefaults:(id)sender;

-(IBAction)uploadData:(id)sender;

-(RACSignal *)forbiddenNameSignal;

-(RACSignal *)modelIsValidSignal;

@end

and the implementation

#import "CDWPlayerViewModel.h"

@interface CDWPlayerViewModel ()
@property(nonatomic, retain) NSArray *forbiddenNames;
@property(nonatomic, readwrite) NSUInteger maxPointUpdates;
@end

@implementation CDWPlayerViewModel

-(id)init {
    self = [super init];
    if(!self) return nil;

    _playerName = @"Colin";
    _points = 100.0;
    _stepAmount = 1.0;
    _maxPoints = 10000.0;
    _minPoints = 0.0;

    _maxPointUpdates = 10;

    //I guess we'll go with the ned flanders bad words
    //change this to whatever you want
    _forbiddenNames = @[ @"dag nabbit",
                      @"darn",
                      @"poop"
                      ];

    return self;
}

-(IBAction)resetToDefaults:(id)sender {
    self.playerName = @"Colin";
    self.points = 100.0;
    self.stepAmount = 1.0;
    self.maxPoints = 10000.0;
    self.minPoints = 0.0;
    self.maxPointUpdates = 10;
    self.forbiddenNames = @[ @"dag nabbit",
                          @"darn",
                          @"poop"
                          ];
}

-(IBAction)uploadData:(id)sender {
    @weakify(self);
    [[RACScheduler scheduler] schedule:^{
        sleep(1);
        //pretend we are uploading to a server on a backround thread...
        //dont ever put sleep in your code
        //upload player & points...

        [[RACScheduler mainThreadScheduler] schedule:^{
            @strongify(self);
            NSString *msg = [NSString stringWithFormat:
                @"Updated %@ with %.0f points",self.playerName,self.points];

            UIAlertView *alert = [[UIAlertView alloc]
                   initWithTitle:@"Upload Successfull" message:msg delegate:nil
                     cancelButtonTitle:@"ok" otherButtonTitles:nil];
            [alert show];
        }];
    }];
}

-(RACSignal *)forbiddenNameSignal {
    @weakify(self);
    return [RACAble(self.playerName) filter:^BOOL(NSString *newName) {
        @strongify(self);
        return [self.forbiddenNames containsObject:newName];
    }];
}

-(RACSignal *)modelIsValidSignal {
    @weakify(self);
    return [RACSignal
            combineLatest:@[ RACAbleWithStart(self.playerName),
                            RACAbleWithStart(self.points) ]
            reduce:^id(NSString *name, NSNumber *playerPoints){
                @strongify(self);
                return @((name.length > 0) &&
                (![self.forbiddenNames containsObject:name]) &&
                (playerPoints.doubleValue >= self.minPoints));
            }];
}

@end

A short note about @weakify(self); and @strongify(self);, this is one of the things you can do in addition to using __weak id bself = self; in your apps to avoid retaining self. This particular bit of code is from libextobjc which is used by ReactiveCocoa and thus available to you. In particular this has the same effect of creating a weak reference to self. I like this approach because you just keep using self.[property]... in your code and you don’t have to constantly remember to create a bself variable. Check out EXTScope.h in libextobjc.

as you can see its relatively simple because we are only really concerned with a couple properties related to the player. The other properties are for controls to bind to and for some validation. We also have a single action method and a couple signals. The one thing you’ll notice is the View Model has no clue what the UI it’ll bind to is like at all. This is great because it means you have flexibility in what you bind things to and you can hook up to the view model in ways that make sense for the class thats binding to it.

Now lets look in our ViewController and how it is using these properties and signals…

__weak CDWViewController *bself = self;

To make sure we don’t retain self in our blocks we need to use a weak reference. The ReactiveCocoa Project also has @weakify and @strongify for doing this in blocks, but i’ll let you investigate that and see if you want to use it.

//Create the View Model
self.viewModel = [CDWPlayerViewModel new];

obviously start with creating a ViewModel instance

//Start Binding our properties
RAC(self.nameField.text) = 
[RACAbleWithStart(self.viewModel.playerName) distinctUntilChanged];

[[self.nameField.rac_textSignal distinctUntilChanged]
 subscribeNext:^(NSString *x) {
    bself.viewModel.playerName = x;
}];

The first control is the UITextField for the player name, so we need to bind its text property to the view models playerName property. We also need to make sure we update the view model with updates from the text field. This ensures that the text field receives any updates from the view model and also makes sure that the view is updating the player name property on the view model.

//the score property is a double, RC gives us updates as NSNumber which we just call
//stringValue on and bind that to the scorefield text
RAC(self.scoreField.text) = [RACAbleWithStart(self.viewModel.points)
 map:^id(NSNumber *value) {
    return [value stringValue];
}];

We need to bind the labels text property to the view models points property. The view models points property is a double, but ReactiveCocoa gives us updates to this as NSNumber’s so we need to map this to a NSString which the label can use.

//Setup bind the steppers values
self.scoreStepper.value = self.viewModel.points;
RAC(self.scoreStepper.stepValue) = RACAbleWithStart(self.viewModel.stepAmount);
RAC(self.scoreStepper.maximumValue) = RACAbleWithStart(self.viewModel.maxPoints);
RAC(self.scoreStepper.minimumValue) = RACAbleWithStart(self.viewModel.minPoints);

Simple binding and setup. Give the stepper the initial value from the view model and bind the properties (stepValue,min,max) to the view model.

//bind the hidden field to a signal keeping track if
//we've updated less than a certain number times as the view model specifies
RAC(self.scoreStepper.hidden) = [RACAble(self.scoreUpdates) 
map:^id(NSNumber *x) {
    return @(x.intValue >= bself.viewModel.maxPointUpdates);
}];//only take the maxPointUpdates number of score updates
[[RACAble(self.scoreStepper.value) take:self.viewModel.maxPointUpdates]
 subscribeNext:^(id newPoints) {
    bself.viewModel.points = [newPoints doubleValue];
    bself.scoreUpdates++;
}];

We’ll enforce a rule from the view model that at any given time you can only update the points 10 times. To do this I created a NSUInteger property (in fact the only property we ever actually add to the view controller.) Then bind the hidden property to a signal which reduces to a 0 or 1 based on if the number of times we’ve updated is greater or equal to the number of times we’ve updated the points. So as soon as it hits the number we want this will return 1 and flip the hidden property to YES. To update the points we subscribe to the value property of the stepper and anytime it updates we update the view model and increment the player points.

//this signal should only trigger if we have "bad words" in our name
[self.viewModel.forbiddenNameSignal subscribeNext:^(NSString *name) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Forbidden Name!"
                           message:[NSString stringWithFormat:
                           @"The name %@ has been forbidden!",name]
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    [alert show];
    bself.viewModel.playerName = @"";
}];

If you remember the view model has a validation signal which indicates if any names given are forbidden. My list is really bad and not representative of what I personally think are bad words by any stretch of the imagination. The beauty of this is that we don’t need to know any of the details of what the view model thinks is a “bad word”, but it can just provide a signal to indicate that it thinks something should be forbidden. The view model can provide signals for many things like this that it thinks are important to let you know about it. In this case all we’ve decided to do is show an alert view and reset the player name.

//let the upload(save) button only be enabled when the view model says its valid
RAC(self.uploadButton.enabled) = self.viewModel.modelIsValidSignal;

Another signal that the view model provides to us is a signal letting us know if the view model as it exists it valid or not. In this case i’ve hooked this signal to the enabled property of the upload button. So we should not be able to upload the player stats if the state of the view model is bad. The signal here is simple

-(RACSignal *)modelIsValidSignal {
    @weakify(self):
    return [RACSignal
            combineLatest:@[ RACAbleWithStart(self.playerName), 
                            RACAbleWithStart(self.points) ]
            reduce:^id(NSString *name, NSNumber *playerPoints){
                @strongify(self);
                return @((name.length > 0) && 
                     (![self.forbiddenNames containsObject:name]) 
                  && (playerPoints.doubleValue >= self.minPoints));
            }];
}

So for the purposes of this simple demo, we are just concerned if the name length is greater than 0, the name isn’t in the forbidden names and the points are greater than the minimum. Really we should be concerned with more, but I won’t extend it further. We could even just put the forbiden names signal in if we changed it to use map and return a NSNumber with 0 or 1 and so we could use it here inside this signal.

//set the control action for our button to be the ViewModels action method
[self.uploadButton addTarget:self.viewModel
                      action:@selector(uploadData:)
            forControlEvents:UIControlEventTouchUpInside];

The button is set to trigger the View Mode’s upload data action. This method in the sample code simulates uploading something then presents an alert view letting you know about the success of uploading.

//we can subscribe to the same thing in multiple locations
//here we skip the first 4 signals and take only 1 update
//and then disable/hide certain UI elements as our app
//only allows 5 updates
[[[[self.uploadButton rac_signalForControlEvents:UIControlEventTouchUpInside]
   skip:(kMaxUploads - 1)] take:1] subscribeNext:^(id x) {
    bself.nameField.enabled = NO;
    bself.scoreStepper.hidden = YES;
    bself.uploadButton.hidden = YES;
    }];

Here since there is already signals enabling the button now the number of uploads need to be limited. This is subscribing to the signal for the UIControlEventTouchUpInside event and on the nth update where n is kMaxUploads. On the nth update the namefield is disabled, and the score stepper and upload buttons are hidden.

All of this results in a UI that just binds its properties to a view model, sets its actions to actions on the view model and receives signals from the view model indicating things of interest. I admit this particular example is a bit weird, but it demonstrates using a view model and using the basic aspects of ReactiveCocoa. There is a lot more to ReactiveCocoa in particular that I haven’t shown here for the sake of not introducing too many concepts all at once. Additionally we could build some better view models for dealing with networking code and could deal with child view controllers, but that will have to wait for another article.

So what have we seen here?

  • MVVM stands for Model-View-ViewModel
  • The View model contains things like properties to bind to, validation logic and actions to be done to the view model
  • The View Model should not know anything about the UI that will bind to it
  • ReactiveCocoa is an implementation of many of the API’s in Microsofts Reactive Extensions for .NET in Cocoa
  • We learned how to bind & subscribe to properties
  • We learned how to create signals

The biggest thing you can see with reactive cocoa is that all the code and signals are just reacting to events. When we chain these responses together and filter events properly we heavily reduce the need to create tons of variables and methods just to keep track of the events going on. This leads to more reliable code and with the view model we can easily test it and simulate a UI without actually having a live UI in our app.

The complete source code thats shown here is located here https://github.com/Machx/MVVM-IOS-Example.

So check out ReactiveCocoa on github, and I’ve provided some helpful links at the bottom to help understand these concepts. If people want i’ll dive deeper into ReactiveCocoa in later articles.

Update Since first publication this article has been updated to address a couple minor issues

  • Make sure we don’t retain self in blocks
  • Update a piece of code where -map could simply be used in place of -combineLatest:reduce:
  • The github sample code repo code has been updated

Reference Source : Here

Thanks 🙂 Keep Coding 🙂

SolutionPointLogo

iConcept : Cocoa Design Patterns

Cocoa Design Patterns

A Design Pattern is a reocurring solution to a common software engineering problem. The idea behind design patterns is to not continually reinvent the wheel.

Design Patterns differ from Templates in that they do not contain executable code. http://goo.gl/OeSCu

An example of a Design Pattern is the Listener (Observer). A Listener is an object which waits for information from another object. Now, it is clear that this is a very useful basic idea. Listeners are used in all aspects of Mac OS X and Cocoa for many purposes, not the least of which is GUI management. However, rather than stumble over the same design issues whenever you need to implement a type of listener, the Listener is a documented design pattern that features prepared solutions to these issues. You don’t need to discover for yourself that all the Observers for an object can be stored in a single array, because this is included in the Design Pattern.


Question: Is there any place on the net to discuss advanced programming techniques, problems arising when trying to apply patterns and similar (preferably related to CeePlusPlus), just like this WikiWikiWeb is?

How about the Portland Pattern Repository? http://www.c2.com . It’s the first WikiWikiWeb.


Digest/Directory of standard Gang of Four design patterns in Cocoa

It is informative to note that many of the famous design patterns in “Design Patterns” were first recognized in NeXTstep, a precursor to Cocoa, and in fact “Design Patterns” provides many such citations. Many of the patterns exist within Cocoa with different names than the Gang of Four gave them for the “Design Patterns” book.

The following is a digest/directory of standard Gang of Four design patterns and their names, roles, and relationships within Cocoa. For each pattern, there are links to pages within this site including discussions, named Cocoa classes that participate in the patterns, and commentary about the patterns in the context of Cocoa.

The place to start is Apple�s own design patterns documentation https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/DesignPatterns”

>CocoaDesignPatterns/DesignPatterns”>CocoaDesignPatterns.html

*Abstract Factory

Creates an instance of several families of classes *

NSObject Objective-C class methods are sometimes call factory methods. This pattern is intrinsic to the Objective-C language. Every Objective C class is potentially an abstract factory. This pattern is also used to implement CocoaClassClustersSubClass“>ShouldClassClusterPlaceholderBeASubClass

http://developer.apple.com/documentation/Cocoa/Conceptual/DesignPatterns”

>CocoaDesignPatterns/index.html

*Builder Separates object construction from its representation *

NSDocumentManager? � Builds NSDocument instances with NSWindowManager(s), handles recent documents menu, builds document related responder chain� NSApplication? � Builds main menu, initial responder chain, run loop�

*Factory Method Creates an instance of several derived classes *

Objective-C class methods are sometimes call factory methods. This pattern is intrinsic to the Objective-C language. NSObject ClassClustersSubClass“>ShouldClassClusterPlaceholderBeASubClass

http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/index.html

*Prototype A fully initialized instance to be copied or cloned *

NSCell is a Prototype when used with NSMatrix.

*Singleton A class of which only a single instance can exist *

Structural Patterns

*Adapter Match interfaces of different classes *

*Bridge Separates an object�s interface from its implementation *

*Composite A tree structure of simple and composite objects *

*Decorator Add responsibilities to objects dynamically *

*Facade A single class that represents an entire subsystem *

NSImage – NSText and NSTextView encapsulate the functionality of complex text layout and editing which is internally implement with NSTextStorage, NSLayoutManager, and other classes.

*Flyweight A fine-grained instance used for efficient sharing * NSCell

*Proxy An object representing another object *

Behavioral Patterns

*Chain of Resp. A way of passing a request between a chain of objects *

*Command Encapsulate a command request as an object *

*Interpreter A way to include language elements in a program *

Value Transformers?

*Iterator Sequentially access the elements of a collection *

*Mediator Defines simplified communication between classes *

NSObjectController, NSArrayController, NSTreeController, and NSUserDefaultsController http://developer.apple.com/documentation/Cocoa/Conceptual/DesignPatterns”

>CocoaDesignPatterns/index.html

*Memento Capture and restore an object’s internal state *

NSCoder NSKeyedArchiver and NSKeyUnarchiver http://developer.apple.com/documentation/Cocoa/Conceptual/DesignPatterns”

>CocoaDesignPatterns/index.html

*Observer A way of notifying change to a number of classes *

*State Alter an object’s behavior when its state changes *

*Strategy Encapsulates an algorithm inside a class *

NSLayoutMananger NSFormatter?

*TemplateMethod Defer the exact steps of an algorithm to a subclass *

*Visitor Defines a new operation to a class without change *

Cocoa Unique Patterns

*Target/Action A variation/simplification of the Command pattern *

NSControl NSActionCell @selector Similar to Qt Signals & Slots

*Method Swizzling A technique for runtime modification of the relationship between message selectors and the implementation that will be called in response to a message *

*Delegation Enable one object to control, modify, or specialize the behavior of another object through a loosely coupled interface.

This is really an example of the Strategy design pattern. In fact if you look at the “Application” algorithm implemented as a Strategy in Rob Martin’s Agile Principles, Patterns, and Practices you see NSApplication + AppDelegatereproduced almost exactly.

Reference : Source Here

iConcepts: How to Interview Programmers

How to Interview Programmers

Reference Source : Here

Google has finally come clean that they figured out what many of us have been repeating for years: brain teasers in interviews don’t lead to measurably better employee outcomes.

I’ve never interviewed at Google but I did interview at a company that asked me a “brain teaser” question. It wasn’t one off of the shelf, but based on natural conversation (I mentioned I was a frequent-flier, so I had to calculate some aviation-related things that were very similar to “Guess the # of piano tuners in NYC”.). It was very difficult to resist the urge to blurt out: “Do you have any idea what you are doing?”

These aren’t just wacky – they’re stupid. Not only do these questions bear little resemblance to anything we do in software development, it’s lazy to use brain-teasers. “Let’s spend 30 seconds thinking up a few puzzles then have the candidate spend a few hours answering them.” Recruiting should be your number one priority! Treat it like it’s more important than the semi-annual flossing you do the the day before your dentist appointment, ok?

I have gotten too many job offers after inadequate interviewing to think that interview incompetence is anything but prevalent in our industry. Luckily for them, I’m excellent at what I do, but plenty of other startups lose the hiring lottery. You don’t need to be one of them!

Over the years I’ve refined my process to weed out people from the very start and provide repeatable, scalable interviews that organizations can trust.

Preconditions

Hiring is the most important thing you can do as an organization. Yes, more important than building software, selling it, and cashing fat checks. Without your people, your organization is nothing. You’ll need to trust them to act independently with minimal oversight.

The interview process starts long before candidate XYZ lands on your jobs page.

Before you hire your first person
  • Figure out your culture. Most startup CEOs/Founders/CTOs that I talk to have no discernible idea what their culture is. How can you hire for cultural fit if you don’t know what it is?
  • Make sure everyone on the team interviews every candidate. If you’re large enough, include people from other teams.
  • Make sure everyone on the team knows how to interview, based on a checklist/plan. Instead of Bob asking the same SQL questions that he came up with in 1993, have a guide that each person can consult. Have each person write down what they are going to talk about and go through it as a group. What are you trying to look for? How do you know if you found the answer?
  • Don’t ask the same thing twice. I’ve been in day-long interviews and had to “tell [person X] about [myself]?” six times. I didn’t accept an offer at that company: clearly they have communication and organizational problems.
  • Conduct mock-interviews to level up your hiring capability.
  • Have your developers take the coding challenges so they can provide intelligent guidance (and make sure that the challenge works / is still relevant. I’ve been in an interview where the coding challenge had an unintentional bug and wouldn’t work as stated.)
During the interview tips
  • Be open and honest. Power distance in interviews is heavily in your favor; be the first to offer salary and equity ranges for the position. Don’t ask them “what’s your bottom line salary?” – you should have a well-defined technical ladder that outlines the career path of a developer within your company. No tricks, just fair, equitable, and transparent progress.
  • Tailor the interview to the candidate. If someone has spent 30 years writing compilers, don’t ask them “What is a pointer?”. For someone fresh out of school, ask more CS-y questions. Many companies have the same set of Q&A for every candidate and it shows both a lack of effort and turns candidates away. If you’ve gone to the trouble to bring a candidate into the office, don’t waste your and their time – researching the candidate shows that you are truly interested in them and what they have to offer.
  • Don’t “lead the witness”. I’ve sat in depressingly many interviews (on both sides of the table) where someone asked a question like: “So, do you perform Test Driven Development or do you simply ‘Cowboy Code’”? Any smart candidate, regardless of whether or not they’ve even heard of TDD, will read between the lines and tell you exactly what you wanted to hear.
  • Ask topgrading-style questions and be careful not to let your biases be used against you.
  • Have your shit together. Make sure that the person who is helping the candidate out gets everyone in the right place at the right time. The candidate is interviewing you and your organization as much as you are interviewing them. The best candidates are interviewing at companies that getthis.
  • Make lunch reservations at a nice sit-down restaurant. The best teams eat lunch together.
Post-interview
  • Everyone must give a thumbs up or thumbs down (and why, based on the above). The rationale is just as important as the rating. Why do or don’t they fit the culture? Why will they raise the collective skills of the team (you do measure that, right?). If you don’t like the color of the t-shirt they wore to the interview, tough. That’s not a reason to not hire someone.
  • If they are going to be issued an offer, send it ASAP.
  • If not, thank them for their time and explain they will not be moving forward. Do this as soon as possible.

Pre On-Site Interview

Initial phone screen (30-45 minutes)

Just a few background questions (why are you looking for a job, what sounds interesting about what we are doing, what is your current salary, etc.). (This should take about 30-45 minutes.) The goal is to make sure the interviewee meets your “deal-breakers” (you should have a list) and vice-versa, and minimize the amount of people who slip through the cracks that later don’t take an offer (or you don’t issue one) because of knowable conditions that wouldn’t allow them to be successful in the role.

Be sure to talk about the company culture, how the company makes money (being profitable helps), the fundraising situation, how large it is, etc. – these answers will help a candidate self-select to move forward in the process. If they don’t want to work at a 3 person startup – why waste your and their time by continuing with phone screens and on-site interviews?

For example, if you don’t allow work-from-anywhere, be up front and explain that in this interview. Most programmers expect it nowadays (and you’re silly if you don’t offer it). Why spend thousands of dollars to fly them out only to have them turn down your offer because of that?

Second phone screen (1-2 hours)

After the deal-breaker conversation, at least you and the candidate are not immediately disqualified. Now, let’s figure out if they actually can program. Ask a bunch of topgrading questions then a few FizzBuzz-style questions to make sure they can actually program.

For the coding challenges, I use some sort of screen-share program like TeamViewer. I ask them to open a REPL in the language of their choice and write a series of simple programs (I construct a special URL that has the instructions they can use so I don’t have to read it over the phone).

They are not fizz-buzz (because folks have figured out they need to know it) but similar time/space challenges.

On-Site Interview

If they pass these, then bring the person out for a day of in-person interviews (flying first-class, provided it’s not prohibitively expensive, picked up at the airport in a nice car, all that jazz).

If the candidate is at all good, they will be fielding many offers – if you can take care of them from the start of the process it will help you stand apart from the crowd. Don’t go overboard – a driver in a tux sends a strange message – but show that you care.

Day’s events

  • Tour the office, show off the fancy espresso machine in the break room, etc.
  • Explain the day’s events (basically, show them this list)
  • A few programming challenges (of increasing difficulty) that involve stuff the candidate would use on the job, extracted from, or related to, our problem domain.
  • Lunch
  • Then pair programming for the rest of the day to make sure we can all get along with this person (continuing through the next day if possible).
  • Fancy car ride back to their hotel (not the airport). Try and give them more than a day in your city; if you have the budget, give them the whole weekend.

Programming Challenges (2-4 hours)

You need to see if this person can solve challenges that are harder than FizzBuzz but won’t take them 3 weeks. They should be difficult enough that they can’t solve it by memory but not require much esoteric knowledge (unless you’re looking for that). It’s “open-book” – Google, Stack Overflow, etc.

In the initial interview I ask their preferred development environment (OS, editor, etc.) and setup a computer thusly, so that they should feel more-or-less at home. Alternately, if it’s specialized enough, I have them bring in their own laptop and work off of that.

I have a Github repository that is already setup with a basic test suite and a bunch of problem sets that they can choose from. If you are setting out to build this repo from scratch, I highly suggest something like RubyQuiz or maybe CodeQuizzes.

For example, you might have them implement a local script that takes either a Zip code or city name and prints out the current weather.

The goal is to see if they can solve a real-world problem that either we have solved or is representative enough of what we do on a daily basis to be a good predictor of future performance (weather involves dealing with/parsing an API, and how do you automatedly-test a 3rd party API?).

Lunch

Self-explanatory. Have lunch, break bread with them. Everyone on the team attends. This is the proverbial “have a beer with them?” test. Let them lead, ask them open-ended questions.

Pair Programming

If you had the applicant sign an NDA that grants the company ownership of the code, (you don’t want them to work on production code, then come back later and claim that you owe them some equity or compensation) have each developer prepare some tasks on the real code-base that are complicated and require some problem solving. Often I find some bugs that I think are tricky, track down the solution (but I don’t fix it), then I can have them try it. Debugging requires building up complex mental models of how the code works, and it also tests how they might react when presented with difficult problems.

If they haven’t/won’t sign an ownership agreement (I’ve never had someone do this) then take some open-source project you use and have them work on adding some new functionality to it that you need. Contributing to Open Source Software should be a core part of your business – and the licensing means that your business is not put at risk.

Reference Checks

July 2 update. An anonymous commenter asked about reference checks. They completely slipped my mind, but in my experience the value of the reference check is pretty variable. I’d be curious to see if Google has any data that suggests it’s a good predictor of future success.

At bigger companies, legal has beaten into everyone’s heads that reference checks are sources of liability and should stick to factual information only: Did such-and-such work here, for the terms stated (the role and time-frame), and at what salary, etc.

I’ve never been able to extract actual meaningful information, but sometimes you can read between the lines.

At smaller companies, you’re much more likely to get the founder/CTO on the line and chat about their work habits. Of course, the candidate hand-picked these people because they are going to give a rosy picture – all reports you get must be taken with a grain of salt.

If you get a reference that gives a negative picture, I suppose that is a good reason to cut and run, but I can’t imagine any candidate worth hiring would make that sort of mistake. For me the only question I need answered is: “Would you hire XYZ again?” – if it’s a “no”, then I tend to run.

I’ve heard some folks do friend-of-a-friend – ask people who no longer work there about candidate XYZ. Personally I’ve never done it but I can see that might be more diagnostic, but I think the ethics are probably pretty dicey.

(What is better – candidates should interview former employees. Really interesting. Same grain of salt applies; I’ll follow-up later in a “How to interview companies” post.)

Longer-Term

If possible, put a new hire on a 1 month contract before you make a final offer. The contract rate is the equivalent salary for the position, but you need more data to make sure it’s a fit. If they are clearly not a fit, give them a generous severance and assistance in finding a job elsewhere.

If they are a fit, issue a final offer (using the same salary as before) with the equity grant (how can you judge future multiplier potential after one interview?).

I understand not every candidate can and will agree to a one-month contract. In that case, make them an offer, slot them in to your ladder where you expect, but withhold the equity component until the end of the month, unless it’s a standard amount (the later the stage of the company, the less variable the equity calculations).

Update:

Evan Hensleigh (@futuraprime) notes:

“Good advice! But I’m not sure about the contract period. You might be turning away good people who need, e.g., health insurance.”

Fair point. In that case, I’d be more than happy to offer a bump in the contract rate to include 1 month of their previous employer’s COBRA. Ultimately, most US states are “at will” employment – you can be fired at any time for any reason. A few benefits aside (which can be resolved) being fired after one month is functionally equivalent (provided you treat the employee as a contractor under the rules of your state).

Thanks 🙂 Keep Coding 🙂

SolutionPointLogo