🚀 Introduction to Functional Programming (Part:1) Functional Programming is a programming style where we build applications using functions by avoiding changing data and state. Key Ideas of Functional Programming: ✔ Pure Functions: Functions that always return the same output for the same input ✔ Immutability: Do not change existing data, create new data instead ✔ First-Class Functions: Functions can be treated like variables ✔ Higher-Order Functions: Functions that take other functions as arguments What are Pure Functions? A pure function is a function that: 1. Always returns the same output for the same input 2. Has no side effects (does not change anything outside the function) Example:(Pure Function) const add = (a, b) => { return a + b; }; >> add(2, 3) will always return 5 >> It doesn’t modify any external data Example:1 (Not a Pure Function) let total = 0; const addToTotal = (num) => { total += num; }; >> Output depends on previous value of total >> It modifies external state Example:2 (Not Pure Function) const getRandom = () => { return Math.random(); }; >> Same input → different output >> getRandom() = Unpredictable Real-World Example 1: E-commerce Cart Total ❌ Not Pure (bad approach) let total = 0; const addToCart = (price) => { total += price;}; ✅ Pure Function (good approach) const calculateTotal = (prices) => { return prices.reduce((sum, price) => sum + price, 0);}; calculateTotal([100, 200, 300]); // 600 >> Same input → same output >> No external changes >> Easy to test Real-World Example 2: Updating User Data (React Style) ❌ Not Pure const user = { name: "Kavi", age: 21 }; const updateAge = () => { user.age = 22; }; >> Problem: Directly mutating data (can cause UI bugs in React) ✅ Pure Function const updateAge = (user) => { return { ...user, age: 22 }; }; const updatedUser = updateAge(user); >> Original object not changed >> Safe for React state updates Real-World Example 3: Filtering Products ✅ Pure Function const filterExpensiveProducts = (products) => { return products.filter(p => p.price > 1000); } filterExpensiveProducts([ { name: "Phone", price: 500 }, { name: "Laptop", price: 50000 } ]); >> No mutation >> Just transforms input → output 🔥 Where You’ll Use This >> React state updates >> API data transformation >> Redux / state management >> Data filtering & calculations #JavaScript #FunctionalProgramming #WebDevelopment #CleanCode #FrontendDevelopment #Coding #100DaysOfCode #DeveloperLife
Introduction to Functional Programming: Pure Functions and Immutability
More Relevant Posts
-
[𝗢𝗢𝗣 𝗣𝗼𝘀𝘁 #1] 𝗪𝗵𝘆 𝗱𝗼 𝘄𝗲 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝘂𝘀𝗲 𝗢𝗯𝗷𝗲𝗰𝘁-𝗢𝗿𝗶𝗲𝗻𝘁𝗲𝗱 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 (𝗢𝗢𝗣)? Early programming was entirely imperative: you wrote a list of instructions, the computer executed them in order. As programs grew, programmers invented subroutines (functions), global variables, and modules. This worked fine for small programs. The problem emerged when programs grew to tens of thousands of lines. Global state became unmanageable. Functions reached across the entire codebase to modify data. A change in one place broke something in an unrelated place. Programs became brittle, hard to understand, and nearly impossible to maintain. This was called the 𝘀𝗼𝗳𝘁𝘄𝗮𝗿𝗲 𝗰𝗿𝗶𝘀𝗶𝘀, a real phenomenon identified in the late 1960s where software projects routinely ran over budget, over time, and failed. Object-Oriented Programming is a programming paradigm that organizes software around 𝗼𝗯𝗷𝗲𝗰𝘁𝘀 - bundles of state (data) and behavior (functions), rather than around procedures and logic alone. Here are the 4 major problems OOP solves to keep your projects from collapsing under their own weight: 1. 𝗧𝗵𝗲 "𝗪𝗵𝗼𝗱𝘂𝗻𝗻𝗶𝘁" 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 (𝗨𝗻𝗰𝗼𝗻𝘁𝗿𝗼𝗹𝗹𝗲𝗱 𝗦𝘁𝗮𝘁𝗲) In procedural code, global data is a free-for-all. Any function can change any variable. When a bug corrupts your data, you have to hunt through every line of code to find the culprit. • 𝗢𝗢𝗣 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗘𝗻𝗰𝗮𝗽𝘀𝘂𝗹𝗮𝘁𝗶𝗼𝗻. Objects own their data. If you want to change a value, you go through a specific method. This contains the "blast radius" of bugs. 2. 𝗧𝗵𝗲 "𝗛𝗼𝘂𝘀𝗲 𝗼𝗳 𝗖𝗮𝗿𝗱𝘀" 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 (𝗖𝗼𝘂𝗽𝗹𝗶𝗻𝗴 & 𝗥𝗶𝗴𝗶𝗱𝗶𝘁𝘆) Ever changed one small function and watched ten unrelated parts of the app break? That’s tight coupling. • 𝗢𝗢𝗣 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗔𝗯𝘀𝘁𝗿𝗮𝗰𝘁𝗶𝗼𝗻 & 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀. Objects hide 𝘩𝘰𝘸 they work and only show 𝘸𝘩𝘢𝘵 they can do. You can swap out the "engine" without changing the "dashboard." 3. 𝗧𝗵𝗲 "𝗖𝗼𝗽𝘆-𝗣𝗮𝘀𝘁𝗲" 𝗧𝗿𝗮𝗽 (𝗖𝗼𝗱𝗲 𝗗𝘂𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻) If you have a Circle and a Rectangle, you shouldn’t have to rewrite the draw() logic from scratch for both. • 𝗢𝗢𝗣 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲 & 𝗣𝗼𝗹𝘆𝗺𝗼𝗿𝗽𝗵𝗶𝘀𝗺. You define common behavior in a base "Shape" class. Your code treats everything as a Shape, and the objects handle the specific details themselves. 4. 𝗧𝗵𝗲 "𝗠𝗲𝗻𝘁𝗮𝗹 𝗚𝘆𝗺𝗻𝗮𝘀𝘁𝗶𝗰𝘀" 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 (𝗖𝗼𝗴𝗻𝗶𝘁𝗶𝘃𝗲 𝗟𝗼𝗮𝗱) A 2,000-line file of raw procedures is impossible to hold in your head. It doesn't look like the real world. • 𝗢𝗢𝗣 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗗𝗼𝗺𝗮𝗶𝗻 𝗠𝗼𝗱𝗲𝗹𝗶𝗻𝗴. By creating objects like User, Order, or PaymentProcessor, the code mirrors how we naturally think. It turns abstract logic into a relatable story. Feel free to add more in the comments! 👇
To view or add a comment, sign in
-
#6 Object-Oriented Programming Object-Oriented Programming is a way of building software around objects real-world things that bundle data and behavior together. Instead of writing a flat list of functions, you model the problem the way you think about it. Class vs Object A class is the blueprint. An object is the actual thing you create from that blueprint. Think cookie cutter (class) → cookies (objects). The 3 pillars of Object-Oriented Programming 1. Encapsulation This enablee the ability to hide an object’s internal data and expose only what’s needed. It protects your data from being changed accidentally and keeps the interface clean. Real-world feel:You use a car’s steering wheel and pedals; you don’t fiddle with the engine wires. 2. Inheritance A child class inherits attributes and behavior from a parent class. It’s the “is-a” relationship that saves you from repeating yourself. Real-world feel: A SportsCar is a Car— it gets all the car basics and adds its own extras. 3. Polymorphism Same method name, different behavior depending on the object. It lets you write code that works on a parent type while the child’s version runs. Real-world feel: car.start(); does something different for an electric car vs a petrol car. Abstraction It’s a form of encapsulation that hides complexity. You expose only the essential features and hide how they work. Real-world feel:You press start() you don’t need to know the ignition sequence. Overriding When a child class provides its own implementation of a method that already exists in the parent. That’s what makes polymorphism work. What does Object Oriented Programming actually build? Large, maintainable systems (banking apps, e-commerce platforms, games) Reusable components you can extend across a project Modular software where each object handles its own data and behavior Languages that use Object Oriented- Programming Java, C#, C++, Python, JavaScript, PHP, Ruby, Kotlin, Swift — basically every mainstream language for building real applications. Object Orieanted Programming is less about syntax and more about thinking in objects. That shift is what makes big projects manageable. Object Orieanted Programming - Flow Chart [Start] ↓ Define a CLASS (blueprint) ↓ Create an OBJECT (instance of the class) ↓ Use ENCAPSULATION ↓ ← private attributes + public methods Use ABSTRACTION ↓ ← expose only what’s needed (e.g., car.drive()) Use INHERITANCE ↓ ← ChildClass inherits from ParentClass Use POLYMORPHISM ↓ ← Same method name, different behavior ↓ [End] #OOP #SoftwareEngineering #Programming #CareerGrowth #Agit2026 #buildinginpublic #WomaninTechnology
To view or add a comment, sign in
-
-
An Interesting Example Explaining Program - Process - Thread - Task 1. Program Definition: A program is a set of instructions written in a specific programming language that the computer can execute. It is essentially a blueprint, and it does not perform any action until it is run. Analogy: Think of a program as a recipe for cooking. The recipe outlines all the steps and ingredients needed to make a dish, but until you start cooking, the recipe is just an inactive set of instructions. 2. Process Definition: A process is an instance of a program in execution. When you run a program, it becomes a process. A process has its own memory space, system resources, and an operating system environment. Analogy: Continuing with the recipe analogy, a process is like someone actually cooking according to the recipe. Each person (process) has their own kitchen space (memory) and resources, like ingredients and utensils, which they use while cooking. Example: When you open a web browser (like Chrome or Firefox), a process is created for it. Each tab within the browser might even have its own process, depending on the browser design. 3. Thread Definition: A thread is the smallest unit of execution within a process. A process can have multiple threads, all sharing the same memory but running independently. Threads within a process can perform different tasks simultaneously, improving efficiency. Analogy: In the cooking example, if multiple people are working together on the same dish, each person could be considered a thread. They share the same kitchen (memory) and ingredients (resources) but may be responsible for different parts of the task, like chopping vegetables or stirring the pot. Example: In your web browser, multiple threads might handle different tasks: one for rendering the page, another for handling user input, and yet another for network requests. These threads all work within the same browser process. 4. Task Definition: In many modern programming frameworks (like .NET), a task is an abstraction that represents an asynchronous operation, which can run on a thread. Tasks are typically used for parallelism and concurrency, making it easier to manage multiple operations without blocking the main thread. Analogy: If cooking is the process and each cook is a thread, then a task might represent specific cooking jobs, like “boil water” or “slice onions.” These tasks can be assigned to cooks (threads) as they become available, optimizing workflow without everyone waiting for one task to complete before starting another. Example: In a web application, if you request data from a database, this request can be handled as a task. The application doesn't have to wait for the database to respond (which can be slow); instead, it can continue other work until the data is ready.
To view or add a comment, sign in
-
Pure Functional Programming & why it matters Pure functional programming uses pure functions, immutable data structures, referential transparency and higher-order functions. Read more: https://lnkd.in/dXkBtQnY Or listen to Christoffer Ekeroth: https://lnkd.in/dEZa8fGf #functionalprogramming
To view or add a comment, sign in
-
Pure functions make programs more predictable and easier to reason about since there are no hidden dependencies or side effects to consider. Which also makes it easier to test and let AI generate the code for you.
Pure Functional Programming & why it matters Pure functional programming uses pure functions, immutable data structures, referential transparency and higher-order functions. Read more: https://lnkd.in/dXkBtQnY Or listen to Christoffer Ekeroth: https://lnkd.in/dEZa8fGf #functionalprogramming
To view or add a comment, sign in
-
The article/post I’m happily reposting gives examples from Elm and Haskell, where purity is strictly enforced by the compiler. From my experience, deliberately separating pure and impure code is still very much worth the effort even in functional-first languages that don’t enforce it. It requires some voluntary discipline (it’s not as easy as in Haskell or Elm), but you’ll be grateful for it during maintenance or major refactoring.
Pure Functional Programming & why it matters Pure functional programming uses pure functions, immutable data structures, referential transparency and higher-order functions. Read more: https://lnkd.in/dXkBtQnY Or listen to Christoffer Ekeroth: https://lnkd.in/dEZa8fGf #functionalprogramming
To view or add a comment, sign in
-
🚀 Reflection in C#: The Code's Self-Awareness Superpower Ever wondered how an application knows its own version number or finds a specific method without you hard-coding it? The secret is Reflection. In .NET, Reflection allows your code to look in a mirror and inspect its own structure while it’s running. 🔍 What exactly is Reflection? In simple terms, Reflection is the ability of code to access the metadata of an assembly during runtime. Think of it as "dynamic inspection." Instead of the program just following a pre-set script, it can stop and ask, "Wait, what methods do I have? What version am I? What classes are inside this DLL?" 📚 First, Understand Metadata Reflection works because of something called Metadata. Metadata simply means: Information about your code. Imagine a Book 📖 Data • Chapters • Paragraphs • Story content Metadata • Title • Author • ISBN The metadata isn't the story itself, but it describes the story. In C#, metadata describes: • Classes • Methods • Properties • Assemblies Reflection lets us read this metadata during runtime. 🛠️ Practical Example #1 — Getting Application Version Instead of manually updating your version everywhere, you can retrieve it dynamically. using System.Reflection; // Get the executing assembly Assembly assembly = Assembly.GetExecutingAssembly(); // Get version metadata AssemblyName assemblyName = assembly.GetName(); Version version = assemblyName.Version; Console.WriteLine("Current Version: " + version); This is commonly used in: ✔ About pages ✔ Logging ✔ Diagnostics 🛠️ Practical Example #2 — Discovering Methods Dynamically Reflection can also inspect objects and find methods at runtime. Type t = obj.GetType(); // Find method by name MethodInfo method = t.GetMethod("MySecretMethod"); This capability is heavily used by frameworks like: • ASP.NET Core • Entity Framework • Dependency Injection Containers • Testing frameworks ⚡ Why Reflection is Powerful Reflection allows your application to become dynamic and adaptive. 💡 Key Takeaways 🔹 Assembly Class → Get application-level metadata (version, name, etc.) 🔹 Type Class → Inspect object structure (methods, properties, fields) 🔹 Runtime Power → Your code can adapt while the program is running Summary: Reflection turns your code into a detective, allowing it to explore its own metadata to solve complex, dynamic programming problems! 🕵️♂️💻 #CSharp #DotNet #Programming #CodingTips #SoftwareDevelopment #TechSimplified #DotNet #DotNetCore #Programming #Coding #OOP (Object-Oriented Programming) #SystemReflection #Metaprogramming #Metadata #LateBinding #DependencyInjection #SoftwareArchitecture #CleanCode #Middleware #DevCommunity #SoftwareEngineering #CodeNewbie (if explaining the basics) #100DaysOfCode #TechTips #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝗖𝗼𝗻𝘁𝗲𝘅𝘁 𝗶𝗻 𝗦𝗽𝗿𝗶𝗻𝗴 — 𝗧𝗵𝗲 𝗕𝗿𝗮𝗶𝗻 𝗬𝗼𝘂’𝗿𝗲 𝗜𝗴𝗻𝗼𝗿𝗶𝗻𝗴 (𝗨𝗻𝘁𝗶𝗹 𝗜𝘁 𝗕𝗿𝗲𝗮𝗸𝘀) Most developers say: 👉 “ApplicationContext is just a container for beans.” That’s incomplete — and honestly, a weak understanding. If you don’t truly get ApplicationContext, you won’t be able to debug half your Spring Boot issues. Let’s break it down properly 👇 🧠 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝗖𝗼𝗻𝘁𝗲𝘅𝘁? 👉 ApplicationContext = Advanced IoC Container in Spring It doesn’t just “store objects.” It: - Creates beans - Manages their lifecycle - Injects dependencies - Handles events - Supports AOP, i18n, and more 🔥 𝗖𝗼𝗿𝗲 𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝗯𝗶𝗹𝗶𝘁𝗶𝗲𝘀 : 1️⃣ 𝗕𝗲𝗮𝗻 𝗖𝗿𝗲𝗮𝘁𝗶𝗼𝗻 & 𝗠𝗮𝗻𝗮𝗴𝗲𝗺𝗲𝗻𝘁: Spring creates and manages objects (beans) instead of you. 🔹 Example 1: @Service class UserService {} 👉 Automatically created and managed by ApplicationContext 🔹 Example 2: @Bean public RestTemplate restTemplate() { return new RestTemplate(); } 👉 Manually defined bean, still managed by context 2️⃣𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗜𝗻𝗷𝗲𝗰𝘁𝗶𝗼𝗻 (𝗗𝗜) ApplicationContext wires objects together. 🔹 Example 1: @Autowired private UserService userService; 👉 You don’t create dependencies — Spring injects them 3️⃣ 𝗕𝗲𝗮𝗻 𝗟𝗶𝗳𝗲𝗰𝘆𝗰𝗹𝗲 𝗠𝗮𝗻𝗮𝗴𝗲𝗺𝗲𝗻𝘁 It controls how and when beans are created and destroyed 𝗙𝗹𝗼𝘄: Instantiate → Inject Dependencies → Initialize → Ready → Destroy 🔹 Example 1: @PostConstruct public void init() {} 🔹 Example 2: @PreDestroy public void cleanup() {} 4️⃣ 𝗖𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 It loads and manages application configuration. 🔹 Example: @Value("${server.port}") private int port; 5️⃣ 𝗘𝘃𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗦𝘆𝘀𝘁𝗲𝗺 ApplicationContext allows communication via events. 🔹 Example: @EventListener(ApplicationReadyEvent.class) public void onStart() {} 6️⃣ 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀: AOP (Aspect-Oriented Programming) Internationalization (i18n) Resource loading 🔹 Example 1: Logging using AOP 🔹 Example 2: Different language messages using message sources 🧩 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝗖𝗼𝗻𝘁𝗲𝘅𝘁 1. 𝘼𝙣𝙣𝙤𝙩𝙖𝙩𝙞𝙤𝙣𝘾𝙤𝙣𝙛𝙞𝙜𝘼𝙥𝙥𝙡𝙞𝙘𝙖𝙩𝙞𝙤𝙣𝘾𝙤𝙣𝙩𝙚𝙭𝙩 👉 Used in standalone apps 2. 𝘾𝙡𝙖𝙨𝙨𝙋𝙖𝙩𝙝𝙓𝙢𝙡𝘼𝙥𝙥𝙡𝙞𝙘𝙖𝙩𝙞𝙤𝙣𝘾𝙤𝙣𝙩𝙚𝙭𝙩 👉 Old XML-based configuration 3. 𝙒𝙚𝙗𝘼𝙥𝙥𝙡𝙞𝙘𝙖𝙩𝙞𝙤𝙣𝘾𝙤𝙣𝙩𝙚𝙭𝙩 👉 Used in web apps (Spring Boot uses this internally) ⚠️ Most devs fail here: ❌ They don’t know when beans are created ❌ They don’t understand scope (singleton, prototype) ❌ They panic when bean injection fails Think of ApplicationContext as: 👉 “Factory + Container + Brain + Manager of your entire application” 🎯 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 If you understand ApplicationContext: - Debugging becomes easy - Dependency issues become obvious - You stop guessing and start reasoning ♻️ Repost if this gave you clarity #Java #ImmediateJoiner #Spring #OpenToWork
To view or add a comment, sign in
-
-
*✅ Programming Important Terms You Should Know* 💻🚀 Programming is the backbone of tech, and knowing the right terms can boost your learning and career. *🧠 Core Programming Concepts* - *Programming*: Writing instructions for a computer to perform tasks. - *Algorithm*: Step-by-step procedure to solve a problem. - *Flowchart*: Visual representation of a program’s logic. - *Syntax*: Rules that define how code must be written. - *Compilation*: Converting source code into machine code. - *Interpretation*: Executing code line-by-line without compiling first. *⚙️ Basic Programming Elements* - *Variable*: Storage location for data. - *Constant*: Fixed value that cannot change. - *Data Type*: Type of data (int, float, string, boolean). - *Operator*: Symbol performing operations (+, -, *, /, ==). - *Expression*: Combination of variables, operators, and values. - *Statement*: A single line of instruction in a program. *🔄 Control Flow Concepts* - *Conditional Statements*: Execute code based on conditions (if, else). - *Loops*: Repeat a block of code (for, while). - *Break Statement*: Exit a loop early. - *Continue Statement*: Skip the current loop iteration. - *Switch Case*: Multi-condition decision structure. *📦 Functions & Modular Programming* - *Function*: Reusable block of code performing a task. - *Parameter*: Input passed to a function. - *Return Value*: Output returned by a function. - *Module*: File containing reusable functions or classes. - *Library*: Collection of pre-written code. *🧩 Object-Oriented Programming (OOP)* - *Class*: Blueprint for creating objects. - *Object*: Instance of a class. - *Encapsulation*: Bundling data and methods together. - *Inheritance*: One class acquiring properties of another. - *Polymorphism*: Same function behaving differently in different contexts. - *Abstraction*: Hiding complex implementation details. *📊 Data Structures* - *Array*: Collection of elements stored sequentially. - *List*: Ordered collection that can change size. - *Stack*: Last In First Out (LIFO) structure. - *Queue*: First In First Out (FIFO) structure. - *Hash Table / Dictionary*: Key-value data storage. - *Tree*: Hierarchical data structure. - *Graph*: Network of connected nodes. *⚡ Advanced Programming Concepts* - *Recursion*: Function calling itself. - *Concurrency*: Multiple tasks running simultaneously. - *Multithreading*: Multiple threads within a program. - *Memory Management*: Allocation and deallocation of memory. - *Garbage Collection*: Automatic memory cleanup. - *Exception Handling*: Handling runtime errors using try, catch, except. *🌐 Software Development Concepts* - *Framework*: Pre-built structure for building applications. - *API*: Interface allowing different software to communicate. - *Version Control*: Tracking code changes using tools like Git.
To view or add a comment, sign in
-
Why did C++ invent the class keyword when struct already existed? C-style programming (using struct), data and the functions that use that data are separated. In the C-style approach, there is no formal "link" in the code between the Date data and the functions. The functions are just floating around globally. You have to manually pass a pointer (struct Date*) to every single function to tell it which date to work on. C++ introduced the class (and upgraded struct) to allow Encapsulation. This means "binding" the data and the functions together into a single unit. struct members are public by default, while class members are private by default. Imagine you have three different Date structs in your program: birthDate, startDate, and endDate. You also have a function called print_date(). It has no idea which date you want to print unless you explicitly hand it a pointer to one. You have a struct Date (the data: day, month, year). In the C-style approach, there is no formal "link" in the code between the Date data and the functions. The functions are just floating around globally. You have to manually pass a pointer (struct Date*) to every single function to tell it which date to work on. Encapsulation (The C++ Solution) C++ introduced the class (and upgraded struct) to allow Encapsulation. This means "binding" the data and the functions together into a single unit. Instead of passing a pointer manually every time, the function becomes a Member Function of the class. struct, there was "NO SYNTACTIC WAY to DEPICT RELATIONSHIP". In other words, the code didn't look like the functions belonged to the data. Because the function is separate, every time you want to do anything with a date, you have to write code like this: // You have to pass the address (&) of the data manually print_date(&birthDate); set_month(&startDate, 5); is_leap_year(&endDate); When you move a function inside, C++ automatically handles that pointer for you. It creates a hidden pointer called this. It is the bridge that allows a single piece of function code to work for thousands of different objects. When you write a member function in a class, the compiler secretly rewrites it. What you write: void Date::setMonth(int m) { month = m; } What the Compiler actually sees: void Date::setMonth(Date* const this, int m) { this->month = m; } #include <stdio.h> struct Date { int day; }; // In C++, the compiler effectively writes this: // void setDay(Date* const this, int d) void setDay(struct Date* const p, int d) { // 1. THIS IS ALLOWED: // We are changing the DATA at the address. p->day = d; // 2. THIS WOULD CAUSE A COMPILER ERROR: // We are trying to change the ADDRESS of the pointer itself. // p = NULL; // Error: assignment of read-only parameter 'p' } int main() { struct Date myDate = {1}; setDay(&myDate, 15); printf("Day is: %d\n", myDate.day); return 0; }
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development