Skip to content

Instantly share code, notes, and snippets.

@audiolion
Created January 6, 2019 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audiolion/7ef4fb069b09a26cf7bc1cadfd2e2fee to your computer and use it in GitHub Desktop.
Save audiolion/7ef4fb069b09a26cf7bc1cadfd2e2fee to your computer and use it in GitHub Desktop.
/**
*
* A very simple refactoring that eliminates the need for a comment "This is the first attempt".
*
* I am not going to go into the details of why code is better than comments, books like
* The Pragmatic Programmer and Fowler's Refactoring provide well-reasoned arguments as to why
* this is the case.
*
*/
// Original
function updateSuspenseComponent(
current,
workInProgress,
renderExpirationTime,
) {
const mode = workInProgress.mode;
const nextProps = workInProgress.pendingProps;
// We should attempt to render the primary children unless this boundary
// already suspended during this render (`alreadyCaptured` is true).
let nextState: SuspenseState | null = workInProgress.memoizedState;
let nextDidTimeout;
if ((workInProgress.effectTag & DidCapture) === NoEffect) {
// This is the first attempt.
nextState = null;
nextDidTimeout = false;
} else {
// Something in this boundary's subtree already suspended. Switch to
// rendering the fallback children.
nextState = {
timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork,
};
nextDidTimeout = true;
workInProgress.effectTag &= ~DidCapture;
}
}
// Refactor
function updateSuspenseComponent(
current,
workInProgress,
renderExpirationTime,
) {
function firstAttempt(workInProgress) {
return (workInProgress.effectTag & DidCapture) === NoEffect
}
const mode = workInProgress.mode;
const nextProps = workInProgress.pendingProps;
// We should attempt to render the primary children unless this boundary
// already suspended during this render (`alreadyCaptured` is true).
let nextState: SuspenseState | null = workInProgress.memoizedState;
let nextDidTimeout;
if (firstAttempt(workInProgress)) {
nextState = null;
nextDidTimeout = false;
} else {
// Something in this boundary's subtree already suspended. Switch to
// rendering the fallback children.
nextState = {
timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork,
};
nextDidTimeout = true;
workInProgress.effectTag &= ~DidCapture;
}
}
@coryhouse
Copy link

In this case, I'd probably use a temp var rather than a func or comment:

const isFirstAttempt = (workInProgress.effectTag & DidCapture) === NoEffect

I tend to use temp vars instead of comments or functions for one liners.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment