0% found this document useful (0 votes)
3 views35 pages

Frameworks

The document explains various dependency injection patterns in React, including Constructor Injection, Setter Injection, and Interface Injection, highlighting their usage and benefits. It also introduces Aspect-Oriented Programming (AOP) concepts, illustrating how AOP can separate cross-cutting concerns like logging from business logic. Additionally, it covers the features of frameworks, data handling, rendering, and the Virtual DOM in React, emphasizing their importance in building efficient applications.

Uploaded by

cpine0223
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Frameworks

The document explains various dependency injection patterns in React, including Constructor Injection, Setter Injection, and Interface Injection, highlighting their usage and benefits. It also introduces Aspect-Oriented Programming (AOP) concepts, illustrating how AOP can separate cross-cutting concerns like logging from business logic. Additionally, it covers the features of frameworks, data handling, rendering, and the Virtual DOM in React, emphasizing their importance in building efficient applications.

Uploaded by

cpine0223
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Constructor Injection (React


Equivalent)
In React, this is basically passing dependencies via props when creating a component

Example
class ApiService {
getUsers() {
return ["Chris", "Alex"];
}
}

Inject via “constructor” (props)


function Users({ api }) { // dependency injected here
const users = [Link]();

return <div>{[Link](", ")}</div>;


}

// Usage
const api = new ApiService();
<Users api={api} />

Why this = Constructor Injection

●​ Dependency is provided at creation time


●​ Component cannot exist properly without it

This is the most common DI pattern in React

2. Setter Injection (React Equivalent)


Dependency is provided after the component is created

In React, this usually happens with:

●​ useState
●​ useEffect
●​ Updating props dynamically

Example
function Users() {
const [api, setApi] = [Link](null);

[Link](() => {
const service = new ApiService();
setApi(service); // setter injection
}, []);

if (!api) return <div>Loading...</div>;

const users = [Link]();


return <div>{[Link](", ")}</div>;
}

Why this = Setter Injection

●​ Component is created first


●​ Dependency is set later

Another clearer version (prop update)


function Users({ api }) {
if (!api) return <div>No API yet</div>;

return <div>{[Link]().join(", ")}</div>;


}

// Later...
<Users api={null} />
// then updated to
<Users api={new ApiService()} />

3. Interface Injection (React Equivalent)


This one is tricky because JavaScript doesn’t have real interfaces like Java.
But we simulate it using:

●​ Contracts (expected methods)


●​ Context + hooks

Example using Context


const ApiContext = [Link](null);

Provider (framework-like behavior)


function App() {
const api = {
getUsers: () => ["Chris", "Alex"]
};

return (
<[Link] value={api}>
<Users />
</[Link]>
);
}

Consumer (component expects a contract)


function Users() {
const api = [Link](ApiContext); // injected automatically

return <div>{[Link]().join(", ")}</div>;


}

Why this = Interface Injection

●​ Component doesn’t know what it gets

It just expects:​
[Link]()

●​
●​ The provider ensures the correct structure

That’s basically an interface contract


Quick Comparison (React Perspective)
Type React Equivalent How it looks

Constructor Injection Props <Users


api={api} />

Setter Injection useState / setApi(...)


updates

Interface Injection Context + contract useContext()

Important Insight
In React:

●​ Props = direct injection


●​ State/effects = delayed injection
●​ Context = framework-level injection

Simple Way to Remember


●​ Constructor Injection → “Give me everything upfront”
●​ Setter Injection → “You can give it to me later”
●​ Interface Injection → “I don’t care what it is, as long as it behaves correctly”

If you want next, I can show:​


a real production-level folder structure using DI in React (services, hooks, context) —
this is what companies actually use.

What AOP is (in plain words)


AOP is a way of adding extra behavior to your code without mixing it into your main
logic.

Let’s make Aspect-Oriented Programming (AOP) click using practical examples


(especially in JavaScript/React-style thinking).

1. First, the Problem AOP Solves


Imagine you keep repeating this everywhere:

function getUser() {
[Link]("Fetching user..."); // logging
// actual logic
}

function createUser() {
[Link]("Creating user..."); // logging again
// actual logic
}

Problem:

●​ Logging is repeated
●​ It’s mixed with business logic

This logging is a cross-cutting concern (it appears everywhere)

2. What AOP Does


AOP says:

“Let’s take that repeated logic out and apply it automatically wherever needed.”

3. Key Concepts with Examples


1. Aspect
A reusable module for a concern (like logging)

function loggingAspect(fn) {
return function (...args) {
[Link]("Before execution");
const result = fn(...args);
[Link]("After execution");
return result;
};
}

This is your Aspect (logging logic)

2. Join Point
A place where something happens (e.g., function call)

Example:

function getUser() {
return "User data";
}

Calling getUser() is a join point

3. Advice
The code that runs at the join point

In our example:

[Link]("Before execution"); // before advice


[Link]("After execution"); // after advice

4. Pointcut
Rule that decides where to apply the aspect
Example (manual pointcut):

const enhancedGetUser = loggingAspect(getUser);

You chose to apply logging to getUser

4. Full AOP Example (JavaScript)


function loggingAspect(fn) {
return function (...args) {
[Link]("Calling function...");
const result = fn(...args);
[Link]("Function finished");
return result;
};
}

function getUser() {
return "User data";
}

// Apply aspect
const wrappedGetUser = loggingAspect(getUser);

wrappedGetUser();

5. AOP in a React-like Scenario


Let’s say you want logging for API calls.

Without AOP
async function fetchUsers() {
[Link]("Fetching users...");
const res = await fetch("/api/users");
return [Link]();
}

async function fetchPosts() {


[Link]("Fetching posts...");
const res = await fetch("/api/posts");
return [Link]();
}

With AOP-style wrapper


function withLogging(fn) {
return async function (...args) {
[Link]("Starting request...");
const result = await fn(...args);
[Link]("Request finished");
return result;
};
}

Apply it:

const fetchUsers = withLogging(async () => {


const res = await fetch("/api/users");
return [Link]();
});

const fetchPosts = withLogging(async () => {


const res = await fetch("/api/posts");
return [Link]();
});

6. Real-World Cross-Cutting Concerns


AOP is commonly used for:

●​ Logging
●​ Authentication / Authorization
●​ Error handling
●​ Caching
●​ Performance tracking
7. AOP in Frameworks
Frameworks like:

●​ Spring Framework
●​ Angular (via interceptors)

Provide built-in AOP tools

Example in Angular:

●​ HTTP interceptors = AOP for API calls

8. Mental Model (Very Important)


Think of AOP like this:

●​ Your main code = what your app does


●​ Aspects = extra behaviors applied automatically

9. Simple Analogy
Think of a YouTube video:

●​ Video content = business logic


●​ Ads/logging/security = cross-cutting concerns

AOP = inserting ads without editing the video itself

Final One-Line Understanding


AOP lets you add behavior to many parts of your program without modifying those
parts directly.
If you want next, I can show:​
how AOP compares to middleware in Express or interceptors in React apps (this is
where it really becomes practical).

Lexis => these are the smallest building blocks of language called tokens

Keywords → if, return, function


Identifiers → variable names (user, count)
Operators → +, =, ===
Literals → "Hello", 10, true

Syntax => Rules governing how a language is structured

✅ correct syntax
❌ wrong syntax
let count = 10; //
let = count 10; //

Semantics => Logic behind a written code/ meaning of the code

if (true) {
[Link]("Hello");
}

Semantically:

●​ Condition is true → code runs

Pragmatics => How the code is used in real life

Focuses on Readability, maintainability, and best practices

// Works, but bad practice


var x = 10;

// Better
const userCount = 10;

Type System => How values are classified

let x = 10; // number


let y = "text"; // string
Alphabet => Set of all basic symbols or characters used to write a language

let x = 10;

Alphabet used:

●​ l, e, t, x → letters
●​ 1, 0 → digits
●​ = → symbol
●​ space → whitespace

Framework is a predefined structure that provides reusable tools, components and


guidelines that help developers build applications efficiently and consistently

Here are clear, well-structured notes on the Features of a Framework—useful for exams
and practical understanding.

What are Features of a Framework?


These are the key characteristics that make frameworks useful for building
applications efficiently and consistently.

Main Features of a Framework

1. Predefined Structure (Architecture)


Frameworks provide a ready-made structure for organizing code.

Example:

●​ Folder structure
●​ Separation of concerns (components, services, etc.)

In React:

●​ Component-based structure
2. Reusability
Code can be reused across different parts of the application.

Example:

●​ Components
●​ Services
●​ Utility functions

Saves time and reduces duplication

3. Inversion of Control (IoC)


The framework controls the flow of the application.

Instead of:



●​ You calling functions manually
●​ The framework calls your code when needed

Example:

●​ Lifecycle methods
●​ Event handling

4. Built-in Functionality
Frameworks provide ready-made features like:

●​ Routing
●​ State management
●​ Form handling
●​ API integration

Reduces need to build everything from scratch

5. Modularity
Applications are divided into independent modules/components

Benefits:

●​ Easier maintenance
●​ Better scalability

6. Extensibility
You can extend or customize the framework

Example:

●​ Plugins
●​ Middleware
●​ Custom hooks

7. Consistency & Standardization


Enforces a standard way of writing code

Benefits:

●​ Easier teamwork
●​ Predictable code structure

8. Dependency Injection Support


Frameworks help manage dependencies

Common in:

●​ Angular

9. Event-Driven Architecture
Frameworks respond to user actions (events)
Example:

●​ Clicks
●​ Form submissions

10. Performance Optimization


Built-in optimizations:

●​ Efficient rendering
●​ Lazy loading
●​ Caching

Example:

●​ Virtual DOM in React

11. Security Features


Helps protect applications from common threats

Example:

●​ Input validation
●​ Protection against XSS

12. Testing Support


Frameworks often include tools for:

●​ Unit testing
●​ Integration testing

Good catch—data handling and rendering are actually core features of modern
frameworks, especially in tools like React and Angular.
1. Data Handling in Frameworks
Data handling = how a framework manages, updates, and shares data in an
application

What it includes:
a) State Management

●​ Tracks data that changes over time

const [count, setCount] = useState(0);

When count changes → UI updates

b) Data Flow

Defines how data moves:

●​ React → One-way (parent → child)


●​ Angular → Two-way binding

c) API/Data Fetching
useEffect(() => {
fetch("/api/users")
.then(res => [Link]())
.then(setUsers);
}, []);

Frameworks make it easier to:

●​ Fetch
●​ Store
●​ Use data

d) Global Data Sharing


Sharing data across components

●​ Context API (React)


●​ Services (Angular)

Why Data Handling Matters:


●​ Keeps UI in sync with data
●​ Avoids inconsistencies
●​ Makes apps dynamic

2. Rendering in Frameworks
Rendering = how data is displayed on the screen (UI)

Types of Rendering:

a) Client-Side Rendering (CSR)

Browser renders UI using JavaScript

Used in:

●​ React

b) Server-Side Rendering (SSR)

Server sends fully rendered HTML

Used in:

●​ [Link]

c) Static Rendering (SSG)


Pages are pre-built

Dynamic Rendering (Important)


return <h1>{[Link]}</h1>;

UI updates automatically when data changes

Efficient Rendering
Frameworks optimize rendering:

Example in React:

●​ Virtual DOM
●​ Only updates changed parts

Why Rendering Matters:


●​ Determines performance
●​ Affects user experience
●​ Controls how fast UI updates

How Data Handling + Rendering Work


Together
This is the core idea of modern frameworks:

1.​ Data changes


2.​ Framework detects change
3.​ UI re-renders automatically

Example:
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);

Flow:

●​ Click → updates data


●​ Data changes → triggers rendering
●​ UI updates automatically

import React from "react"; (Needed to use JSX like)

import ReactDOM from "react-dom"; (Responsible for rendering React content to the
browser)

const numbers = [1, 2, 3, 4]; (Creates an array of numbers)

const updateNums = [Link]((number) => {

return <li key={number}>{number}</li>;

}); (.map() loops through the array for each number → returns a <li> element )

[Link](

<ul>{updateNums}</ul>, (actual rendering happens here)

[Link]("root") (react inserts everything inside this div)

);

Concept Focus Purpose

IoC Control flow Control of the program is shifted from you to the
framework.
example ([Link]("click",
handleClick))

DI Dependency management Dependencies are given to a class instead of being


created inside them

example (

function User({ api }) {

return [Link]();}

api is injected from outside

AOP Cross-cutting concerns Separate repeated additional behaviour without


changing the main logic

Example (

function withLogging(fn) {

return (...args) => {

[Link]("Start");

return fn(...args);

};

OOP Code structure Paradym that Organize code using objects and
classes while utilizing concepts like encapsulation,
inheritance and polymophism

ORM Database interaction Type of programming used to bridge the gap between
OOP and relational DB
Here’s a clear, exam-ready answer based on your question (React + Virtual DOM):

Virtual DOM vs Actual DOM


Virtual DOM

The Virtual DOM is a lightweight, in-memory representation of the real DOM used by React.

●​ It is a JavaScript object
●​ React updates the Virtual DOM first, then compares it with the previous version
(diffing)
●​ Only the changed parts are updated in the real DOM

Actual DOM

The Actual DOM is the real structure of the webpage in the browser.

●​ Direct updates are slow and expensive


●​ Any change causes re-rendering of elements

How the Virtual DOM Works


In React, the Virtual DOM works in the following steps:

1. Initial Render

●​ React creates a Virtual DOM representation of the UI


●​ It is then rendered to the Actual DOM

2. State Change

●​ When data/state changes, React creates a new Virtual DOM

3. Diffing
●​ React compares the new Virtual DOM with the previous one
●​ This process is called diffing

4. Reconciliation

●​ React identifies only the changed elements

5. Efficient Update

●​ Only those changed parts are updated in the Actual DOM

Difference between Component-Based Architecture


and SPA

Component-Based Architecture Single Page Application (SPA)

Focuses on building UI using Focuses on loading a single page and


reusable components updating content dynamically

Divides UI into independent Uses client-side routing


components

Improves reusability and Improves speed and user experience


maintainability

It is a design approach It is an application type

Example: Navbar, Footer components Example: Home, About pages without reload
Used in frameworks like React Implemented using frameworks like React

React Components Demonstration


[Link]

import React from "react";

function Navbar() {

return (

<nav>

<a href="/">Home</a> | <a href="/about">About</a>

</nav>

);

export default Navbar;

🔹 [Link]
import React from "react";

function Home() {

return <h1>Home Page</h1>;

export default Home;


🔹 [Link]
import React from "react";

function About() {

return <h1>About Page</h1>;

export default About;

🔹 [Link] (SPA behavior)


import React from "react";

import Navbar from "./Navbar";

import Home from "./Home";

import About from "./About";

function App() {

const path = [Link];

return (

<div>

<Navbar />

{path === "/" && <Home />}

{path === "/about" && <About />}

</div>

);

}
export default App;

👉 Shows:
●​ Reusable components
●​ SPA navigation (no reload)

End-to-End Web Application using Full Stack


Frameworks

1 Backend ([Link] + Express + MongoDB)

const express = require("express");

const mongoose = require("mongoose");

const cors = require("cors");

const app = express();

[Link](cors());

[Link]([Link]());

[Link]("mongodb://localhost:27017/mernDB");

const TaskSchema = new [Link]({

title: String,

});

const Task = [Link]("Task", TaskSchema);

// Create task
[Link]("/tasks", async (req, res) => {

const task = await [Link]([Link]);

[Link](task);

});

// Get tasks

[Link]("/tasks", async (req, res) => {

const tasks = await [Link]();

[Link](tasks);

});

[Link](5000, () => [Link]("Server running on port 5000"));

2 Frontend (React)

import React, { useEffect, useState } from "react";

import axios from "axios";

function App() {

const [tasks, setTasks] = useState([]);

const [title, setTitle] = useState("");

const fetchTasks = async () => {

const res = await [Link]("[Link]

setTasks([Link]);

};
const addTask = async () => {

await [Link]("[Link] { title });

setTitle("");

fetchTasks();

};

useEffect(() => {

fetchTasks();

}, []);

return (

<div>

<h2>Task Manager</h2>

<input

value={title}

onChange={(e) => setTitle([Link])}

placeholder="Enter task"

/>

<button onClick={addTask}>Add</button>

<ul>

{[Link]((task) => (

<li key={task._id}>{[Link]}</li>

))}

</ul>
</div>

);

export default App;

RESTful API
A RESTful API is an Application Programming Interface (API) that follows the principles
of REST (Representational State Transfer), an architectural style used for building web
services.

Key Idea
A RESTful API allows communication between a client (frontend) and a server (backend)
using standard HTTP methods.

Key Principles of REST


1.​ Client-Server Architecture​
The client (e.g., browser, React app) and server are separate and communicate via
requests and responses.

2.​ Statelessness​
Each request from the client must contain all the information needed. The server
does not store client session data.

3.​ Uniform Interface​


Uses standard HTTP methods:
●​ GET → Retrieve data
●​ POST → Create data
●​ PUT/PATCH → Update data
●​ DELETE → Remove data
4.​ Resource-Based​
Everything is treated as a resource (e.g., users, tasks), identified using URLs.​

Example:​

/api/tasks​
/api/users​

5.​ Use of JSON/XML​


Data is usually exchanged in JSON format.

Example of RESTful API


Request:

GET /api/tasks

Response:

{ "id": 1, "title": "Study", "completed": false },

{ "id": 2, "title": "Code", "completed": true }

Example in Express ([Link])


[Link]("/tasks", (req, res) => {

[Link]({ message: "Get all tasks" });

});
[Link]("/tasks", (req, res) => {

[Link]({ message: "Create task" });

});

Advantages of RESTful APIs


●​ Simple and easy to understand
●​ Scalable and flexible
●​ Uses standard HTTP protocols
●​ Works with many platforms (web, mobile, etc.)
●​ Stateless (improves performance)

Explain [Link]
[Link] is a lightweight web framework for [Link] used to build server-side applications
and APIs.

Features:

●​ Handles routing
●​ Supports middleware
●​ Simplifies server creation

Advantages of [Link]
●​ Fast and lightweight
●​ Easy to learn
●​ Flexible (minimal structure)
●​ Large ecosystem (middleware support)
Simple Middleware for Validation (middleware is any
logic that happens between when a request is made to
when a response is provided)

const express = require("express");

const app = express();

[Link]([Link]());

// Middleware

function validateUser(req, res, next) {

const { name } = [Link];

if (!name) {

return [Link](400).send("Name is required");

next(); // proceed if valid

// Route

[Link]("/user", validateUser, (req, res) => {

[Link]("User is valid");

});

[Link](3000, () => [Link]("Server running"));


Shows:

✔️
✔️
●​ Middleware usage
●​ Validation

Security Best Practices


1. Input Validation

●​ Prevents attacks like XSS and SQL injection


●​ Always validate user input

2. Authentication & Authorization

●​ Ensure only authorized users access resources


●​ Use tokens/password protection

Here are exam-ready, detailed notes on ORM (Object-Relational Mapping) organized by


testable areas that commonly appear in exams.

1. Definition of ORM (Very Important)


Object-Relational Mapping (ORM) is a technique that allows developers to map objects in
object-oriented programming languages (like Java, JavaScript, Python) to relational
database tables.

2. ORM Mapping Types


1. One-to-One Relationship
●​ One record in a table is related to one record in another table.

Example:
●​ User ↔ Profile

2. One-to-Many Relationship
●​ One record is linked to many records.

Example:

●​ One user → many orders

3. Many-to-Many Relationship
●​ Many records relate to many records.

Example:

●​ Students ↔ Courses

5. ORM in Practice (Frameworks)


Common ORM frameworks:

●​ Java → Hibernate / JPA


●​ [Link] → Sequelize / TypeORM
●​ Python → Django ORM / SQLAlchemy

6. Example ([Link] with Sequelize)


const { Sequelize, DataTypes } = require("sequelize");

const sequelize = new Sequelize("db", "user", "password", {

dialect: "mysql",

});
const User = [Link]("User", {

name: [Link],

email: [Link],

});

[Link]();

7. CRUD Operations using ORM (VERY


IMPORTANT)
Create

[Link]({ name: "Chris", email: "chris@[Link]" });

Read

[Link]();

[Link]({ where: { name: "Chris" } });

Update

[Link]({ name: "John" }, { where: { id: 1 } });

Delete

[Link]({ where: { id: 1 } });


8. Advantages of ORM
●​ Reduces SQL complexity
●​ Faster development
●​ Code reusability
●​ Database independence
●​ Easier maintenance

9. Disadvantages of ORM
●​ Slower than raw SQL in complex queries
●​ Less control over database operations
●​ Can generate inefficient queries
●​ Learning curve

10. ORM vs SQL


ORM SQL

Object-oriented Query-based

Easier to write More control

Less optimized Highly optimized


sometimes

Abstracts database Direct access

You might also like