Clean Code | Introduction | Quick Notes


A handbook of agile software craftsmanship by Robert C.Martin.

Writing clean code is what you must do in order to call yourself a professional, there is no excuse to do anything less than your best.

In this series of quick notes, I am going to share the quick notes from this book with you, So welcome aboard, let’s start with the introduction.

So think 2 mins, what is the valid measurement of code quality for you? The answer according to the book is funny but its WTFs/minute. haha ūüôā Now you can easily measure the quality of your code.

Next question will be, How to handle bad code? the answer is Craftsmanship. There are two parts of learning Craftsmanship: Knowledge and Work. It means you must gain the knowledge of principles, patterns and best practices and you must also grind the knowledge into your finders, eyes by working hard.

Yes, that’s why this book is divided into three parts.

  1. First will teach you principles, patterns, and best practices.
  2. Second, Case studies of ever-increasing complexity. Here you have to think and give the reason for making each change.
  3. Third, a list of heuristics and smells gathered while creating the case studies.

Thanks for reading this, I am also including what I like most and I must recommend this book to each and every person who is responsible for writing/reviewing code. For more just buy the book.

How to Respond to an Authentication Challenge | iOS

How to Respond to an Authentication Challenge

If a session requires authentication it creates authentication challenge


in order for the connection to continue, the delegate has three options.

  • Provide authentication credentials
  • Attempt to continue without credentails
  • Cancel the authentication request.

NSURLProtectionSpace will give all information about the authentication type and failure if any attempts failed earlier.

Providing Credentials

To attempt to authenticate, the application should create an NSURLCredential object with authentication information of the form expected by the server. You can determine the server’s authentication method by calling authenticationMethod on the protection space.

  • HTTP basic authentication (NSURLAuthenticationMethodHTTPBasic) requires a user name and password. P
  • HTTP digest authentication (NSURLAuthenticationMethodHTTPDigest), like basic authentication, requires a user name and password.withcredentialWithUser:password:persistence:.
  • Client certificate authentication (NSURLAuthenticationMethodClientCertificate) requires the system identity and all certificates needed to authenticate with the server. Create an¬†NSURLCredential¬†object.
  • Server trust authentication (NSURLAuthenticationMethodServerTrust) requires a trust provided by the protection space of the authentication challenge.

Continuing Without Credentials

If the delegate chooses not to provide a credential for the authentication challenge, it can attempt to continue without one.

‚ÄĘ NSURLSessionAuthChallengePerformDefaultHandling¬†processes the request as though the delegate did not provide a delegate method to handle the challenge.

  • NSURLSessionAuthChallengeRejectProtectionSpace¬†rejects the challenge. Depending on the authentication types allowed by the server‚Äôs response, the URL loading class may call this delegate method more than once, for additional protection spaces.

Canceling the Connection

The delegate may also choose to cancel the authentication challenge, by passing NSURLSessionAuthChallengeCancelAuthenticationChallenge to the provided completion handler block.

Objective C Days | Memory Management |Short Note to Brush up


Let’s see the traditional C ways for clearing up of unused objects is a bit of a nightmare. There are no ways in the language like how should be approached.

Imagine one function A create one object and pass it to another function B now both are using the same data now the problem is who is: the responsible for deleting it if it no longer used? and let’s say we have one function who is also gonna use the same data than what?

The solution is there are conventions and design patterns to handle these situations,  that’s the reason the reference counting was developed and management technique used in Obj-C.

What we have in Obj-C

Obj-C uses reference counting as its Memory Management Technique so according to that each object keeps an internal count of how many times it’s needed.¬† So only in case of, if count drops to zero. Yes you can compare it with Garbage Collector we have in Java but it’s not like automatic some chunk of code getting executed and removing the objects which ones are not needed.


Most important thing is Object Ownership it means an object owner is someone that has explicitly said: ‚ÄúI need that object, don’t delete‚ÄĚ. So one object can have more than one owner.

If object owner is not using it they have the responsibility to tell so that the reference count should be decreased by one. So while dealing with Obj-C pointers/Objects it’s really good to send correct messages.


alloc, it will allocate a fresh instance of the object, set the reference count +1.

new, shortest way to write alloc&init.

retain, you passed the object and you want to tell you to need that so its reference count should be increased by 1 again.

autorelease, need object temporarily and want to delete once you did with the operations.

copy creates a new copy of the object.

dealloc, opposite of init method, automatically get called right before the object is destroyed.

 Convenience Methods

Static methods used for allocating the initializing objects directly but are aware that you are not the owner of that object, once the scope of your program finish it will be removed.¬† Ex: [NSString stringWithFormat:@‚ÄĚSay %@‚ÄĚ,@‚ÄĚHello‚ÄĚ];

Autorelease Pools

It’s an instance of NSAutoreleasePool, objects which are to be auto released. You can also send a message to autorelease or create object using convenience methods. So once the object added into autorelease pool and when the pool is popped, all the objects will be deleted.

Retain Cycles

Retain cycle is a condition where two objects strongly maintain a reference to each other and stop each other from being released. For example, let we have two classes as.

@interface Parent : NSObject
@property (nonatomic, strong) Child *child;

@implementation Parent

@interface Child : NSObject
@property (nonatomic, strong) Parent * parent;

@implementation Child

So, at some point of time when creating object of any of these class as

Parent *parent = [[Parent alloc] init];
Child *child = [[Child alloc] init];
parent.child = child;
child.parent = parent;

Here the parent object maintaining a strong reference of Child class and child object maintaining a strong reference of Parent class in back. So, both parent and child object having a reference count of one and one. Both objects will get released from memory only when their reference count will reach to zero but in this scenario, this will not be going to happen ever because both are mutually pointing to each other a dead lock is get created here. This situation is called the Retain Cycle that will lead to memory leaks.

Fortunately, it‚Äôs very easy to fix this problem‚ÄĒjust tell one of the properties to maintain a weak reference to the other object so, what‚Äôs this weak and strong reference means??

Strong Reference: A strong reference says that don’t release this object till I m owning this.

Weak Reference: A weak reference says that don’t release this object until someone else pointing this strongly.

Just like strong and __strong, weak and __weak keywords are there for declaring properties and instance variables respectively as a weakly referenced object.

Quick Tips and common mistakes

Think about strong and weak pointers as well as retain cycles, Avoid unnecessary caching, Don’t declare every object  globally unnecessarily, use Xcode Instruments such as static analyzer and find the potential memory leaks and fix them

Arrays, Dictionaries and other objects that contain any object generally retain objects once you add it to them. It means once you create an object the reference count will be 1 and once you add it into an Arrays it will be 2.

Releasing the Object that you don’t own, let’s say if creating a new object using convenience method than there is no need to release that.

Keeping and using an Object that you don’t Own.

Calling dealloc directly. So never call dealloc by the way you have to call init after calling alloc its kinda default constructor for init the default value of the object.

Over-releasing. Accidentally you’re releasing something twice instead of once. You can also track these crashes by just enabling Zombies.

Retain Cycles. When an object released there is a cascading effect, the root object released its children’s as well and so on. Let’s say there is some condition like A owns B and B owns An as they own each other.

iOS | Bounds vs Frame ?

Everyone talk about bounds and frame during the interview for sure. lets make it little easy.

The Bounds of a view is recentagle, expressed as location coordinates (x,y) and also the size (height, width) relative to the own coordinate system.

The Frame of a view is recentagle, expressed as location coordinates (x,y) and also the size (height, width) relative to the its superview.

So for example lets say if you have¬†UILabel¬†on top of your¬†UIView¬†that has size of (100×100) with thelocation coordinates (10,10). so here is the Swift code.

override func viewDidLoad() {

        print("label.bounds.origin.x    = \(label.bounds.origin.x)")
        print("label.bounds.origin.y    = \(label.bounds.origin.y)")
        print("label.bounds.size.height = \(label.bounds.size.height)")
        print("label.bounds.size.width  = \(label.bounds.size.width)")

        print("label.frame.origin.x    = \(label.frame.origin.x)")
        print("label.frame.origin.y    = \(label.frame.origin.y)")
        print("label.frame.size.height = \(label.frame.size.height)")
        print("label.frame.size.width  = \(label.frame.size.width)")

So for the both cases size(height, width) will be same only the position (x,y) will be different as in case of bounds its relative to its own view and for frame its relative to superview. for more please see the below image(source: slideshare, CS 193P lecture).

Screen Shot 2017-05-17 at 11.12.59 AM

Subscripts in Swift ?

Shortest way to access the member elements of collection, list or sequence, means there is no need to create saparate function. lets say you have an array so you can write subscripts for setting and retrieving the value by index. Sounds good ???

Another good thing is we can define number of subscripts based on the type of index value we pass, even we can define subscripts with multiple input parameters, so its all to our need.

The syntax is very much similar to stored property and functions. Just we need to write subscript keyword and specify one or more input paramters and reture type. like the methods subscripts are also read-write or readonly. This behaviour is communicated by the same way we do in computed properties. 

subscript(index: Int) -> Int    {
    get {
        //return value here
    } set(newValue) {
        //set the new value here

the usage is to access the member elements in a collection, list or sequence. For example, Swift’s¬†Dictionary¬†instance. You can set and get the value using¬†Key. if they key does’t exist it will add into the¬†Dictionary.

var priorities = ["Work" : 3, "Family" : 1, "Other" : 4]
priorities["Work"] = 2

Swift’s Dictionary¬†type implements its key-value subscripting, its takes and returns an optional value. if you set the value as¬†nil¬†it’ll remove from¬†Dictionary.

priorities["Work"] = nil

the interseting part what i like is¬†subscripts¬†can take any types of values, n number of value and can return any type of value, but they can’t use¬†in-out¬†parameters and can’t provide default parameters value.

struct Matrix {
    let rows: Int, columns : Int
    var grid : [Double]

    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)

    private func isValidIndex(row: Int, column: Int) -> Bool    {
        return row >= 0 && row < rows && column >= 0 && column < columns

    subscript (row: Int, column: Int) -> Double  {
        get {
            assert(isValidIndex(row: row, column: column))
            return grid[(row * column) + column]
        } set {
            assert(isValidIndex(row: row, column: column))
            grid[(row * column) + column] = newValue

var matrix = Matrix(rows: 2, columns: 2)
matrix[1, 1] = 10.0

print(matrix[1, 1])

Top 10 reasons for iOS app rejection ?

Today apps are changing the world. The App Store has grown into an exciting and vibrant ecosystem for millions of developers. Whether you are a first-time developer or a large team of experienced programmers, we are excited that you are creating apps for the App Store and want to help you understand our guidelines so you can be confident your app will get through the review process quickly.

Here are top 10 reasons for app rejections from Apple.

16% Guideline 2.1 ‚Äď Performance: App Completeness

14% More Information Needed

9% Guideline 4.1 ‚Äď Design: Copycats

8% Guideline 2.3.7 ‚Äď Performance: Accurate Metadata

4% Guideline 3.1.1 ‚Äď Business: In-App Purchase

4% Guideline 2.3.3 ‚Äď Performance: Accurate Metadata

3% Guideline 4.0 ‚Äď Design: Spam

3% Guideline 4.0 ‚Äď Design

3% Guideline 2.3.3 ‚Äď Performance: Accurate Metadata

3% Did Not Comply with Program License Agreement

Failable Numeric Conversion Initializers | Swift 3.1

Swift 3.1 implements failable initializers for all numeric types like Int, Int8, Int16, Int32, UInt, UInt8, UInt16, UInt32, Float, Float80, Double. So which either completely successful without loss of information or simply returns nil.

This feature is very useful let’s see an example.

typealias JSONDictionary = [String: AnyObject]
class Employee  {
    let name: String
    let level: Double
    init?(json: JSONDictionary) {
       guard   let name = json["name"] as? String,
           let levelString = json["level"] as? String,
            let levelDouble = Double(levelString),
            let level = Int(exactly: levelDouble)  // 3.1 feature here
            else {
                return nil
        } = name
        self.level = level

func getEmployees(from data: Data) -> [Employee]?   {
    guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
        let jsonArray = json as? [JSONDictionary]   else {
            return nil

    return jsonArray.flatMap(Employee.init)

let jsonString = "[{\"name\":\"John\", \"level\":\"7.2\"}]"
if let data = .utf8) {
    let employees = getEmployees(from: data)
    print(employees ?? "its Nil")
} else {
    print("Data Nil")