Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sai Venkatesh- Backend - Improve speed and function of deleting multiple blue squares #1130

Open
wants to merge 2 commits into
base: development
Choose a base branch
from

Conversation

SFA23SCM35V
Copy link

@SFA23SCM35V SFA23SCM35V commented Oct 10, 2024

Description

Blue squares used to come back, now they just delete really slowly or not at all

Related PRS (if any):

This backend PR is related to the #2774 frontend PR.

Main changes explained:

Used async/await consistently, removing the callback approach from findById.
Simplified error handling by wrapping the entire block in a try/catch.
Replaced redundant return statements with direct res responses for permission and record checks.
Improved readability and structure by removing unnecessary comments and logs.

How to test:

  1. check into current branch
  2. do npm install and ... to run this PR locally
  3. Clear site data/cache
  4. log as Owner user
  5. Profile>Blue Square Section>Delete a bunch in a row
  6. verify functionality

https://www.loom.com/share/02a9fd342bf84425abdf547566c85035

@SFA23SCM35V SFA23SCM35V changed the title Improve speed and function of deleting multiple blue squares Sai Venkatesh- Backend - Improve speed and function of deleting multiple blue squares Oct 10, 2024
Copy link
Contributor

@nathanah nathanah left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just remove some of the comments to clean things up and I'll approve. The code refactor looks good.

src/controllers/userProfileController.js Outdated Show resolved Hide resolved
Comment on lines 1721 to 1728

/*
Used async/await consistently, removing the callback approach from findById.
Simplified error handling by wrapping the entire block in a try/catch.
Replaced redundant return statements with direct res responses for permission and record checks.
Improved readability and structure by removing unnecessary comments and logs.

const originalinfringements = record?.infringements ?? [];
*/

This comment was marked as resolved.

@one-community one-community added the High Priority - Please Review First This is an important PR we'd like to get merged as soon as possible label Oct 14, 2024
Copy link

@Ankuriboh Ankuriboh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactoring existing backend code, tested and should be ready to merge. Before that, please kindly remove all the unnecessary comments from the code.

Also, as mentioned in the corresponding frontend PR, please kindly branching out in this repo instead of a forked one. Thanks!

@sheetalmangate
Copy link

In the code refactor, a try-catch block is used for all code within the function. what If the .save() method fails, it should be handled either in a specific try-catch block or by using a callback function.

@SFA23SCM35V
Copy link
Author

@nathanah

  1. Consistent use of async/await and removal of callbacks
    Improved Readability and Debugging: By using async/await consistently instead of mixing callbacks with promises, the code becomes more linear and easier to understand. This makes it easier to spot bugs and reason about the program flow, which could reduce the time spent debugging.
    Reduced Nested Callbacks (Callback Hell): Callbacks often lead to deeply nested code structures, which are harder to maintain and debug. Using async/await flattens the code, making it more readable and maintainable.
    Impact on speed: While this change doesn't directly improve execution speed, it helps avoid bugs and potential inefficiencies in how asynchronous code executes, making your application less prone to errors like callback mismanagement (e.g., multiple responses).

  2. Simplified Error Handling with try/catch
    Less Complexity: Wrapping the whole asynchronous code block in a try/catch block allows you to handle errors in a single place instead of adding error handling to every callback. This reduces cognitive load for the developer and ensures that errors are caught and handled properly.
    Consistency: Simplified error handling ensures that all errors (network issues, database errors, etc.) are caught uniformly, which helps prevent unexpected crashes that could slow down the app.
    Impact on speed: While simplifying error handling itself doesn't directly speed up the code, better error management means that the app may handle failure cases (such as database errors) faster and more predictably, preventing performance degradation from unhandled exceptions.

  3. Removed Redundant return Statements
    Improved Flow: By directly sending responses using res.status(...).send(...) instead of unnecessary return statements, the code becomes more straightforward, reducing confusion.
    Code Simplicity: The more concise code means fewer instructions for the JavaScript engine to interpret, and while this is a micro-optimization, cleaner code usually leads to fewer bugs and easier performance profiling.
    Impact on speed: There's minimal direct speed improvement here, but a more straightforward control flow ensures that there are no unnecessary execution paths, which can help reduce response time.

  4. Reduced Unnecessary Comments and Logs
    Cleaner Code: Removing unnecessary comments and logs can speed up the development and testing process by reducing noise. During debugging, logging statements can slow down performance slightly, especially if they're placed in critical or frequent parts of the code, like inside loops or asynchronous functions.
    Less Disk I/O or Console Overhead: While logging helps during development, leaving unnecessary logs in production can introduce overhead, especially if logging is synchronous or involves writing to disk or remote services.
    Impact on speed: Removing unnecessary logging can marginally improve performance, especially if logging was blocking or performed during high-traffic operations. This is a small gain, but it can be noticeable in highly concurrent systems.

@nathanah

Consolidated Destructuring for Props
By destructuring props at the start of the function:
const { blueSquares, handleBlueSquare, hasPermission } = props;
Benefit: This reduces redundant lookups like props.hasPermission, making the code more concise and slightly faster at runtime (though the performance gain is negligible in modern JavaScript engines). The main benefit here is readability and easier debugging, which reduces development time when modifying or maintaining the delete functionality.

Simplified handleOnClick by Reducing Repeated Conditions
Before: You had multiple conditions handling edit, delete, and view actions separately.
After: You combined similar conditions into a single call, like so:
if (canEditInfringements || canDeleteInfringements) {
handleBlueSquare(true, 'modBlueSquare', blueSquare._id);
} else {
handleBlueSquare(true, 'viewBlueSquare', blueSquare._id);
}

Benefit: This makes the logic easier to follow, reduces unnecessary branches, and ensures quicker execution when deleting. Although the performance improvement is minimal, cleaner logic reduces the chance of bugs, making the delete functionality more reliable and easier to optimize in the future.

Moved Formatting Logic Inside JSX
Before: You were checking for conditions and formatting strings in separate blocks.
After: You moved this into the JSX for a more streamlined rendering process:
{blueSquare.createdDate ? ${formatCreatedDate(blueSquare.createdDate)}: : ''}
{blueSquare.description}

Benefit: This minimizes unnecessary intermediate logic and lets React handle the rendering more efficiently. This doesn’t directly speed up the deletion but makes rendering the component more efficient, especially in complex UIs with lots of elements. By reducing unnecessary overhead in rendering, React can potentially free up resources faster when performing state updates like deletion.

Removed Redundant Conditions and Comments
Benefit: Removing unused or redundant conditions reduces the number of checks the system has to make when rendering or handling click events. While this has minimal direct performance impact, it improves the overall flow of the code, making it easier to read, debug, and optimize in the future.
How These Changes Affect Deletion Speed
Reduced Logical Overhead: Simplifying the conditions for clicking (i.e., when a user clicks to delete a blue square) means the event handler is more straightforward, with fewer branching conditions. This can slightly reduce the time it takes for the function to determine what action to perform (edit, delete, or view), making deletion a bit faster in terms of execution.

Better Maintainability: Cleaner code is easier to modify and optimize. If you ever need to further optimize the delete functionality (e.g., through better state management or using React.memo to prevent unnecessary re-renders), having a cleaner base will make these optimizations more effective and easier to implement.

If you still feel it doesn't improve the speed, feel free to suggest changes.

@SFA23SCM35V
Copy link
Author

@Ankuriboh
removed the comments and will create a new branch in this repo from now
if everything works well please Approve the PR.

Copy link

@samarth9201 samarth9201 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code works as expected, just a small suggestion from security point of view. But overall looks okay.

Screenshot (86)

// Respond with success
res.status(200).json({ _id: updatedRecord._id });
} catch (error) {
res.status(400).send(error.message);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could possibly leak some sensitive information. For example, it can return stack traces which can contain information about database and environment variables. Instead send a standard error message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
High Priority - Please Review First This is an important PR we'd like to get merged as soon as possible
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants