RSS

Interfaces, Extensions, Abstractions, & Virtual Classes

28 Jun
Interfaces, Extensions, Abstractions, & Virtual Classes

I’m working on a project that has landed me on a foreign planet in a galaxy far far away where I need to learn about Interfaces, Extensions, Abstract, and Virtual classes. I figured that since I tend to understand something a lot more clearly when I have to write about it in a way that someone else may also understand I might as well generate a blog post!


Interfaces

thWH0B31KN

An interface is a point where two things (systems, subjects, organizations, etc.) meet and interact, like the touch pad on your microwave, the snooze button on your alarm clock, or the computer screen in your intergalactic spaceship.

In Apex a class interacts with the outside world through its methods: the methods form the class’s interface.

As it turn out, you can also define what methods must exist in the class (the class’s interface) with a separate piece of code called an Interface.

So you can think of an Interface as sort of a template for a class. You could also think of it as a Contract where the class that implements the Interface agrees to do something with each of the methods it defines (according to Wikipedia, an Interface is “an abstract type that is used to specify a behavior that classes must implement“).


Here are some points about Interfaces:

Interface

  • An Interface is like a class
    • For example, when you want to write an Interface using MavensMate you tell it that you want to write a New Apex Class
  • Interfaces do not have an access modifier (private, public, protected, or global)
    • By definition Interfaces are always global
  • Another class Implements an Interface
    • Example: public class TriggerDispatcher implements ITriggerDispatcher
    • Multiple Interfaces can be implemented by a single class
  • Methods defined in the Interface are do not have a code body in the Interface
    • Only the method signatures are present followed by a semicolon
    • Method bodies are empty so they’re simply not even written (no curly braces)
      • Example: public String createString(Integer int);   << see, no {} code body, just a semi-colon
  • The class that implements the Interface must provide bodies for each of its methods (although the bodies can be empty)
  • Classes implementing Interfaces can have additional methods from the ones defined in the Interface
  • Multiple Interfaces can be implemented by a single class
  • Many programmers name their Interface classes with an “I” at the beginning
    • Example: ITriggerHandler
  • Interfaces cannot have member variables
  • Interfaces do not have access modifiers like public, private, etc
  • When an Interface extends another interface, the parent interface and methods do not need to be defined as virtual (read on for more on Extending and Virtual)

What are Interfaces Good For?

Interfaces separate the declaration of methods from the implementation of them. This is known as a “level of abstraction” and allows you to have different actions that can occur for the same method.

Here’s an example from the project that is making me learn this stuff: setting up a Trigger Framework.

framework

No matter what object has initiated the trigger, or what type of action initiated the trigger (insert, update, delete, undelete), there will always be a method that each trigger handler will use to initiate its actions. Since it is expected that there will be multiple trigger handlers needed, having them implement an Interface ensures that each will have the same method(s).  In this example the methods of the interface are named “mainEntry,” “inProgressEntry,” and “updateObjects:”

ITriggerHandler

Even though each class that implements the Interface will have a mainEntry method, that method for classes that handle the Account object will have different actions than the one for classes that handle the Asset object. And isn’t it nice when they all have the same method signature? It’s so neat and tidy and makes for such nice, consistent code. 😛

Now classes that implement this Interface must provide bodies for all methods in it. Here is an example where they all have exceptionally skinny bodies:

implementation

skeleton


Interface Data Types

When you define an Interface you are also defining a data type. This means that you can use the Interface name anywhere you would use a data type, like when declaring a variable:

DataType

When you do this you must be sure that any object that you assign to that variable is an instance of a class that has implemented the Interface. In other words, your variable is an Interface type, and all classes that implement the Interface are also Interface types.


Extensions

extensions

An Extension is when one class Extends another class, adding additional or different functionality from what existed in the first class. The extending class inherits all the methods and properties of the first class and then has the ability to add more stuff, too. It’s just like a hair extension which adds to the hair on your head!

The actual terminology is “parent class” for the original class, and “subclass” for the class that extends the parent. Sort of boring. I like “super class” for the new-and-improved version… and maybe “underdog class” for the original. 😀

Classes that extend other classes may also inherit another power: the ability to override methods from the original class. What this means is that the super class may not have to put up with the functionality that came with the methods it inherited, and, instead, can have it’s very own unique functionality for them.

There is a term for this–Polymorphism–which means that classes that extend other classes (subclasses) can have their own unique behaviors yet share some of the same behaviors as the class they extended (the parent class).

In order for this to happen the parent class must be a Virtual class and the methods that can be overridden must be Virtual methods or the parent class must be an Abstract class and the methods that can be overridden must be Virtual methods or Abstract methods. More on this below.


Some Key Points About Extensions

  • A class can extend only one other class
    • (As opposed to Interfaces where a class can implement several Interfaces)
  • The syntax looks like this:
    • Parent Class Definition: public class ParentClass {}
    • Subclass Definition: public class SubClass extends ParentClass {}
  • Interfaces can extend other interfaces
  • In order for a parent class to be extended it must be declared as Virtual or Abstract (more on this below)
  • Subclasses can override virtual methods within virtual classes (polymorphism)
  • Subclasses must override abstract methods within abstract classes if they are going to use them
    • Subclasses can override virtual methods within abstract classes if they want to, but they don’t have to

Virtual Keyword for Classes and Methods

thXFALVMWZ

Virtual is a keyword that is used to modify the definition of a class or method (the technical term is “definition modifier”).

What it means when it’s used in a class definition is that the class can be extended and any virtual methods within the class can be overridden. (Overridden means that you have written your own code that replaces the code in the original method.)

What it means when it’s used in a method signature is that the method can be overridden (as long as that method resides in a class that can be extended).

To override a virtual method all you need to do is re-write the signature of the method and include the keyword “override” right after the access modifier like this:

public override void methodName() {}

holodeck

Some Key Points on the Virtual Definition Modifier:

  • Classes declared to be Virtual can be extended and will allow overrides of their methods that can be overridden
  • Methods within a Virtual class that also have the Virtual definition modifier may be overridden
    • Methods not marked Virtual cannot be overridden
  • Virtual methods must have a code body, but the code body can be empty
    • (As opposed to Interface and Abstract methods which cannot have a code body in the Interface of class where they’re originally defined)
    • Example: public virtual void methodName() {}  << see, a {} code body
  • Interfaces are, be definition, already considered to be virtual so including that keyword in the Interface declaration is redundant (and, in fact, the Developer Console will not allow you to include it)

 Abstract Keyword for Classes and Methods

abstract

Abstract is a keyword that is also used to modify the definition of a class or method.

When used in a class definition what it means is that the class is sort of just floating around in space and cannot be used as-is. It’s “abstract” as in “not concrete.” Since it cannot be used on its own it cannot be instantiated (it isn’t concrete so it can’t really exist).

concrete

It also means that the class may contain Abstract methods.

An abstract method looks almost exactly like a method in a Interface in that it has its signature but no body. The only difference is the signature will also have the “abstract” definition modifier:

  • Abstract method signature: abstract void mainEntry();
    • (Abstract method signatures may also have access modifiers like “private” or “public”)
  • Interface method signature: void mainEntry();

There is a key difference between an Abstract class method and an Interface method, however, and it is that classes extending an abstract class have the option to provide bodies for abstract methods from the parent class, whereas classes implementing an Interface must provide a body for every method in the parent Interface.

Some Key Points on the Abstract Definition Modifier:

  • Abstract classes must be extended in order to use them, they cannot stand on their own (be instantiated)
  • Abstract classes can have methods which are Abstract, Virtual, or just regular ol’ methods that contains code
    • As opposed to Virtual classes that can have Virtual or regular ol’ methods, but cannot have Abstract methods
  • Abstract classes can have member variables
    • Interfaces cannot
  • Abstract methods cannot have a code body in the class where they are originally defined
    • (As opposed to virtual methods that must have a code body)
    • Instead the signature is terminated with a semicolon like a regular line of code
    • Example: public abstract void methodName();  << see, no {} code body, just a semi-colon
  • Abstract methods cannot be static

So How Do Interfaces, Abstract Classes, and Virtual Classes Compare?

Generally you’ll see comparisons between Interfaces and Abstract Classes because both must be put into play by another class in order to be used, whereas Virtual Classes are more like just regular ol’ classes that can be instantiated and used as-is. In order to get them straightened out in my mind, however, I’ve included Virtual Classes along with the other two so I can more readily see their similarities and differences.

  • Instantiation:
    • Neither Interfaces or Abstract Classes can stand on their own
      • Interfaces must be implemented
      • Abstract classes must be extended
    • Virtual classes can stand on their own (be instantiated)
      • They can also be extended if the need arises
  • Methods:
    • All methods in an Interface are methods without bodies (just the method signature) and their body must be defined in the class that implements the Interface
    • All methods in Virtual classes will have bodies which can be well-defined or empty
      • Virtual within a Virtual class can be overridden
      • Regular ol’ methods within a Virtual class cannot be overridden (they’re just inherited by the subclass)
      • Virtual classes cannot have Abstract methods
    • Abstract classes can have Abstract, Virtual, or just regular ol’ methods
      • Abstract methods do not have a body
      • Abstract methods must be overridden if they are going to be used
        • If you’re not going to use an abstract method you do not need to create a body for that method in the subclass
      • Virtual methods can be overridden if you want to do so
      • Regular ol’ methods within an abstract class cannot be overridden (they’re just inherited by the subclass)
  • Member Variables:
    • Interfaces cannot have member variables (they have only methods)
    • Abstract and Virtual classes can have member variables
  • Extending and Implementing:
    • Interfaces can extend other Interfaces
      • Interfaces cannot implement Interfaces
      • Interfaces cannot extend Abstract or Virtual classes
    • Abstract and Virtual classes can implement Interfaces
    • Virtual classes can extend Abstract classes and other Virtual classes
    • Abstract classes can extend other Abstract classes
      • Abstract classes cannot extend Virtual classes

How To Know Which To Use

confused2

Here’s where some experience with Apex or Java coding most surely helps a ton. Fortunately I found a couple explanations, which I’ll paraphrase here, that really helped me understand how I might choose between an Abstract class and an Interface.

When thinking about the possible super classes that you may spin off of your underdog class, would you group those classes together based on a “thing” (a noun) or an “action” (a verb)?

For example, if your super classes were types of star ships (Enterprise, Gryphon, Drake, Apollo), then they would be “things.” If they will have similar actions (warp speed, cloaking, disk separation), then they would be “actions.”

  • For classes that are more “things,” use an Abstract class as the parent class
  • For classes that are more like “actions,” use an Interface

Another way to look at which to use is by where you want your implementation.

  • With an Interface you can share your methods with any class that implements your Interface
  • With an Abstract Class your methods are stored in one central place where all subclasses can access them, which avoids code duplication

Yet another way to compare the two:

  • When you can fully describe the class in terms of “what it does” without needing to specify any of “how it does it,” then you should use an Interface
  • If you need to include some implementation details, then you will need to represent your concept in an Abstract Class

And here’s a caveat:

  • If you add a new method to an Interface then you mush track down all the implementations of the interface and include the new method
  • If you add a new Abstract or Virtual method to an Abstract Class you can provide a default code body and then only classes that need to override the default actions need to be updated

    Features                                      Interfaces                                Abstract Class

    Multiple inheritance A class may implement several interfaces A class may extend only one abstract class
    Default implementation An interface cannot provide any code, just the method signatures. An abstract class can provide complete, default code and/or just the details that have to be overridden.
    Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
    Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface An abstract class defines the core identity of a class and there it is used for objects of the same type
    Homogeneity If various classes only share method signatures then it is better to use Interfaces If various classes are of the same kind and use common behavior or status then it is better to use an abstract class
    Speed Interfaces require more time to find the actual method in the corresponding classes Fast

     


Chaining It All Together

So now that I’ve figured out a thing or two while researching this blog I feel a whole lot more comfortable reading the Trigger Framework code I’m trying to understand. It’s a nice piece of work by Hari Krishnan (you can find it here) and is the framework that I’ve decided to use to build out the triggers needed in an org I’m working/learning in.

In Mr. Krishnan’s framework he has identified a couple Interfaces that define the methods that need to be present in the trigger code. While I found this concept fairly straightforward, what had me thrown was that he also uses virtual and abstract classes to implement those Interfaces.

But there is a wonderful reasoning for this: by implementing the Interfaces with abstract and virtual methods they become optional for the end classes (the classes that extend the abstract and virtual classes) where the actual grunt-work code resides.

For instance, he has defined several methods in his Interface ITriggerDispatcher. He then implements that Interface with a virtual class, and in that class he added a new, fully defined method. Finally the object-specific end classes extend the virtual class. In this end class only the methods from the virtual class that are needed are overridden. The other methods are ready to be used if the time arises that they are needed, but until such time they do not need to reside in the final class. Furthermore, when new functionality is needed, only the end classes need to be created or updated without having to change anything within the framework.

Pretty cool.

thSMHS9V79

Advertisements
 
Leave a comment

Posted by on June 28, 2017 in Apex

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: