📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • What is An Interface?
  • Value of interfaces
  • Testability
  • Extensibility
  • Interfaces and Inheritance
  • Interfaces and Polymorphism
  1. Csharp
  2. C Sharp Intermediate

Interfaces

What is An Interface?

An interface is a language construct similar in syntax to a class but is more like a contract or blueprint for a class. As a real-world example, think of an interface as a job description for an open position: it describes what's required for the role, but anyone who meets the criteria can fill it.

public interface ITaxCalculator
{
  int Calculate();
}

public class MyTaxCalculator : ITaxCalculator
{
  public int Calculate()
  {
    // Implementing the blueprint required by `ITaxCalculator`
  }
}

Things to note:

  • By convention, all interface names start with I.

  • Interfaces do not have any implementation. (The Calculate method has no curly braces!)

  • Interface members do not have access modifiers like public or private.

  • All classes that implement interface members must be public.

Value of interfaces

When a class uses another class, this can create a tight coupling.

public class OrderProcessor
{
  private readonly TaxCalculator _taxCalculator;

  public OrderProcessor()
  {
    _taxCalculator = new TaxCalculator();
  }

  public int CalculateTax()
  {
    // Do something with TaxCalculator
  }
}

For example, because OrderProcessor is using TaxCalculator, changing TaxCalculator could impact OrderProcessor (and any other classes using OrderProcessor).

Interfaces solve this problem: instead of using the TaxCalculator class, you use the ITaxCalculator interface.

// This class is based on an interface
// NOTE: The syntax looks similar to class inheritance, but it's NOT the same thing
public class TaxCalculator : ITaxCalculator
{
}

public class OrderProcessor
{
  private readonly ITaxCalculator _taxCalculator;

  public OrderProcessor(ITaxCalculator taxCalculator)
  {
    _taxCalculator = taxCalculator;
  }

  public int CalculateTax()
  {
    // Do something with TaxCalculator
  }
}

Now OrderProcessor doesn't know about TaxCalculator. Instead, it accepts any class based on the ITaxCalculator interface. If you one day want to change the dependent class, you can with little to no impact to OrderProcessor.

Note: Dependency injection helps here (where TaxCalculator gets injected as a field for OrderProcessor).

Testability

Essentially, interfaces help with testability because when performing unit testing on OrderProcessor, you don't have to think about TaxCalculator, making your tests isolated to units.

See Udemy video for more details.

Extensibility

Extensibility is the idea that your code is written in such a way that it's easy to extend its capabilities as your needs change without changing the rest of your application.

In the example above, maybe we come up with a better way to calculate tax. So, we can create a new BetterTaxCalculator class that is based on the same ITaxCalculator interface.

And as long as we adhere to the interface's structure, we are able to improve OrderProcessor without touching it.

This is known as the open-closed principle or OCP: OrderProcessor is open for extension but closed for modification.

Other examples:

  • IRouteCalculator allows us to improve our routing algorithm for our GPS app

  • ILogger allows us to move from logging in the console to logging in a file to logging in a service at a moment's notice

  • IEncryptor allows us to update our encryption algorithm that we use when storing sensitive data

Interfaces and Inheritance

In C#, you have the ability to provide multiple interfaces to a class:

public class InheritedClass : BaseClass, IInterface, IAnotherInterface
{
  // `InheritedClass` now inherits properties and methods from `BaseClass`

  // But it must now implement the methods in `IInterface` and `IAnotherInterface`
  public void InterfaceMethod() {}
  public void AnotherInterfaceMethod() {}
}

In contrast, in languages like C++, you can use multiple inheritances, and it looks exactly like the code above.

It's a common misconception that C# supports multiple inheritance too because of the syntactical similarity.

However, it's not multiple inheritance because we have to explicitly implement InterfaceMethod and AnotherInterfaceMethod. Those methods aren't inherited.

Classes do not inherit from an interface. Classes implement an interface.

Interfaces and Polymorphism

Interfaces do however support polymorphism: the idea that some name can take on many forms.

For example, suppose in my OrderProcessor class I have a Notify method where I want to send messages to multiple channels at once.

I can store each notification channel in OrderProcessor and use a polymorphic method like Send that every notification channel shares.

public class OrderProcessor
{
  private readonly IList<INotificationChannel> _notificationChannels;

  public void Notify(string message)
  {
    foreach (var channel in _notificationChannels)
      channel.Send(message);
  }

  public void RegisterNotificationChannel(INotificationChannel channel)
  {
    _notificationChannels.Add(channel);
  }
}

The important point is that the INotificationChannel enforces the Send method as a requirement for all our notification channels, allowing us to benefit from polymorphism.

PreviousPolymorphismNextJava

Last updated 3 years ago