Software Engineering Flashcards

(40 cards)

1
Q

What are the layers of MVC architecture, and how are they implemented in Spring Boot and React?

A

Answer:
Model: Represents the data and business logic. In Spring Boot, it includes JPA entities and repository classes.
View: Represents the user interface. React provides the front-end views, rendering the UI dynamically.
Controller: Manages the request and response flow. In Spring Boot, controllers process incoming HTTP requests using annotations like @RestController.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain JPA and its significance in Spring Boot.

A

What is JPA?
JPA (Java Persistence API) is a specification (a set of rules) for managing data between a Java application and a relational database.
It is part of Java’s official library, providing a way to map Java objects to database tables and vice versa.
Key Feature: JPA allows you to interact with the database using Java code instead of writing raw SQL.
What is ORM?
ORM (Object-Relational Mapping) is a technique where:
Java objects (like a User class) are mapped to database tables (like a users table).
Each field in the class (like name or email) corresponds to a column in the database.
This mapping makes it easy to save, retrieve, and manage data in a database.
How Does JPA Work in Spring Boot?
Entities Represent Tables:

JPA uses special Java classes, called entities, to represent tables in the database.

Java Example:

@Entity
public class User {
@Id
@GeneratedValue
private Long id; // Maps to a database column id

private String name;  // Maps to a column `name`
private String email; // Maps to a column `email` }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you annotate a 1 to many
relationship using JPA annotations?

A

@Entity
public class Parent {
@Id
@GeneratedValue
private Long id;

@OneToMany(mappedBy = "parent")
private List<Child> children; }

@Entity
public class Child {
@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are Repository Classes in Spring Boot?

A
  1. A repository class in Spring Boot is like a special helper tool for managing data stored in a database.
  2. It simplifies common tasks such as saving, reading, updating, or deleting data without needing to write complex database queries.
  3. For example:
    Instead of writing SQL like SELECT * FROM users, you can simply call a method like findAll() on your repository.
    by extending JpaRepository, your repository gets all the basic CRUD functionality automatically. You can also add custom queries if needed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is CRUD, and What Do CRUD Services Do?

A

CRUD stands for the four main operations you typically do with data:

Create: Add new data to the database (e.g., save a new user).
Read: Retrieve existing data (e.g., get all users or find a specific one).
Update: Modify existing data (e.g., change a user’s email).
Delete: Remove data (e.g., delete a user).
CRUD Services are methods or functionalities provided in the repository that allow you to perform these actions. For example:

save(entity) → Adds or updates a record.
findById(id) → Retrieves a record by its unique ID.
deleteById(id) → Deletes a record by its ID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why Are Repository Classes and CRUD Services Important?

A

Simplify Code: You don’t have to write SQL queries manually. Spring Boot does this for you using Java code.

Example: Instead of writing INSERT INTO users (name, email) VALUES (?, ?) for adding a user, you can use save(user).
Less Error-Prone: The framework automatically ensures that the queries are optimized and safe.

Easy to Extend: If you need more specific queries, you can write your own methods, like finding users by name or age.

Analogy
Think of a repository as a delivery driver and a CRUD service as the kitchen staff:

The driver (repository) takes and delivers orders.
The kitchen staff (CRUD service) prepares the food, checks the quality, and packages it before handing it to the driver.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why is JPA Important in Spring Boot?
Simplifies Database Operations.

A

You don’t need to write SQL for every operation. JPA provides methods like save(), findAll(), and deleteById() to handle these automatically.
Object-Oriented Approach:

Instead of working with raw database rows, you work with Java objects. This keeps your code cleaner and easier to understand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Dependency Injection, and why is it used in Spring Boot?

A

Dependency Injection (DI) is a way to provide objects (dependencies) that a class needs, instead of letting the class create those objects itself. It helps keep the code clean and flexible.
Why Use DI in Spring Boot?
Avoid Hardcoding: Instead of writing code to create objects, Spring Boot provides them automatically.
Easy Testing: You can replace real objects with fake ones (mocks) for testing.
Reusable Code: The same dependency can be used in multiple places.
Lifecycle Management: Spring Boot takes care of creating, using, and destroying objects when needed.
How Does It Work in Spring Boot?
Mark Classes as Beans: Use annotations like @Component, @Service, or @Repository to tell Spring Boot to manage these classes.
Inject Dependencies: Use @Autowired to let Spring Boot give your class the objects it needs.
Example:

java
Copy code
@Service
public class MyService {
private final MyRepository repository;

// Spring Boot gives you a MyRepository object automatically.
@Autowired
public MyService(MyRepository repository) {
    this.repository = repository;
}

public void doSomething() {
    repository.save(); // Use the dependency
} } Why Is This Useful? Less Work: Spring Boot handles the hard stuff, like creating and managing objects. Better Code: Classes don’t need to know how to create objects, making the code easier to change and test. Think of DI as asking for a tool you need, and someone hands it to you instead of you searching and making it yourself.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write a repository class and query methods for the Parent entity.

A

@Repository
public interface ParentRepository extends JpaRepository<Parent, Long> {
@Query(“SELECT p FROM Parent p WHERE p.name = :name”)
List<Parent> findByName(@Param("name") String name);
}</Parent>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are RESTFul web services

A

RESTful web services are a way for systems to communicate over the internet using standard web protocols, mainly HTTP, and following the principles of REST (Representational State Transfer). REST is an architectural style that defines a set of rules for creating scalable and flexible web services.

Key Characteristics of RESTful Web Services:
Stateless Communication:

Each request from a client contains all the information needed to process it.
The server does not store any client state between requests.
Resource-Based:

Everything in a RESTful service is treated as a resource (e.g., users, products, orders).
Each resource is identified by a URI (Uniform Resource Identifier), like /api/users or /api/orders/123.
Standard HTTP Methods: RESTful services use standard HTTP methods to perform operations on resources:

GET: Retrieve a resource or list of resources.
POST: Create a new resource.
PUT: Update an existing resource.
DELETE: Remove a resource.
Representation of Resources:

Resources are represented in formats like JSON or XML, which are easy to read and use.
Example of a JSON response for a user:
json
Copy code
{
“id”: 1,
“name”: “John Doe”,
“email”: “john.doe@example.com”
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are some common annotations used in RESTful web services?

A

Answer:
@RestController: Marks a class as a REST controller.
@GetMapping: Maps HTTP GET requests.
@PostMapping: Maps HTTP POST requests.
@RepositoryRestResource: Exposes repository methods as REST endpoints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Security in Spring Boot REST Applications

A

In Spring Boot REST applications, security ensures that sensitive data is protected, and only authorized users can access specific endpoints. This is achieved through authentication, authorization, and protection against common vulnerabilities.

Ways to Apply Security in Spring Boot REST Applications
Spring Security Framework:

Spring Security provides a powerful and flexible framework for implementing authentication and authorization.
Key features include:
Protecting endpoints using HTTP Basic, Form-based login, or token-based authentication.
Role-based access control.
CSRF protection (enabled by default).
Integration with secure hashing algorithms for password encoding (e.g., BCrypt).
HTTP Basic Authentication:

Simple and easy to implement.
Credentials (username and password) are sent with each request in the headers.
Example header:
bash
Copy code
Authorization: Basic base64(username:password)
HTTPS:

Use HTTPS (SSL/TLS) to encrypt data in transit, ensuring it is not intercepted.
Password Encoding:

Always store hashed passwords using a secure algorithm like BCrypt.
Role-Based Access Control:

Restrict access to specific endpoints based on user roles using annotations like @PreAuthorize or @Secured.
Securing Endpoints:

You can restrict access to specific REST endpoints in your SecurityConfig class:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain JWT (JSON WEB TOKEN)in particular in relation to Spring Boot REST

A

JWT (JSON Web Token) is a compact and self-contained way to securely transmit information between parties as a JSON object. It is commonly used for stateless authentication in REST APIs, where the server doesn’t need to keep track of user sessions.
Structure of a JWT
A JWT consists of three parts:

Header:

Contains metadata about the token, such as the algorithm used for signing and the token type.
json
Copy code
{
“alg”: “HS256”,
“typ”: “JWT”
}
Payload:

Contains claims (data) about the user, such as their ID, roles, and expiration time.
json
Copy code
{
“sub”: “user123”, // User ID
“name”: “John Doe”, // Name
“roles”: [“USER”], // Roles or permissions
“exp”: 1693449600 // Expiration time (Unix timestamp)
}
Signature:

A cryptographic signature that ensures the token hasn’t been tampered with. It is created by encoding the header and payload and signing them with a secret key.

Key Properties of JWT
Compact:

Small size makes it ideal for use in HTTP headers and query strings.
Self-Contained:

The token contains all the information required for authentication (e.g., user details, expiration).
Stateless:

The server does not store session data. The JWT itself contains the user’s information.
Secure:

The signature ensures the token’s integrity. If the token is altered, the signature becomes invalid.
How JWT Works in Authentication
User Authentication:

A user logs in with their credentials (e.g., username and password).
If valid, the server generates a JWT, signs it with a secret key, and sends it back to the client.
Client Stores the Token:

The client stores the JWT (e.g., in local storage or cookies).
Include JWT in Requests:

For subsequent API requests, the client includes the JWT in the Authorization header:
makefile
Copy code
Authorization: Bearer <JWT>
Server Validates the Token:</JWT>

The server verifies the token’s signature and checks its claims (e.g., expiration, roles).
If valid, the request is processed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the Virtual DOM in react?

A

The Virtual DOM (Document Object Model) in React is a representation of the real DOM. React uses it to optimize the process of updating the user interface by minimizing direct manipulations of the real DOM.
Virtual DOM Representation:

React creates a virtual representation (a “tree structure”) of the UI in memory.
This representation is a JavaScript object that mirrors the structure of the real DOM.
Reactivity with State/Props:

When the state or props of a React component change, React creates a new virtual DOM tree.
Efficient Updates to the Real DOM:

Once the diff is calculated, React updates only the parts of the real DOM that actually changed, rather than re-rendering the entire page.

Performance:
Direct manipulations of the real DOM are slow because the browser re-paints and reflows the layout after each change.
By using the virtual DOM, React minimizes expensive real DOM operations.

Analogy to Understand the Virtual DOM
Imagine the real DOM is a blueprint for building a house. Making changes directly to the blueprint (real DOM) is slow because every modification requires recalculating the structure of the entire house.

Instead, React uses a draft copy (virtual DOM) where changes are made quickly. Once you’re happy with the draft, you update only the necessary parts of the blueprint, saving time and effort.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why is the Virtual DOM used in react

A

Performance:
Direct manipulations of the real DOM are slow because the browser re-paints and reflows the layout after each change.
By using the virtual DOM, React minimizes expensive real DOM operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a Transpiler in React?

A

A transpiler in React is a tool that converts code written in one language or syntax (e.g., modern JavaScript or JSX) into a compatible version of JavaScript that can be understood by browsers or other environments.

React uses a transpiler because:

Modern JavaScript features (ES6+) and JSX (JavaScript XML) are not supported natively by all browsers.
Code needs to be converted into standard JavaScript to run in these environments.

Popular Transpilers in React
Babel:

When using TypeScript with React, the TypeScript compiler (tsc) transpiles TypeScript code into JavaScript.

Transpilers are also be used on languages that are compiled into javascript like JSX for React and typescript.

Why is a Transpiler Important in React?
Compatibility:

Converts modern JavaScript (ES6+) and JSX into a version of JavaScript that all browsers can understand.
Ensures React apps run seamlessly across different browsers.
Developer Productivity:

Allows developers to use modern syntax, features, and tools, like import/export, async/await, and JSX, which improve code readability and maintainability.
Backward Compatibility:

Older browsers that do not support ES6+ syntax can still run React applications after transpilation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why is a Transpiler Important in React?

A

Why is a Transpiler Important in React?
Compatibility:

Converts modern JavaScript (ES6+) and JSX into a version of JavaScript that all browsers can understand.
Ensures React apps run seamlessly across different browsers.
Developer Productivity:

Allows developers to use modern syntax, features, and tools, like import/export, async/await, and JSX, which improve code readability and maintainability.
Backward Compatibility:

Older browsers that do not support ES6+ syntax can still run React applications after transpilation.

18
Q

What is a functional Component in React

A

A functional component in React is a simple JavaScript function that takes props (properties) as input and returns React elements (JSX) that describe what should be displayed on the screen. They are a more concise and straightforward way to define components compared to class components.

Characteristics of Functional Components:
Simpler Syntax:
A functional component is just a function, unlike class components that require extending React.Component.
l components are reusable and make the codebase easier to maintain.

Now are the first choice for React apps as opposed to class components.

19
Q

How do context and props work in React?

A

Answer: Props pass data from parent to child components.
Context allows sharing data between components without explicitly passing props through every level.

20
Q

Create A simple 1 Page React app using Context and Props.

A

import React, { createContext, useContext, useState } from “react”;
import ReactDOM from “react-dom”;

// Create Context
const CounterContext = createContext();

// Main App Component
function App() {
const [count, setCount] = useState(0);

return (
<CounterContext.Provider value={{ count, setCount }}>
<h1>Simple Counter App</h1>
<CounterDisplay></CounterDisplay>
<IncrementButton></IncrementButton>
</CounterContext.Provider>
);
}

// Component to display the counter
function CounterDisplay() {
const { count } = useContext(CounterContext); // Access count from context
return <h2>Current Count: {count}</h2>;
}

// Component for the button to increment the counter
function IncrementButton() {
const { setCount } = useContext(CounterContext); // Access setCount from context
return <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>;
}

// Render the App
ReactDOM.render(<App></App>, document.getElementById(“root”));

21
Q

Explain @SpringBootTest in Spring Boot

A

@SpringBootTest:

Used for integration testing.
It loads the full application context, allowing testing of the complete setup (e.g., controllers, services, repositories).
Typically used with integration tests that require multiple layers of the application.
Example:
java
Copy code
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
// Test if the application context loads successfully
}
}

22
Q

Explain @Test in Spring Boot

A

@Test:

Marks a method as a test case in JUnit 5.
Used for basic unit testing or with other annotations for integration testing.
Example:
java
Copy code
@Test
void exampleTest() {
assertEquals(2, 1 + 1);
}

23
Q

explain @DisplayName Spring boot

A

@DisplayName:

Provides a custom name for test methods, making them more readable in test reports.
Example:
java
Copy code
@Test
@DisplayName(“Should add two numbers correctly”)
void additionTest() {
assertEquals(5, 2 + 3);
}

24
Q

Explain @DataJpaTest in spring boot

A

Configures a test for JPA components such as repositories.
Loads only the persistence-related components (e.g., database configurations, JPA repositories).
Example:
java
Copy code
@DataJpaTest
class RepositoryTests {
@Autowired
private MyRepository repository;

@Test
void testSaveEntity() {
    Entity entity = repository.save(new Entity("test"));
    assertNotNull(entity.getId());
} }
25
Explain @AutoConfigureMockMvc in spring boot
Used to configure and inject the MockMvc object for testing MVC controllers. Typically used with @SpringBootTest. Example: java Copy code @SpringBootTest @AutoConfigureMockMvc class ControllerTests { @Autowired private MockMvc mockMvc; @Test void testGetEndpoint() throws Exception { mockMvc.perform(get("/endpoint")) .andExpect(status().isOk()) .andExpect(content().string("Hello, World")); } }
26
Explain "Matchers" in relation to testing in react
Matchers: Used to assert conditions in tests. Example: javascript Copy code import { render, screen } from '@testing-library/react'; test('renders a heading', () => { render(

Hello, World!

); expect(screen.getByText('Hello, World!')).toBeInTheDocument(); });
27
Explain "waitFor" in relation to testing in react
Used to wait for asynchronous operations (e.g., data fetching) to complete. Example: javascript Copy code import { render, screen, waitFor } from '@testing-library/react'; test('loads and displays data', async () => { render(); await waitFor(() => expect(screen.getByText('Loaded data')).toBeInTheDocument()); });
28
Explain "getByText " in relation to testing in react
A query function to find an element containing specific text. Example: javascript Copy code import { render, screen } from '@testing-library/react'; test('renders welcome message', () => { render(

Welcome to the App

); const message = screen.getByText('Welcome to the App'); expect(message).toBeInTheDocument(); });
29
Explain "userEvent " in relation to testing in react
Simulates user interactions like clicks, typing, and more. Example: javascript Copy code import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; test('handles button click', () => { render(); userEvent.click(screen.getByText('Click me')); });
30
Explain "toBeInTheDocument " in relation to testing in react
Asserts that an element is present in the DOM. Example: javascript Copy code import { render, screen } from '@testing-library/react'; test('renders a component', () => { render(
Hello, World!
); expect(screen.getByText('Hello, World!')).toBeInTheDocument(); });
31
1. What is the purpose of async calls in React?
Async calls are used to fetch or send data to APIs without blocking the user interface, allowing the app to remain responsive.
32
2. What is a callback in JavaScript?
A callback is a function passed as an argument to another function, which gets executed after the main function completes. Example: javascript Copy code fetchData(data => { console.log(data); });
33
3. What is a promise in JavaScript?
A promise is an object that represents the eventual completion or failure of an asynchronous operation. Example: javascript Copy code fetch('https://api.example.com') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
34
4. What are async/await in JavaScript?
Async/await provides a cleaner syntax for handling promises, making asynchronous code look synchronous. Example: javascript Copy code async function fetchData() { const response = await fetch('https://api.example.com'); const data = await response.json(); console.log(data); }
35
5. What is Axios in React?
Axios is a library used for making HTTP requests, offering features like promises, automatic JSON parsing, and error handling. Example: javascript Copy code import axios from 'axios'; async function fetchData() { const response = await axios.get('https://api.example.com'); console.log(response.data); }
36
6. How do you fetch data from a REST API in a React component?
Use the useEffect hook to fetch data on component mount. Use Axios or Fetch API to make the HTTP request. Example: javascript Copy code useEffect(() => { async function fetchData() { const response = await axios.get('https://api.example.com'); setData(response.data); } fetchData(); }, []);
37
7. How do you manage API response data in React?
Use the useState hook to store the data and update it when the response is received. Example: javascript Copy code const [data, setData] = useState([]);
38
8. How do you handle loading states while fetching data in React?
Use a state variable (e.g., loading) to show a loading indicator until the data is fetched. Example: javascript Copy code if (loading) return

Loading...

;
39
9. How do you handle errors during API calls in React?
Use a try-catch block to catch errors and update an error state variable. Example: javascript Copy code try { const response = await axios.get('https://api.example.com'); setData(response.data); } catch (err) { setError('Failed to fetch data'); }
40
10. How do you display data fetched from a REST API in React?
Map over the fetched data array and render each item as a list or a component. Example: javascript Copy code
    {data.map(item => (
  • {item.name}
  • ))}