📕
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
  • Relationships Between Classes
  • Inheritance
  • Syntax
  • Composition
  • Real-world example
  • Syntax
  • Favour Composition over Inheritance
  • Problems with inheritance
  • Advantages of composition
  • Summary
  1. Csharp
  2. C Sharp Intermediate

Association Between Classes

Class coupling is a measure of how interconnected classes and subsystems are.

  • Tight coupling means changing the code in class A impacts class D, which impacts class F, and so on.

  • Loose coupling means changing the code in class A doesn't require you to change anything else.

To achieve loose coupling, we need to understand

  • Encapsulation

    • No class knows the details about how any other class works

  • The relationships between classes

  • Interfaces

Relationships Between Classes

There are 2 types of relationships between classes:

  • Inheritance

  • Composition

Inheritance

Inheritance is a relationship between two classes that allows one to inherit code from another. This is known as an is-a relationship: a truck is a vehicle.

The class being inherited from is known as the parent or base or super class. The class doing the inheriting is known as the child or derived or sub class.

Benefits:

  • Code re-use

  • Polymorphic behaviour (will speak more about this in a separate section)

Syntax

public class Vehicle
{
  // Common shared code
}

public class Truck : Vehicle
{
  // Code specific to Truck
}

Pro tip: When you create any class, it automatically inherits from the Object class! That means you have access its basic methods and properties/fields.

Composition

Composition is a relationship between two classes that allows one to container another. This is known as a has-a relationship: a car has an engine.

The class placed inside the other class is known as the composite class.

Benefits:

  • Code re-use

  • Flexibility

  • Promotes loose coupling

Real-world example

Here's a real-world use case for composition. Imagine you have 2 classes: DbMigrator and Installer. These classes are responsible for specific tasks in your application.

Now imagine that both classes require logging because the business wants to track the health of its processes. We can create a Logger class for this and place an instance of it inside DbMigrator and Installer.

Syntax

In C#, there's no special syntax. You're just storing your composite class inside the main class as a private field.

public class Logger
{
  public void Log(string message)
  {
    Console.WriteLine(message);
  }
}

public class Installer
{
  private Logger _logger;

  public Installer(Logger logger)
  {
    _logger = logger;
  }

  public void Install()
  {
    _logger.log("Installing application...");
  }
}

Favour Composition over Inheritance

Problems with inheritance

The problem with inheritance is that developers can abuse it, creating large hierarchies where changing one class trickles down to all its ancestors.

For example, imagine we have an Animal class that gets inherited from a Person and Dog class. Suppose at the time of creating this relationship, we add a Walk method to the Animal class.

What happens now if we want to add a Goldfish class? Then we probably have to move the Walk method to a Mammal class, which inherits Animal. Then we make Person and Dog inherit from Mammal.

This is what tight coupling looks like.

Advantages of composition

Any inheritance relationship can be translated to composition.

Instead of thinking, "a person is an animal", you think, "a person has an animal" and a "person has a walkable".

In other words, you compose the functionality you need in a class by tying together a bunch of other classes.

TLDR: The main benefit of composition is that it's easy to add a new class tomorrow without having to go back and change everything else. If you're missing some functionality for this new class, just create another composite class to insert into your new class.

Summary

Inheritance's pros:

  • Code re-use

  • Inheritance is more intuitive, as thinking about relationships as "has-a" can be awkward

Inheritance's cons:

  • Tightly coupled

  • Easily abused to create fragile large hierarchies

Composition's pros:

  • Code re-use

  • Greater flexibility

  • Loose coupling due to lack of hierarchies

Composition's cons:

  • A little harder to understand "has-a" relationships

PreviousClassesNextInheritance

Last updated 3 years ago