Showing posts with label base. Show all posts
Showing posts with label base. Show all posts

Thursday, July 12, 2018

Swift Protocol Extensions


Protocol extensions is one of the beautiful features of Swift language.

Let’s see the usefulness with a use case.

I have a Logger protocol which is having simple log function which takes string to be logged and logs it.


       
 protocol Logger {
    func log(message: String)
 }



I am taking 3 service classes which has to confirm to this Logger protocol for logging service errors.

       
 class FacebookServices: Logger {
    func log(message: String) {
        print("Facebook - \(message)")
    }
 }

 class TwitterServices: Logger {
    func log(message: String) {
        print("Twitter - \(message)")
    }
 }

 class InstagramServices: Logger {
    func log(message: String) {
        print("Instagram - \(message)")
    }
 }



All the 3 classes are confirming to Logger protocol and implemented interface method log.

Now, What If we need log a generic error like "Service Unavailable”. 

We need to write that in all the 3 classes or we need to take a base class and keep the logGenericError method there.

       
 class FacebookServices: Logger {
    func log(message: String) {
        print("Facebook - \(message)")
    }
    
    func logGenericError() {
        print("Service unavailable!")
    }
 }

 class TwitterServices: Logger {
    func log(message: String) {
        print("Twitter - \(message)")
    }
    
    func logGenericError() {
        print("Service unavailable!")
    }
 }

 class InstagramServices: Logger {
    func log(message: String) {
        print("Instagram - \(message)")
    }
    
    func logGenericError() {
        print("Service unavailable!")
    }
 }



Instead of this, We can extend the Logger protocol and keep our convenient API there which allows all the classes confirming to the portal can access that extension.

       
 extension Logger {
    func logGenericError() {
        print("Service unavailable!")
    }
 }

 let twitter = TwitterServices()
 let facebook = FacebookServices()

 twitter.log(message: "404")
 twitter.logGenericError() // Service unavailable!

 twitter.log(message: "500")
 twitter.logGenericError()  // Service unavailable!




Easy and very useful Right?

We can customise the logGenericError() If a service needs like shown below.

       
 class InstagramServices: Logger {
    func log(message: String) {
        print("Instagram - \(message)")
    }
    func logGenericError() {
        print("Please try later!")
    }
 }

 let instagram = InstagramServices()
 instagram.logGenericError() // Please try later!



Go with Protocol extensions in such use cases instead of going for base classes.

Hope this post is useful. Feel free to comment incase of any queries.



Tuesday, January 16, 2018

Swift Convenience Initializers

A class can have any number of designated Initializers.
In my case It’s a Downloader class which can be initialized using an URL or a String.



We can write 2 designated initialisers for this. Now with URL as parameter and other with String as parameter. Though we can do like this, Keeping an Initializer for each type of parameter, There is an issue here.



All the initialization code has to be duplicated in all designated initializers. Whatever we do in Designated initializer 1 should be kept in Designated Initializer 2 and so on.

To avoid this, we can use convenience initialisers as shown below.



Downloader class can also be instantiated using a url string value also using the convenience initializer. But, A convenience initializer should have to call any one of designated initializers of a class If that class in having only one convenience initializer.




One more use case of convenience initializer is that, We can simplify the initialization process by setting default values.




Here aspectRatio property can be set to a default value to simplify initialization.


Now you understood where and how to use convenience initializers.

  1. To simplify initialization process with default values.
  2. To avoid code redundancy in Designated Initializers.


There are some rules for Designated and Convenience Initializers.

  1. A designated initializer must call a designated initializer from its immediate superclass.
  2. A convenience initializer must call another initializer from the same class.
  3. A convenience initializer must ultimately call a designated initializer.

Take Aways:-


  • Convenience Initializers are just for developer’s convenient way of initializations keeping some parameters as default ones.
  • There is no thumb rule to use convenience initializers. 
  • Convenience Initializers can not be overridden.
  • There are 3 rules for Designated and Convenience Initializers
  • Only classes can have convenience Initializers. Structures can not.



Hope this post is useful. Feel free to comment incase of any queries.




Sunday, May 22, 2016

Objective-C Calling Base class methods from Child class

With in any class implementation 'self' refers to the object of that class and 'super' refers to the parent class.

We can call parent class methods using the 'super' keyword.


Let's see an example in Objective-C.


     
@interface Parent : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end

     @interface Child : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end


Unlike in other programming languages, We don't need to give a prefix 'override' for overridden methods in Objective-C. But the only rule is subclass method should have the same name and property list of base class method for overriding.


     
@implementation Parent

          - (void)thankYou:(NSString*)visitorName{

              NSLog(@"From Parent : Thank you %@", visitorName);
          }

     @end

     @implementation Child

          - (void)thankYou:(NSString*)visitorName{

               NSLog(@"From child : Thank you %@", visitorName);
          }

     @end


In the above example, Whenever there is a visitor, Parent class says thank you when we send a 'thankYou' message to Parent class by calling thankYou method.



     
[parentObj thankYou:@"visitor1"];  // From Parent : Thank you visitor1


In my child class, I need this thankYou method but I want a thank on behalf of my child object. So I need to go for overriding this method as I can write child own logic in the method.



     
[childObj thankYou:@"visitor1"];    // From Child : Thank you visitor1


See, Same functionality but a little customization in the subclass with the help of Method Overriding.

Let's see how can we extend the functionality. I mean I need my Base class method called also first and after that my child class logic. I don't need to replace the functionality of base class. I just need to extend the functionality.


                         



In addition to completely replacing an existing implementation, you might want to extend a superclass's implementation. Here comes the super keyword. Within a method definition, super refers to the parent class of the current object. To call methods in the base class from child class, We can use this super keyword.

For example, I need both my parent and child should thank a visitor but should be properly conveyed.



     
@implementation Child

        - (void)thankYou:(NSString*)visitorName{

             [super thankYou: visitorName];  //calling baseclass method

             NSLog(@"From child : Thank you %@", visitorName);
         }

     @end


If a child object thanks, a visitor gets a thank you from both parent and child. Of course, child is saying on behalf of parent also here. 

Now If you call child object's thank you method,



  [childObj thankYou:@"visitor1"];       //  From Parent : Thank you visitor1

                                                         //  From Child : Thank you visitor1



Hope this post is useful. Feel free to comment in case of any queries.

Objective-C super keyword

With in any class implementation 'self' refers to the object of that class and 'super' refers to the parent class.

We can call parent class methods using the 'super' keyword.



                         


Let's see an example in Objective-C.


     
@interface Parent : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end

     @interface Child : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end


Unlike in other programming languages, We don't need to give a prefix 'override' for overridden methods in Objective-C. But the only rule is subclass method should have the same name and property list of base class method for overriding.


     
@implementation Parent

          - (void)thankYou:(NSString*)visitorName{

              NSLog(@"From Parent : Thank you %@", visitorName);
          }

     @end

     @implementation Child

          - (void)thankYou:(NSString*)visitorName{

               NSLog(@"From child : Thank you %@", visitorName);
          }

     @end


In the above example, Whenever there is a visitor, Parent class says thank you when we send a 'thankYou' message to Parent class by calling thankYou method.



     
[parentObj thankYou:@"visitor1"];  // From Parent : Thank you visitor1


In my child class, I need this thankYou method but I want a thank on behalf of my child object. So I need to go for overriding this method as I can write child own logic in the method.



     
[childObj thankYou:@"visitor1"];    // From Child : Thank you visitor1


See, Same functionality but a little customization in the subclass with the help of Method Overriding.

Let's see how can we extend the functionality. I mean I need my Base class method called also first and after that my child class logic. I don't need to replace the functionality of base class. I just need to extend the functionality.



                         


In addition to completely replacing an existing implementation, you might want to extend a superclass's implementation. Here comes the super keyword. Within a method definition, super refers to the parent class of the current object. To call methods in the base class from child class, We can use this super keyword.

For example, I need both my parent and child should thank a visitor but should be properly conveyed.



     
@implementation Child

        - (void)thankYou:(NSString*)visitorName{

             [super thankYou: visitorName];  //calling baseclass method

             NSLog(@"From child : Thank you %@", visitorName);
         }

     @end


If a child object thanks, a visitor gets a thank you from both parent and child. Of course, child is saying on behalf of parent also here. 

Now If you call child object's thank you method,



  [childObj thankYou:@"visitor1"];       //  From Parent : Thank you visitor1

                                                         //  From Child : Thank you visitor1



Hope this post is useful. Feel free to comment in case of any queries.

Objective C Polymorphism

Before discussing Polymorphism, Please have a look at Dynamic Binding which enables Polymorphism.

Polymorphism comes when we have hierarchy of classes with Method overriding.


                         



Let's take a BaseClass and Subclass. In my case, this is Parent and a Child. Both of them having a similar action like 'doYourJob'. Though it's a similar kind of job, both Parent and Child have to implement them differently.



 @interface Parent : NSObject

   - (void)doYourJob;

 @end

 @interface Child : Parent

   - (void)doYourJob;


 @end





   
Parent * parentObj = [Parent alloc] init];
   [parentObj doYourJob];   //go to OFFICE


   Child * childObj = [Child alloc] init];
   [childObj doYourJob];     //go to SCHOOL


When we call 'doYourJob' method on parent object, parent object's method will get called. If we call that on child object. child object's method will get called which performs a different action.

Thus, Based on the object which is calling the method, The respective method will get called. This is called Polymorphism, having different forms. Dynamic Binding enables this.


Hope this post is useful. Feel free to comment in case of any queries.


                         



Friday, May 20, 2016

Objective-C Method Overriding

We override methods in Base class in child classes to,

  • Replace/Customize the base class functionality
  • Extend the base class method's functionality

If you need to add allover new functionality to a class, I would like to suggest Categories. Use Method overriding only when you need to replace/extend the base class original functionality.

Please go through my post Objective C Subclass vs Category to get an idea on when to go for Categories and when to go for SubClassing.

Talking about Method overriding, Let's have a look at the basic definition of it first.


                         



Method overriding is a language feature in which a class can provide an implementation of a method that is already provided by one of its parent classes. The implementation in this class replaces (that is, overrides) the implementation in the parent class.

When you define a method with the same name as that of a parent class, that new method replaces the inherited definition. The new method must have the same return type and take the same number and type of parameters as the method you are overriding.

So, as per the definition, With the help of Method overriding feature in OOP, We have an option to extend/replace the base class functionality in a child class as per our requirement.

Let's see an example in Objective-C.



     
@interface Parent : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end

     @interface Child : NSObject  

     - (void)thankYou:(NSString*)visitorName;

     @end


Unlike in other programming languages, We don't need to give a prefix 'override' for overridden methods in Objective-C. But the only rule is subclass method should have the same name and property list of base class method for overriding.



     
@implementation Parent

          - (void)thankYou:(NSString*)visitorName{

              NSLog(@"From Parent : Thank you %@", visitorName);
          }

     @end

     @implementation Child

          - (void)thankYou:(NSString*)visitorName{

               NSLog(@"From child : Thank you %@", visitorName);
          }

     @end


In the above example, Whenever there is a visitor, Parent class says thank you when we send a 'thankYou' message to Parent class by calling thankYou method.



     
[parentObj thankYou:@"visitor1"];  // From Parent : Thank you visitor1


In my child class, I need this thankYou method but I want a thank on behalf of my child object. So I need to go for overriding this method as I can write child own logic in the method.



     
[childObj thankYou:@"visitor1"];    // From Child : Thank you visitor1


See, Same functionality but a little customization in the subclass with the help of Method Overriding.

Let's see how can we extend the functionality. I mean I need my Base class method called also first and after that my child class logic. I don't need to replace the functionality of base class. I just need to extend the functionality.

In addition to completely replacing an existing implementation, you might want to extend a superclass's implementation. Here comes the super keyword. Within a method definition, super refers to the parent class of the current object. To call methods in the base class from child class, We can use this super keyword.

For example, I need both my parent and child should thank a visitor but should be properly conveyed.



     
@implementation Child

        - (void)thankYou:(NSString*)visitorName{

             [super thankYou: visitorName];  //calling baseclass method

             NSLog(@"From child : Thank you %@", visitorName);
         }

     @end


If a child object thanks, a visitor gets a thank you from both parent and child. Of course, child is saying on behalf of parent also here. 

Now If you call child object's thank you method,



  [childObj thankYou:@"visitor1"];       //  From Parent : Thank you visitor1

                                                         //  From Child : Thank you visitor1



Hope this post is useful. Feel free to comment in case of any queries.