<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Neethack - Medium]]></title>
        <description><![CDATA[A blog about technology, programming and things. - Medium]]></description>
        <link>https://medium.com/neethack?source=rss----51941ecd316e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Neethack - Medium</title>
            <link>https://medium.com/neethack?source=rss----51941ecd316e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:10:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/neethack" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unlock React.js Success: Avoid those 6 Antipatterns]]></title>
            <link>https://medium.com/neethack/unlock-react-js-success-avoid-those-6-antipatterns-f507918ac2ae?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/f507918ac2ae</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 04:22:05 GMT</pubDate>
            <atom:updated>2023-12-05T02:10:56.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PycqoAZFrR-0xFErpzLGTg.png" /></figure><p>After working on React for a while, it has been through a paradigm shift from class components to functions and hooks, the best practice is constantly changing. However, after research based on my learning from the community and my experience, here are the antipatterns that people are often not aware of but hinder the success of the project:</p><h3>1. Use JSON data to render components</h3><p>By default, the React component is a declarative XML structure with a sprinkle of javascript. However, often we see people try to separate data and React components, for example rendering a menu with links:</p><pre>const links = [{<br>  title: &quot;Posts&quot;,<br>  url: &quot;/posts&quot;<br>}, {<br>  title: &quot;Search&quot;,<br>  url: &quot;/search&quot;,<br>  onClick: (e) =&gt; {<br>    e.preventDefault()<br>    console.log(&quot;searching…&quot;)<br>  }<br>}]<br>const Menu = () =&gt; (<br>  &lt;&gt;<br>    {links.map(link =&gt;<br>      &lt;a href={link.url} onClick={link.onClick}&gt;{link.title}&lt;/a&gt;<br>    )}<br>  &lt;/&gt;<br>)</pre><p>Looks like the data is separated from render logic, but the React JSX, which is XML, is a data structure too. If we write:</p><pre>const Menu = () =&gt; (<br>  &lt;&gt;<br>    &lt;a href=&quot;/posts&quot;&gt;Posts&lt;/a&gt;<br>    &lt;a href=&quot;#&quot; onClick={() =&gt; console.log(&quot;searching…&quot;)}&gt;Search&lt;/a&gt;<br>  &lt;/&gt;<br>)</pre><p>This is equivalent to the previous code, but is less abstract and more flexible since we can add optional logic to the JSX itself, rather than forcing the data to map from same JSON format. With large components, those json mapping can easily be getting out of control.</p><p>Another example is the Table header, for example:</p><pre>const headers = [&quot;ID&quot;, &quot;NAME&quot;, &quot;PRICE&quot;]<br>const Table = () =&gt; (<br>  &lt;table&gt;<br>  &lt;thead&gt;<br>  {headers.map(header =&gt; &lt;th&gt;{header}&lt;/th&gt;)}<br>  &lt;/thead&gt;<br>  &lt;tbody&gt;…&lt;/tbody&gt;<br>  &lt;/table&gt;<br>)</pre><p>It’s completely okay to just use pure `&lt;th&gt;ID&lt;/th&gt;` instead since it’s just a data structure. Unless for some edge cases you need to access the index by header value.</p><h3>2. Remap data from GraphQL/API</h3><p>One of the advantages of GraphQL is its flexibility to fetch the data we need, however, the field name and the inherited query structure might not 100% match what we want, for example:</p><pre>const Product = ({ id }) =&gt; {<br>  const { data, loading, error } = useQuery(gql`<br>    query findProduct($id: ID!) {<br>      find_product(id: $id) {<br>        id<br>        name<br>        original_price<br>        discount_price<br>        category {<br>          id<br>          name<br>        }<br>      }<br>    }<br>  `, { variables: { id }})<br>  <br>  if (loading || error) {<br>    return null;<br>  }<br>  const product = parseProduct(data.find_product)<br>  return (<br>    &lt;ProductItem <br>      name={product.name}<br>      price={product.currentPrice}<br>      category={product.categoryType}<br>    /&gt;<br>  )<br>}<br><br>function parseProduct(data) {<br>  return {<br>    …data,<br>    currentPrice: data.discount_price,<br>    originalPrice: data.original_price,<br>    categoryType: data.category.name<br>  }<br>}</pre><p>Here, because we don’t like the structure of GraphQL results, we map the nested fields to flat values and rename the field names to camel case.<br>Looks okay right? It looks more consistent and more descriptive. However when we want to track where the attributes from, it will inevitably hit the `parseProduct` function and it serves as an obfuscator in this case. Rename variable is good and it’s refactor 101, but changing the data structure from API will make it hard to track the flow of data and make the program harder to understand, isn’t worth the trade-off.</p><h3>3. Nesting components</h3><p>React is a component base library, which makes it easy to extract logic into components and use it in another component to separate the logic, however, it creates a problem that sometimes the business logic is nested deep inside the component tree, and makes it hard to understand, for example:</p><pre>const Query = ({ children }) =&gt; {<br>  const { data, loading, error } = useQuery(POSTS_QUERY);<br>  if (loading || error) {<br>    return null<br>  }<br>  return children(data.posts)<br>}<br><br>const Page = () =&gt; (<br>  &lt;Query&gt;<br>    {posts =&gt; &lt;Content posts={posts} /&gt;}<br>  &lt;/Query&gt;<br>)<br><br>const Content = ({ posts }) =&gt; {<br>  const [page, setPage] = useState(1);<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;Posts posts={posts} page={page} setPage={setPage}&gt;<br>      &lt;Footer page={page} /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>const Posts = ({ posts, page, setPage }) =&gt; (<br>  &lt;div&gt;<br>    {posts.slice(page * 10, 10).map(post =&gt; (<br>      &lt;Post post={post} /&gt;<br>    ))}<br>    &lt;Pagination page={page} setPage={setPage} /&gt;<br>  &lt;/div&gt;<br>)<br><br>const Post = ({ post }) =&gt; &lt;div&gt;{post.id}: {post.title}&lt;/div&gt;</pre><p>It’s a simple component to fetch and show the ID and title of posts, but the nested structure creates layers that need to jump up and down to understand the context, also nested components introduce the problem of props drilling, which is the props need to pass down from parent container, the more level of components, the more props we need to pass down. Compare to a more flattened version:</p><pre>const Page = () =&gt; {<br>  const { data, loading, error } = useQuery(POSTS_QUERY);<br>  const [page, setPage] = useState(1);<br>  if (loading || error) {<br>    return null<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;div&gt;<br>        {data.posts.slice(page * 10, 10).map(post =&gt; (<br>          &lt;div&gt;{post.id}: {post.title}&lt;/div&gt;<br>        ))}<br>        &lt;Pagination page={page} setPage={setPage} /&gt;<br>      &lt;/div&gt;<br>      &lt;Footer page={page} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>It is more straightforward to understand. When extracting components, we should prefer composition over nesting, extract logic to hooks first, and avoid nesting the component. Also, don’t define a child component inside another function component, it might trigger a render issue since each render creates a new function component reference.</p><h3>4. Clean code in the test</h3><p>Having code without duplication is not a bad thing, but it comes with a cost. In terms of testing, having clean code means the test will be harder to understand and maintain because the test is a part of the code serves as documentation about how to use a component, it is better to keep the test more readable rather than clean, for example:</p><pre>describe(&quot;Component&quot;, () =&gt; {<br>  let getByText, getByRole, queryByText, getByAltText<br>  const data = { post: { id: 1, title: &quot;Post&quot;, description: &quot;Test&quot; } }<br>  beforeEach(async () =&gt; {<br>    { getByText, getByRole, queryByText, getByAltText } = render(&lt;Component data={data}&gt;)<br>    await waitFor(() =&gt; {<br>      expect(queryByText(&quot;Loading&quot;)).not.toBeInTheDocument()<br>    })<br>  })<br>  <br>  it(&quot;display description&quot;, () =&gt; {<br>    expect(getByText(&quot;Post&quot;)).toBeInTheDocument()<br>  })<br><br>  it(&quot;display button&quot;, () =&gt; {<br>    expect(getByRole(&quot;button&quot;, { name: &quot;Submit&quot; })).toBeInTheDocument()<br>  })<br>})</pre><p>It looks good that the duplicated render and wait part is in the `beforeEach` block and shared through variables, however, the variable will cause the component to leak into the other tests. And the test itself no longer descriptive, since the majority of the action is happening before the test. A test that follows the steps of setup, action, and assert should be like:</p><pre>describe(&quot;Component&quot;, () =&gt; {<br>  const data = { post: { id: 1, title: &quot;Post&quot;, description: &quot;Test&quot; } }<br>  const renderComponent = async (data) =&gt; {<br>    const result = render(&lt;Component data={data}&gt;)<br>    await waitFor(() =&gt; {<br>      expect(result.queryByText(&quot;Loading&quot;)).not.toBeInTheDocument()<br>    })<br>    return result<br>  }<br><br>  it(&quot;display description&quot;, () =&gt; {<br>    const { getByText } = renderComponent(data)<br>    expect(getByText(&quot;Post&quot;)).toBeInTheDocument()<br>  })<br><br>  it(&quot;display button&quot;, () =&gt; {<br>    const { getByRole } = renderComponent(data)<br>    expect(getByRole(&quot;button&quot;, { name: &quot;Submit&quot; })).toBeInTheDocument()<br>  })<br>})</pre><p>It looks subtle but having the main action part inside the test can avoid variable leaking and make the test more readable and maintainable, especially when working on the long nested tests.</p><h3>5. useEffect</h3><p>`useEffect` is a hook that was first introduced to replace the original `componentDidMount` and other lifecycle methods, it’s a straightforward replacement. However, after people get more familiar with hooks, it turns out that the majority of the `useEffect` usage is a code smell. There are a couple of types of the hook:</p><h4>1. Transforming data</h4><p>Lots of usage of useEffect hook is transforming data from API or props into another state, for example:</p><pre>const Post = ({ id, user }) =&gt; {<br>  const [isAuthor, setIsAuthor] = useState(false)<br>  const { data, loading, error } = useQuery(QUERY, {<br>    variables: { id }<br>  })<br>  useEffect(() =&gt; {<br>    if (data) {<br>      setIsAuthor(data.post.author === user.name)<br>    }<br>  }, [data])<br><br>  if (loading || error) {<br>    return null;<br>  }<br>  const post = data.post<br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.description}&lt;p&gt;<br>      {isAuthor &amp;&amp; &lt;EditLink id={post.id} /&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>This will cause a double render since the use effect will be run after the render. And it turns out most of those states can just reduce from data in render:</p><pre>const Post = ({ id, user }) =&gt; {<br>  const { data, loading, error } = useQuery(QUERY, {<br>    variables: { id }<br>  })<br><br>  if (loading || error) {<br>    return null;<br>  }<br>  const post = data.post<br>  const isAuthor = post.author === user.name<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.description}&lt;/p&gt;<br>      {isAuthor &amp;&amp; &lt;EditLink id={post.id} /&gt;}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Those also include filter and sorting, which is derivative data from filter/sorting params, and the data, we can use `useMemo` hook to replace costly calculations.</p><h4>2. Handling events</h4><p>One usage of `useEffect` is the side effect of handling events, for example:</p><pre>const Page = () =&gt; {<br>  const [isOpen, setIsOpen] = useState(false)<br>  useEffect(() =&gt; {<br>    if (isOpen) {<br>      console.log(&quot;modal is opened by user&quot;)<br>    }<br>  }, [isOpen])<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Title&lt;/h1&gt;<br>      &lt;div&gt;<br>        Content<br>      &lt;/div&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true) }&gt;Open Modal&lt;/button&gt;<br>      &lt;Modal isOpen={isOpen} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Which would be easier to track by triggering the event in the callback itself:</p><pre>const Page = () =&gt; {<br>  const [isOpen, setIsOpen] = useState(false)<br>  const openModal = () =&gt; {<br>    setIsOpen(true)<br>    console.log(&quot;modal is opened by user&quot;)<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Title&lt;/h1&gt;<br>      &lt;div&gt;<br>        Content<br>      &lt;/div&gt;<br>      &lt;button onClick={() =&gt; openModal() }&gt;Open Modal&lt;/button&gt;<br>      &lt;Modal isOpen={isOpen} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>3. Fetching data</h4><pre>const Post = ({ id }) =&gt; {<br>  const [post, setPost] = useState(null)<br>  useEffect(() =&gt; {<br>    fetchPost(id).then((data) =&gt; setPost(data.post))<br>  }, [id])<br>  if (!post) { return null }<br>  return (<br>    &lt;div&gt;{post.id}&lt;/div&gt;<br>  )<br>}</pre><p>This might be the one legit use case for `useEffect` hooks, however, the recent promise compatible hooks like `useSWR` and `useQuery` in React Query or Apollo Client can better represent the data fetching by hiding the effect and handle the cache inside the hook.</p><pre>const Post = ({ id }) =&gt; {<br>  const { data, isError, isLoading } = useSWR(<br>    id,<br>    id =&gt; fetchPost(id).then((data) =&gt; data)<br>  )<br>  if (isLoading || isError) { return null }<br><br>  return (<br>    &lt;div&gt;{data.post.id}&lt;/div&gt;<br>  )<br>}</pre><h3>6. State management</h3><p>Application state management is the main complexity in most of the React apps. The good part of React is the component-based structure, meaning every component can have its state and manage it. However, when the service becomes complex, the component tree becomes bigger, and we unavoidably need to share the state with other components, creating the problem of prop drilling. Making components having lots of props and hard to maintain.</p><pre>const PostsPage = () =&gt; {<br>  const [posts, setPosts] = useState([])<br>  const [error, setError] = useState(null)<br><br>  useEffect(() =&gt; {<br>    fetchPosts().then(response =&gt; setPosts(response))<br>  }, [])<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;{error}&lt;/div&gt;<br>      {posts.map(post =&gt; &lt;Post post={post} setError={setError} setPosts={setPosts} /&gt;)}<br>    &lt;/div&gt;<br>  )<br>}<br><br>const Post = ({ post, setError, setPosts }) =&gt; {<br>  const [ isEditing, setIsEditing ] = useState(false)<br>  if (isEditing) {<br>    return &lt;EditPost post={post} setError={setError} setPosts={setPosts} setIsEditing={setIsEditing}/&gt;<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.description}&lt;/p&gt;<br>      &lt;p&gt;{post.author}&lt;/p&gt;<br>      &lt;p&gt;{post.createdAt}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setIsEditing(true) }&gt;Edit&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>const EditPost = ({ post, setError, setPosts, setIsEditing }) =&gt; {<br>  const [title, setTitle] = useState(post.title)<br>  const [description, setDescription] = useState(post.description)<br>  const onSubmit = async () =&gt; {<br>    try {<br>      await updatePost({ id: post.id, title, description })<br>      setPosts(posts =&gt; <br>        posts.map(p =&gt; {<br>          if (p.id !== post.id) {<br>            return p<br>          }<br>          return {<br>            …p,<br>            title,<br>            description<br>          }<br>       })<br>     )<br>    } catch (e) {<br>      setError(e.message)<br>    } finally {<br>      setIsEditing(false)<br>    }<br>  }<br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input <br>        name=&quot;title&quot;<br>        value={title}<br>        onChange={(e) =&gt; setTitle(e.target.value) }<br>      /&gt;<br>      &lt;input <br>        name=&quot;description&quot;<br>        type=&quot;text&quot;<br>        value={description}<br>        onChange={(e) =&gt; setDescription(e.target.value) }<br>      /&gt;<br>      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><p>When Facebook realized this issue in their development team, they came up with a solution called Flux, which means single-direction data flow, and it borrowed the concept of reducer from functional programming, becoming the Redux framework right now. The idea of Redux is managing the application state in a centralized store, and defining the event that changes the state as “action”, therefore every state can be equally accessed by every component. Therefore no more props drilling and state-sharing issues, every React developer lives happily ever after.</p><p>But no, Redux is a solution to solve that one problem but introduces a couple of the new problems, in the example using `react-redux` and `redux-toolkit`:</p><pre>const fetchPostsThunk = createAsyncThunk(<br>  &quot;fetchPosts&quot;,<br>  async () =&gt; {<br>    const posts = await fetchPosts()<br>    return posts<br>  }<br>)<br><br>const updatePostThunk = createAsyncThunk(<br>  &quot;updatePost&quot;,<br>  async ({ id, title, description }, { rejectWithValue }) =&gt; {<br>    try {<br>      const post = await updatePost({ id, title, description })<br>      return post<br>    } catch (error) {<br>      return rejectWithValue(error.message)<br>    }<br>  }<br>)<br><br>const postsPageSlice = createSlice({<br>  name: &quot;postsPage&quot;,<br>  initialState: {<br>    posts: [],<br>    error: null<br>  },<br>  reducers: {<br>    editPost: (state, action) =&gt; {<br>      const index = state.posts.findIndex(post =&gt; post.id === action.payload)<br>      if (index &gt;= 0) {<br>        state.posts[index].isEditing = true<br>      }<br>    }<br>  },<br>  extraReducers: (builder) =&gt; {<br>    builder.addCase(fetchPostsThunk.fulfilled, (state, action) =&gt; {<br>      state.posts = state.posts.concat(action.payload)<br>    })<br>    builder.addCase(updatePostThunk.fulfilled, (state, action) =&gt; {<br>      const index = state.posts.findIndex(post =&gt; post.id === action.payload.id)<br>      if (index &gt;= 0) {<br>        state.posts[index] = action.payload<br>      }<br>    })<br>    builder.addCase(updatePostThunk.rejected, (state, action) =&gt; {<br>      state.error = action.payload<br>    })<br>  }<br>})<br><br>const actions = postsPageSlice.actions<br><br>const store = configureStore({<br>  reducer: {<br>    postsPage: postsPageSlice.reducer<br>  }<br>})<br><br>const App = () =&gt; (<br>  &lt;Provider store={store}&gt;<br>    &lt;PostsPage /&gt;<br>  &lt;/Provider&gt;<br>)<br><br>const PostsPage = () =&gt; {<br>  const dispatch = useDispatch()<br>  const { posts, error } = useSelector(state =&gt; state.postsPage)<br>  useEffect(() =&gt; {<br>    dispatch(fetchPostsThunk())<br>  }, [dispatch])<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;{error}&lt;/div&gt;<br>      {posts.map(post =&gt; &lt;Post post={post} /&gt;)}<br>    &lt;/div&gt;<br>  )<br>}<br><br>const Post = ({ post }) =&gt; {<br>  const dispatch = useDispatch()<br>  if (post.isEditing) {<br>    return &lt;EditPost post={post} /&gt;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.description}&lt;/p&gt;<br>      &lt;p&gt;{post.author}&lt;/p&gt;<br>      &lt;p&gt;{post.createdAt}&lt;/p&gt;<br>      &lt;button<br>        onClick={() =&gt; dispatch(actions.editPost(post.id)) }<br>      &gt;<br>        Edit<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>const EditPost = ({ post }) =&gt; {<br>  const dispatch = useDispatch()<br>  const [title, setTitle] = useState(post.title)<br>  const [description, setDescription] = useState(post.description)<br>  const onSubmit = async () =&gt; {<br>    dispatch(updatePostThunk({ id: post.id, title, description }))<br>  }<br><br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input <br>        name=&quot;title&quot;<br>        value={title}<br>        onChange={(e) =&gt; setTitle(e.target.value) }<br>      /&gt;<br>      &lt;input <br>        name=&quot;description&quot;<br>        type=&quot;text&quot;<br>        value={description}<br>        onChange={(e) =&gt; setDescription(e.target.value) }<br>      /&gt;<br>      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><p>It introduces the following issues:</p><ol><li>Boilerplate: Using Redux will introduce multiple layers including actions and reducers, which make the application more complicated and even a simple UI state mutation become hard.</li><li>The complexity of the centralized state: In Redux’s ideology, every state needs to be stored in the Redux store, which forces the local state that is not shared between components to become global. In example, we have a list of posts, which have their own form and isEditing state. If completely follow the centralized state, we will have to move those state to Redux and manage them, rather to let component manage them locally.</li><li>Use Thunk to store remote data in Redux: In Redux, every state needs to be stored in a single store, including data from API, but essentially the API data is not controlled by the application. If we just store the result as it is, it is okay. But if the result needs to mutate to reflect the application change, for example, fetch a list when the user types things into search input, the user will need to handle those state disposal, mutation, and merge, which is hard to do it correctly. Also, thunk gives too much power to the developer, it could hide complex logic with multiple dispatch transitions that back and forth from the reducer and thunk itself, making it hard to understand compared to normal API calls.</li></ol><p>Overall, if we follow the ideology of Redux, which is a centralized state, it will have those extra complexities. If we don’t follow the ideology, and make shortcuts by maintaining local state and remote state separately, we are losing the benefit of a centralized state. Redux has a couple of benefits that are good when applying middleware like persists, but in other cases it is hard to use it correctly, it’s like communism, if you fail that must be because you are not following Communism, but if you are successful that also means you are not following the Communism.</p><p>Alternatively, I would suggests:</p><p>1. Flatten nested components: Consider restructuring the component hierarchy to reduce the need for state sharing and prop drilling. This can help simplify the component tree and make it easier to manage state locally within each component.</p><p>2. Explore alternative state management libraries: Instead of jumping straight to Redux, consider using alternative state management libraries like Jotai or Recoil. These libraries offer global state management capabilities while providing a simpler and more flexible API compared to Redux.</p><p>3. Consider Zustand for centralized store: If a centralized store is necessary for state management, consider using Zustand. Zustand is a lightweight state management library that provides a centralized store-like structure without the boilerplate and complexity associated with Redux.</p><p>4. Evaluate the need for Redux: Carefully assess whether Redux is truly necessary for the specific requirements of your application. While Redux has benefits like middleware support, it may introduce additional complexity and boilerplate for simpler UI state mutations.</p><p><em>originally from </em><a href="http://neethack.com/"><em>neethack.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f507918ac2ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/unlock-react-js-success-avoid-those-6-antipatterns-f507918ac2ae">Unlock React.js Success: Avoid those 6 Antipatterns</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Tetris with Zustand]]></title>
            <link>https://medium.com/neethack/react-tetris-with-zustand-b3a63f6a0297?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/b3a63f6a0297</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tetris]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[zustand]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 05:25:30 GMT</pubDate>
            <atom:updated>2022-10-15T05:25:30.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*nXjjzMEiNif6zAUyN4HmlA.png" /></figure><p><a href="https://neethack.com/react-tetris">Play Tetris Game</a></p><h3>Yet another React Tetris</h3><p>Tetris was created in 1984, it is a simple game in which the player controls the falling “tetromino”, and clears them by combining tetromino into one line. It is one of the most popular computer puzzle games and has hundreds of implementations on different platforms.</p><p>When I am looking for some side project to work on, I remembered once seeing a Tetris implementation by React, there are surprisingly lots of implementations of Tetris in React as if there is a category of it.</p><p>However, as a personal goal to distinguish from other projects, I want to implement this as simply as possible. Then I think of <a href="https://github.com/pmndrs/zustand">Zustand</a>, a framework I found when working on Apollo <a href="https://github.com/Rafe/apollo-reactive-store">Reactive Store</a>, it is much simpler than Redux and more readable than React hook.</p><h3>Zustand</h3><p>Zustand is a great framework, I recommend taking a look at the example on the home page. It has the benefit of a single monostore, without the complexity introduced by Redux. The usage is simple, we design the states we need for the Tetris, and combine the state and actions that will modify the state into the store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/657184550422540b4c7975161ab2c6f1/href">https://medium.com/media/657184550422540b4c7975161ab2c6f1/href</a></iframe><p>And than we can use the store like `const { gameState, level, line } = useGame(state =&gt; state)` in React Component.</p><h3>Application logic</h3><p>One of the goals for this project is to implement Tetris without too many abstractions and make the code as close as possible to the application logic. As a result, I write down the Application as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aed2a9f775d92ef053b2cfa1554cf1a/href">https://medium.com/media/4aed2a9f775d92ef053b2cfa1554cf1a/href</a></iframe><p>As the implementation in <a href="https://github.com/Rafe/react-tetris/blob/main/src/App.tsx">App</a>, the logic can be pretty close to the description within the Zustand store, without too much jumping between code or extra modules/variables.</p><h3>Game loop, Movement and Coyote Time</h3><p>The main game loop only contains one simple logic, if the game is started, trigger ArrowDown every tick. The main game logic is actually inside the ArrorDown key.</p><p>When we press the left or right arrow key, we simply check if the position is empty, and move the current piece. But when moving down, it has a lot more to consider. If the piece can not move anymore, first we need to give some time for the player to adjust the piece, we called those “coyote time” in the game. (based on the cartoon character coyote, who can float a little bit before falling down the cliff). We record the time of the tick that the piece stall. If no movement after a certain time, or if moving but exceeds the time limit, we “lock” the piece into the board, clear the full lines, and pop the new piece. This gives the player some time to adjust the piece to the right place, especially useful when under high level since the piece falls in 1 sec and most of the time will be coyote time.</p><p>If the next piece can not be popped, the game will be over, which is also triggered when ArrowDown is triggered.</p><h3>Rotation, Wallkick, and Smooth Criminal</h3><p>Rotation is a tricky part of the application. Generally, there are couple of ways to implement this:</p><p>1. Run matrix transition.<br>2. Create 4 different pieces for each direction.<br>3. Mix 1 and 2, create one piece centered in the pivot, and run matrix transition.</p><p>The problem with matrix transition is, we want the piece to rotate around the “pivot”, for example, a T piece will rotate around the centerpiece, but matrix transition will make the result “shifted” a bit. So it will need adjustment afterward, the solution I used is, to record the position of the pivot while matrix transitions, and shift the piece to keep the pivot in the same position.</p><p>Another interesting feature is, while rotating, if the position is not available, we want to shift the piece to the next empty place. That makes the player can maneuver the piece around under coyote time. Implementation is pretty straight forward, I compare the rotated piece with different positions, if the current position is not available, move down, else left, right, or up. Until an empty position is found, or return the original piece.</p><p>Combine with Coyote Time, this makes the game can be played smoothly under high speed, or else the game will end quickly at a high level.</p><h3>Animation</h3><p>There is 2 animation in the game, while hard drop the piece with space, the piece falls immediately, we play a “shaken” animation to indicate the speed. Another is when the line is full, we play clear animation. That animation is simple with CSS but complicates the application logic a bit due to the timing. I have to insert multiple “setTimeout” to play the animation. Maybe an async function/generator approach might be better.</p><h3>Repeat button</h3><p>While using keyboard input, it has a default repeat rate depending on the operating system setting. We want to overwrite it to have a consistent control, and also implement it for the button controller. For the keyboard basically, we listen to the keyboard “keydown” and “keyup” events, while the key is pressed, record the event in a global hash after 150ms repeat the event in a 50ms interval until the key is released.</p><p>For the button, it is a bit complicated due to the touch event also happening. Currently, when you touch the button, it will trigger events in this sequence:</p><p>- touchStart<br>- touchEnd<br>- mouseDown<br>- mouseUp</p><p>So we have to record the touch event in `touchStart`, and reset it after the final `mouseUp` event, also support the case for only “mouseDown” and “mouseUp” which is so confusing just by describing it… however, I reference other implementations and come out with logic for it.</p><h3>Conclusion</h3><p>Tetris is a game that is pretty simple but includes a lot of details to make the game more playable. It is pretty fun to dig into those history and implementation details and eat dog food for fun all the time. I am pretty happy with the result, Although I might need to put more effort into design in the future version…</p><h3>References</h3><p>[<a href="https://github.com/brandly/react-tetris](https://github.com/brandly/react-tetris)">https://github.com/brandly/react-tetris](https://github.com/brandly/react-tetris)</a><br>[<a href="https://github.com/chvin/react-tetris](https://github.com/chvin/react-tetris)">https://github.com/chvin/react-tetris](https://github.com/chvin/react-tetris)</a><br>[<a href="https://tetris.com/play-tetris](https://tetris.com/play-tetris)">https://tetris.com/play-tetris](https://tetris.com/play-tetris)</a><br>[<a href="https://tetris.wiki/](https://tetris.com/play-tetris)">https://tetris.wiki/](https://tetris.com/play-tetris)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a63f6a0297" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/react-tetris-with-zustand-b3a63f6a0297">React Tetris with Zustand</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop being a 10x engineer]]></title>
            <link>https://medium.com/neethack/stop-being-a-10x-engineer-f28952b9e0cc?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/f28952b9e0cc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[career-development]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Wed, 24 Nov 2021 04:26:18 GMT</pubDate>
            <atom:updated>2021-12-10T01:07:26.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NV2Nnba132PNsyRQTvW3Dg.png" /></figure><p>Have you heard from the recruiters or internet memes, talking about a special kind of engineer, called 10x engineer?<br>Rumor says those engineers can write 10x more code than their coworkers, and get 10x more jobs done. At the same time, they are only working at midnight,<br>using only command-line and vim, and perform every task by automation scripts.</p><p>Where is the 10x engineer name coming from? How do they know and evaluate people can achieve 10x more jobs than others? Turns out the original of this is from a study in 1968, E<a href="http://web.eecs.umich.edu/~weimerw/481/readings/productivity-performance.pdf">xploratory experimental studies comparing online and offline programming performance</a>. The study has a total of 24 engineers, group them into 2 groups and try to solve algorithm problems like Maze and Algebra. Afterward compare the time they spend on the task, debugging time, and program runtime. Turns out there is a huge difference between the best and the worst engineer, all of those differences can be approximated with a ratio of 10:1. This means the best engineer performs 10 times better than the worst engineer.</p><p>This study certainly doesn’t mean the engineer can perform 10x better in real-life jobs. First, this is using algorithm problems but not real engineering problems. Second, it is comparing the worst to the best, but not median or average, I can find a high school student and compete on algorithm problems, but that doesn’t make me perform 10x better than the average engineer. Third, it is a limited experiment that is only performed with small samples and fixed tasks, doesn’t have enough presence to the whole group.</p><p>However, we all know some brilliant engineers that can solve the problems that we can’t solve, know a lot more things than us, and create outstanding projects. In this perspective, the study is not completely wrong. After all, the whole industry is built up by some genius engineers like Linus Torvalds, DHH, Matz, Steve Wozniak, Guido van Rossum… We can undoubtedly say they have more than 10x impact on the industry than average engineers.</p><p>So the real problem is not that some engineers perform much more than others, but is when seeking those performances, people evaluate the wrong things and accidentally encourage the toxic traits.</p><h3>Toxic traits</h3><p>In a series of tweets by <a href="https://twitter.com/skirani/status/1149302828420067328">@skirani</a>, he described the 10x engineers as the person who “hate meetings”, “working at night”, “poor mentors” and “use black desktop background” (this is real). Of course, this got bashed hard on the internet. Some of the traits are full of bias and problematic behaviors, but it is also an iceberg on people’s impression about 10x engineers, they are smart but hard to manage, have strong passion but also lose interest in tasks if they get bored, doesn’t like rules, often go rogue on their things but working even in off-hours, having a strong opinion about things, will spend hours to debate on small things, doesn’t like other people changing or having an opinion about their code.</p><p>Of course, lots of smart engineers act in this way. Partly is because being smart and passionate about programming enhances people’s ego. Combine with those images about genius engineers make people think it is okay to follow the passion, avoid meetings and communications to get things done, work on other parts of the system, read through the legacy source codes to refactors and get annoyed when people doubt the obvious things or having “stupid” questions. They think they are contributing more compare to other coworkers until they wonder why they got a really bad review at the end of the year.</p><p>The first thing is those 10x engineer traits are wrong about causality, some genius engineers might act in this way, but acting like genius engineers doesn’t make you a genius, it just gives people an excuse to act like this. There is a tendency for engineers to lack socialization and have a strong ego, but it is not an excuse to not learn to avoid those behaviors. A good engineer should be and only be decided by the overall performance, but not about those toxic traits.</p><p>Although it might be partially true, they contribute more depending on the way people measure performance. They finished more tickets, write more code than others. But at the same time, the reality is more complicated. In the end, it is people reviewing the performance. So if the manager or coworker doesn’t recognize the things they are working on, it doesn’t mean too much to the performance. And most of the time the manager won’t read every line of code they wrote. Also changes and refactoring the code unavoidably create more bugs and issues, giving a bad impression that they are bringing troubles if they are also working in their project. Moreover, is it really benefit the company? Because personal interest doesn’t necessarily align with the company’s interest. They might create a self-made framework just for fun when there are existing choices, which in the end brings more troubles to the people who have to maintain it.</p><h3>Definition of outstanding / 10x</h3><p>If writing more code, finishing more tickets, and following the passion doesn’t make you the 10x engineer, what should you do? People need to think inversely about the definition of outstanding. The outstanding is a comparison standard, the point of 10x engineer is not getting 10x things done, but is not acting like a 1x engineer. There is no need to become a rockstar in the team, but just don’t be the asshole in the team.</p><p>So for being a 10x engineer, people need to first avoid making mistakes. Although everybody is saying you have to be courageous and make mistakes. But it is different to make “calculated” mistakes and “avoidable” mistakes. It is like taking bets, even you are making the bets that have higher than average odds, there are still chance to fail, this is essentially different than just taking a bet with low odds and expecting it to work out. For not being a 1x engineer, you need to avoid those careless mistakes, careful about what you are writing, don’t write bad code, don’t create bugs, don’t work on the things that no one asks you to do, focus on the project, ask people if you don’t know things, make sure the thing you do is correct, meet the expectation of delivery time and don’t overpromise. At the same time, listen to other people’s opinions, be nice to coworkers, avoid having an ego in meeting and code. By achieving those, you can have a good review and happily avoid being a 1x engineer in the team.</p><p>After that, you can finally consider how to be more productive and increase the impact on the team and company. Increasing the technical ability is one thing, read source code, create side projects, learning frameworks, use automation, tools, and IDE… etc, there are lots of ways to learn and to increase productivity. But essentially, from the company’s standpoint, it doesn’t matter how good you are, you need to deliver results to be actually productive. First you need to find out what is the right thing to do, deliver and take credit from it. You have limited time and focus, so it’s better not just randomly work on something that you feel is interesting, you need to find the right problem to solve by asking people, collecting opinions, and creating spikes to validate it. Afterward, you need to take credit for it. Because the manager will not recognize the code you wrote, even the coworker. Host a lunch to share the knowledge, do an announcement and presentation in a company meeting. It is not necessary for solving the problem, but it can build up the reputation, so the next time you can have more trust and freedom to work on things, and give you something to say in self-review.</p><p>And then you need to help the team because the performance is evaluated by the team. If the team does not perform well, you will not have a good performance too. The simple way is to do the same inverse thinking at the team level. Helping the team to deliver fewer bugs, write simple code and make sure it is implementing the feature that the user needs. For achieving that, code review is a good way to provide feedback and find potential bugs. Also asking the right questions in meetings to clarify the user needs. But also you need to understand team dynamics, sometimes saying things directly, pointing out mistakes does not work well if you did not build up trust with the team. Knowing the team and using the right approach to help the team, is one of the hardest things to learn, but also essential to the productivity of the team.</p><p>Finally, you need to manage the expectation from the manager, eventually, they are the ones to decide your performance. But the manager’s job is not to make your success, but to make sure you don’t mass up. So there is a conflict of interests, working on something cool that benefits the company, actually doesn’t align with the manager’s interest. Because the manager won’t get credit even if you achieve that but take the blame if you failed. That is why by research the middle manager is not as innovative as workers and executive officers. That is why you need to manage up to align the interests. One way is to ask the manager for a promotion, career development, or interesting projects to work on. Having discussions and setup clear expectations about success. Review the progress together, let the manager solve the problem for you, and also take credit for your success.</p><h3>Given 10x impact</h3><p>But even though you matched the expectation and deliver results, that will still not make you a 10x engineer. So we are going back to the same question: how to become a 10x engineer?</p><p>If you review the examples of those genius engineers, like Linus Torvalds, did he write the whole Linux kernel by himself? Obvious not. Software is a team sport, a successful software involves a lot of people’s contributions and efforts. The iconic genius engineers usually are the ones who start the project and get credits from the later success. Eventually, the engineer can give more than 10x impacts is the leader of the successful project and team.</p><p>For leading the project to success, having good communication skills is important. Only the person who can communicate well, mentor, and share knowledge with others, can lead other talented engineers to contribute to the project. On the other hand, having good technical skills can help, but more important is to learn from others. The project will always have unknowns, so it is more important to be able to quickly learn what you don’t know and connect that knowledge to solve the problem. Last is the execution, it might sound cliche but eventually, the leader needs to work hard to make the project successful. Eventually, how to focus the leader on the project, is one of the most important factors for success.</p><h3>Conclusion</h3><p>Therefore, for being a 10x engineer, you need to be able to lead the project to success. Avoid making avoidable mistakes, help and mentor others, manage the expectation from management, and finally work hard to execute the project to success. Forgot about those specific traits or toxic traits, it only creates more engineers that are an asshole, and given the excuse to not be a nice person to work with.</p><p><em>originally from </em><a href="https://neethack.com/2021/11/stop-being-a-10x-engineer/"><em>neethack.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f28952b9e0cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/stop-being-a-10x-engineer-f28952b9e0cc">Stop being a 10x engineer</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Source code odyssey: GraphQL Ruby]]></title>
            <link>https://medium.com/neethack/source-code-odyssey-graphql-ruby-9bd7b9eff24b?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/9bd7b9eff24b</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 16:58:55 GMT</pubDate>
            <atom:updated>2021-11-24T04:28:26.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*ULNJUwyqSBT2Nnh_Jj0k_Q.png" /></figure><p>Recently I am working with GraphQL on a day-to-day basis. The more I work with it, the more I like the GraphQL API compared to the traditional Restful API. And it is an interesting project, this article is going to do a deep dive on the ruby implementation of <a href="https://graphql-ruby.org/">GraphQL</a> and share some discoveries along the way.</p><p>GraphQL is developed by Facebook (Now Meta), during the development of the new version of Facebook, they found a problem in Restful API that the API can not adapt to the rapid change of client, either it fetches too much data that the client does not need, or it does not have the data it needs for rendering. Therefore they have the idea to create an API specific scripting language to describe what API can provide, what the client wants and execute to give the exact data the client needed in a declarative way, for example:</p><pre>query {<br>  user(id: 1) {<br>    id<br>    name<br>    emailcartItems {<br>      id<br>      name<br>      price<br>    }<br>  }<br>}</pre><p>The GraphQL query start from a query root, and declare the data `fields` it needs from query root, in this example we query the `user` field with argument `id:1`, and after the field we can select more fields that we want to query from the return type, and it can be nested like a graph. The API provides a schema so you know what is the valid fields for each types.</p><pre>schema {<br>  query: QueryRoot<br>}</pre><pre>type QueryRoot {<br>  user(id: ID!): User<br>}</pre><pre>type User {<br>  id: ID!<br>  name: String!</pre><pre>  cartItems: [CartItem!]!<br>}</pre><pre>type CartItem {<br>  id: ID!<br>  name: String!<br>  price: Int!<br>}</pre><p>This defines the types and data that the API provides. So the user can fabricate the query to fetch exactly the data they need for the client.</p><p>So how is the GraphQL query executed in the backend? It is similar to how interpreters run scripting language since GraphQL is a mini scripting language itself.</p><h3>Lifecycle</h3><p>As a scripting language, the query is passed to the API by a POST request, and executed in the backend in following sequence:</p><ol><li>Tokenize: `GraphQL::Language::Lexer` splits the string into a stream of tokens</li><li>Parse: `GraphQL::Language::Parser` builds an abstract syntax tree (AST) out of the stream of tokens</li><li>Validate: `GraphQL::StaticValidation::Validator` validates the incoming AST as a valid query for the schema</li><li>Analyze: If there are any query analyzers, they are run with `GraphQL::Analysis.analyze_query`</li><li>Execute: The query is traversed, `resolve` functions are called and the response is built</li><li>Respond: The response is returned as a Hash</li></ol><h3>Tokenize and Parse</h3><p>Like every programming language. Before we execute the GraphQL query, we need to parse it to create an Abstract Syntax Tree. In GraphQL-Ruby, the parser is implemented by <a href="https://github.com/ruby/racc">racc</a>. Which provides a syntax to generate Ruby compiler to parse another language.</p><p>In GraphQL ruby, the entry point is `GraphQL.parse(query)` which invoke the `GraphQL::Language::Parser.parse`, which generated by <a href="https://github.com/rmosolgo/graphql-ruby/blob/master/lib/graphql/language/parser.y">parser.y</a></p><p>`parser.y` define the GraphQL grammer rules, tokenize the query by `GraphQL::Language::Lexer.tokenize(graphql_string)` and implement `make_node` method to create AST:</p><pre>def make_node(node_name, assigns)<br>  assigns.each do |key, value|<br>    if key != :position_source &amp;&amp; value.is_a?(GraphQL::Language::Token)<br>      assigns[key] = value.to_s<br>    end<br>  end</pre><pre>  assigns[:filename] = <a href="http://twitter.com/filename">@filename</a></pre><pre>  GraphQL::Language::Nodes.const_get(node_name).new(assigns)<br>end</pre><p>This method is the main action to execute in the parser, which creates nodes and Abstract Syntax Tree by `node_name`. `node_name` is defined in the rule, includes `Field`, `OperationDefinition`, `TypeName`, `Argument`, etc… For example, from the query in the example we can create the AST like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df591e03202827684ea1b61a080ddd5/href">https://medium.com/media/5df591e03202827684ea1b61a080ddd5/href</a></iframe><p>From the output we can see the basic layout of the AST, each node has a set of `children_methods` that differ by type of nodes. For `Field`, it is `arguments`, `name`, `directives`, and `selections`, and can call `Field#children` to retrieve them for recursion. Also, the node has a `#scalar_methods` method for comparison and `#merge` for manipulating nodes.</p><p>For more details about programming language in general, includes Tokenize and Parsing. I suggest the ebook: <a href="http://createyourproglang.com/">create your programming language</a> or the <a href="https://github.com/kanaka/mal">MAL</a> project.</p><h3>Validate and Analyze</h3><p>After we have the AST and save it in the `GraphQL::Query` object, the next step is to validate the AST is valid for the schema, and analyze the complexity and information of the AST.</p><p>We call `GraphQL::StaticValidation::Validator#validate` with the Query object, and call the visitor `GraphQL::StaticValidation::BaseVisitor` which is a depth-first traversal visitor that include the rules in `GraphQL::StaticValidation::ALL_RULES` that defines all validation rules like: `FieldsAreDefinedOnType`, `FragmentNamesAreUnique`. The visitor will traverse the AST, when it visits a node, it will run the corresponding method like `on_field`, `on_argument` that is defined in rules, and return the Query is valid or not in the end.</p><p>After validation, we run the `query_analyzer` defined in the Schema and use the `GraphQL::Analysis::AST::Visitor` to analyze the query AST. Basically, it works similar to `GraphQL::StaticValidation::BaseVisitor` but it can carry analyzers and call the analyzer methods when visiting nodes. For example, the `QueryDepth` analyzer looks like this:</p><pre>class QueryDepth &lt; Analyzer<br>  def initialize(query)<br>    <a href="http://twitter.com/max_depth">@max_depth</a> = 0<br>    <a href="http://twitter.com/current_depth">@current_depth</a> = 0<br>    super<br>  end</pre><pre>  def on_enter_field(node, parent, visitor)<br>    return if visitor.skipping? || visitor.visiting_fragment_definition?</pre><pre><a href="http://twitter.com/current_depth">@current_depth</a> += 1<br>  end</pre><pre>  def on_leave_field(node, parent, visitor)<br>    return if visitor.skipping? || visitor.visiting_fragment_definition?</pre><pre>    if <a href="http://twitter.com/max_depth">@max_depth</a> &lt; <a href="http://twitter.com/current_depth">@current_depth</a><br>      <a href="http://twitter.com/max_depth">@max_depth</a> = <a href="http://twitter.com/current_depth">@current_depth</a><br>    end<br>    <a href="http://twitter.com/current_depth">@current_depth</a> -= 1<br>  end</pre><pre>  def result<br>    <a href="http://twitter.com/max_depth">@max_depth</a><br>  end<br>end</pre><p>Which is called by `GraphQL::Analysis::AST.analyze_query` to return the results. By default it only records errors, but we can extend the analyzer to log the result.</p><h3>Schema and Types</h3><p>After analyzing the query, we can start executing the query on the schema we defined. But before that, we need to explain how the schema is defined in the graphql-ruby gem. There are 3 main classes in the schema: `GraphQL::Schema`, `GraphQL::Schema::Object` and `GraphQL::Schema::Field`.</p><p>`GraphQL::Schema` is the root of the schema, it provides an interface to execute the query, contains the root types for exposing the application, query analyzers, and execution strategies. There are 3 root types for `query`, `mutation`, and `subscription` queries.</p><p>The type is a `GraphQL::Schema::Object` class that contains `GraphQL::Schema::Field` that describes the interface for selecting the data, like field name, data type, arguments, and also contain `resolve_proc` or `resolver` that holds the logic for how to resolve the field.</p><pre>def initialize(object, context)<br>  <a href="http://twitter.com/object">@object</a> = object<br>  <a href="http://twitter.com/context">@context</a> = context<br>end</pre><p>A type object instance has an inner object, the type acts like a proxy. When resolving the field, it will first check if the field has a resolver, then check the type has the method same as the field name defined, if not, then delegate the call to the inner object, if the inner object is hash, use hash fetch method instead.</p><p>The object value is the result of the parent field call, or for the root type like `query` or `mutation`, it is specified as `root_value` and passed when executing the query.</p><p>The schema for the example above looks like this:</p><pre>class MySchema &lt; GraphQL::Schema<br>  query QueryRoot<br>end</pre><pre>class QueryRoot &lt; GraphQL::Schema::Object<br>  field :user, UserType, null: true do<br>    argument :id, ID, required: true<br>  end</pre><pre>  # read the root_value and return matched user<br>  def user(id:)<br>    object.find { |u| u[:id] == id }<br>  end<br>end</pre><pre>class User &lt; GraphQL::Schema::Object<br>  field :id, ID, null: false<br>  field :name, String, null: false<br>  field :email, String, null: false<br>  field :cartItems, [CartItemType], null: false<br>end</pre><pre>class CartItem &lt; CartItemType<br>  field :id, ID, null: false<br>  field :name, String, null: false<br>  field :price, Int, null: false<br>end</pre><pre>users = [{<br>  id: &quot;1&quot;,<br>  name: &quot;John Doe&quot;,<br>  email: &quot;<a href="/service/mailto:jd@example.com">jd@example.com</a>&quot;,<br>  cartItems: [{<br>    id: &quot;2&quot;,<br>    name: &quot;Pragmatic graphQL - edition 2&quot;,<br>    price: 60<br>  }]<br>}]</pre><pre>MySchema.execute(query, {<br>  context: {},<br>  root_value: users<br>})<br># =&gt; get the values defined in the example query</pre><p>Each type of object has an attribute called `own_fields`. When we declare `field :name, String, null: false` in type, we add a field instance with the options to the class. The field store the type information and how to resolve the query selection from type. We can get the field instance by `get_field` method.</p><pre>&gt; UserType.fields<br>=&gt; # {&quot;id&quot;=&gt; #&lt;GraphQL::Schema::Field ...&gt;, &quot;name&quot;=&gt; ...}<br>&gt; User.get_field(&quot;name&quot;)<br>=&gt; # &lt;GraphQL::Schema::Field ...&gt;</pre><p>And you can resolve the field by calling the `#resolve` method on field</p><pre>&gt; context = OpenStruct.new({ schema: MySchema })<br>&gt; user = User.send(:new, users.first, context) # skip authorized?<br>&gt; field = User.get_field(&quot;name&quot;)<br>&gt; field.resolve(user, {}, context)<br>=&gt; &quot;John Doe&quot;</pre><p>The `resolve` method will find any resolver class or proc then check the method with field name on type, and fallback to object. If the object is a hash, it will use the field name as a key instead. A simplified version looks like this:</p><pre>def resolve(object, args, ctx)<br>  application_object = object.object<br>  Schmea::Validator.validate!(validators, application_object, ctx, args)</pre><pre>  # check if the field is authorized<br>  if self.authorized?(application_object, args, ctx)<br>    public_send_field(object, args, ctx)<br>  else<br>    ...<br>  end<br>end</pre><pre>def public_send_field(object, args, ctx)<br>  if <a href="http://twitter.com/resolver_class">@resolver_class</a><br>    object = <a href="http://twitter.com/resolver_class">@resolver_class</a>.new(object: object, context: ctx, field: self)<br>  end</pre><pre>if object.respond_to?(<a href="http://twitter.com/method_name">@method_name</a>)<br>    object.public_send(<a href="http://twitter.com/method_name">@method_name</a>, **args)<br>  elsif object.object.is_a?(Hash)<br>    object.object[<a href="http://twitter.com/method_name">@method_name</a>]<br>  elsif object.object.respond_to?(<a href="http://twitter.com/method_name">@method_name</a>)<br>    object.object.public_send(<a href="http://twitter.com/method_name">@method_name</a>, **args)<br>  else<br>    raise &quot;...&quot;<br>  end<br>end</pre><h3>Execute</h3><p>After we understand the structure of schema and query AST, the execute part should just match those 2 together… which I would like to say but it is actually much more complicated than this. Part of this is because there are a lot of cases and features that need to be handled, like multiplex, directives, fragments… etc, but also I wouldn’t say the algorithm is optimized in the execution logic.</p><p>From the entry point: `GraphQL::Schema.execute`, it will trigger the `query_execution_strategy`, which is `GraphQL::Execution::Interpreter` for GraphQL 2.0.</p><p>From here, we call `GraphQL::Execution::Interpreter#evaluate`, it calls `GraphQL::Execution::Interpreter::Runtime#run_eager`, which is the actual class that execute query.</p><p>First, we fetch the root operation type (query, mutation, subscription) and root type, and initialize root type by calling the `authorized_new` method which calls `#authorized?` method on type to make sure the object is accessible.</p><p>After the params and type is set, it gathers the root selections from the query, and resolve the directives by calling `resolve_with_directives`, then gather selections, evaluates the selections by `evaluate_selection_with_args`, It gets the field definition from type, call `field#resolve` with arguments. After the field is resolved, if the result values, then set the result, else continue on the return type and pass the next selections fields on result for iterate. It resolves query as depth search first and merges the result of the fields to GraphQL result.</p><p>With the simplified version, it looks like this (not runnable code, just extract details from [<a href="https://github.com/rmosolgo/graphql-ruby/blob/master/lib/graphql/execution/interpreter/runtime.rb">source</a>] to demonstrate how the execution run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0731d87d7fb190665cfd5efc898a159b/href">https://medium.com/media/0731d87d7fb190665cfd5efc898a159b/href</a></iframe><p>Afterward, the query response will be sent to the client and end the lifecycle.</p><h3>Conclusion</h3><p>Hope this step by steps introduction can help you understand how GraphQL works underhood in general. Creating a DSL for API is a pretty complicated and aggressive idea. But Facebook executes it pretty well and I think more and more GraphQL API will come out and might become the de-facto standard of Web API, just like React. I think we can learn from this and try to find more problems that can be solved by an elegant DSL.</p><p><em>originally from </em><a href="https://neethack.com/2021/11/source-code-odyssey-graphql-ruby/"><em>neethack.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd7b9eff24b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/source-code-odyssey-graphql-ruby-9bd7b9eff24b">Source code odyssey: GraphQL Ruby</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Suspense and Error Boundary]]></title>
            <link>https://medium.com/neethack/react-suspense-and-error-boundary-126002cb37c5?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/126002cb37c5</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 14:01:15 GMT</pubDate>
            <atom:updated>2021-03-26T01:32:01.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pme2Ck0KpISO6CspvscpBg.png" /></figure><p>TLDR: Suspend can catch Promise from children and render fallback until the promise is resolved.</p><p>In React 16.6, React is adding the `Suspense` component that it can render fallback while the app is loading javascript or fetching API. You can see the demonstration from Dan Abramov’s <a href="https://www.youtube.com/watch?v=nLF0n9SACd4">presentation</a> in React conf.</p><p>From the <a href="https://reactjs.org/docs/concurrent-mode-suspense.html">documentation</a> on Reactjs webside, the example below:</p><pre>function ProfilePage({ resource }) {  <br>  return (<br>    &lt;Suspense fallback={&lt;h1&gt;Loading profile...&lt;/h1&gt;}&gt;<br>      &lt;ProfileDetails resource={resource} /&gt;<br>      &lt;Suspense fallback={&lt;h1&gt;Loading posts...&lt;/h1&gt;}&gt;<br>        &lt;ProfileTimeline resource={resource} /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/Suspense&gt;<br>  )<br>}</pre><p>Can render “Loading profile…” while `ProfileDetails` is loading, and “Loading posts…” while `ProfileTimeline` is loading. It can control the timing of render components, skip the children while loading, and avoid race conditions in children. However, it doesn’t just work like magic as the document described. Because for the Suspense component to work, the API needs to follow certain criteria.</p><p>How Suspense work is similar to the ErrorBoundary in React, for example:</p><pre>&lt;ErrorBoundary&gt;<br>  &lt;ProfileDetails resource={resource}/&gt;<br>&lt;/ErrorBoundary&gt;</pre><p>Can catch any errors thrown in the children and skip the render in children. Suspense is similar to ErrorBoundary, But instead of catching the error, it is catching Promise that is thrown from the children, render fallback while the promise is pending, and unblock the children when the promise is resolved.</p><p>To understand how it works, we can take a look at the source code of <a href="https://github.com/facebook/react/blob/master/packages/react/src/ReactLazy.js">React.lazy</a>, React.lazycan work with Suspense, wrapping javascript `import` and trigger Suspense fallback while loading the component:</p><pre>// Create dynamic loading component that trigger Suspense while loading.<br>const LazyComponent = React.lazy(() =&gt; import(&#39;./Component));</pre><pre>&lt;Suspense fallback={&lt;h1&gt;Loading component&lt;/h1&gt;}&gt;<br>  &lt;LazyComponent&gt;<br>&lt;/Suspense&gt;</pre><p>A simplified version of `React.lazy` source code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/079284e605b2fb08f20656662e63e36c/href">https://medium.com/media/079284e605b2fb08f20656662e63e36c/href</a></iframe><p>Therefore for Suspense to work, the API needs to:</p><p>1. Trigger `Promise` that loads the data<br>2. Throw the `Promise` while loading<br>3. Cache the result and return the result when the `Promise` is resolved.</p><h3>Data Fetching</h3><p>Let’s try to implement data fetching to support Suspense. We can reuse the concept in `React.lazy` and replace the `import` with `fetch`</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f5dd9ddffe6b0dd367e6bcee63806f/href">https://medium.com/media/e8f5dd9ddffe6b0dd367e6bcee63806f/href</a></iframe><p>With the `suspenseFetch` function above, we can convert fetch into a suspense compatible API.</p><p><a href="https://github.com/andreiduca/use-async-resource">use-async-resource</a> is a package that can turns fetch into suspense compatible API too, with support for params and fetching the new result. It is a good resource if you want to implement the API with Suspense.</p><h3>Conclusion</h3><p>Suspense is an interesting concept that makes errors and async handling declarative, and it is supported on React level so it will be more stable and easy to handle in the future. However, the Apollo graphql client will not support Suspense API due to the usage of `useRef` does not support throwing promises and errors. But we will see more libraries in React world support Suspense in the future.</p><h3>Reference</h3><p>- <a href="https://itnext.io/what-the-heck-is-this-in-react-suspense-c5e641e487a">https://itnext.io/what-the-heck-is-this-in-react-suspense-c5e641e487a</a><br>- <a href="https://github.com/andreiduca/use-async-resource">https://github.com/andreiduca/use-async-resource</a><br>- <a href="https://dev.to/andreiduca/practical-implementation-of-data-fetching-with-react-suspense-that-you-can-use-today-273m">https://dev.to/andreiduca/practical-implementation-of-data-fetching-with-react-suspense-that-you-can-use-today-273m</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=126002cb37c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/react-suspense-and-error-boundary-126002cb37c5">React Suspense and Error Boundary</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Selenium and Web Driver]]></title>
            <link>https://medium.com/neethack/understand-selenium-and-web-driver-89898e84f63b?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/89898e84f63b</guid>
            <category><![CDATA[webdriver]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[integration-testing]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 03:52:10 GMT</pubDate>
            <atom:updated>2020-12-23T03:52:10.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xUUjDxKm_59zoNLE0dc2A.png" /></figure><p>Integration test, system test, or end to end test in web development are a really helpful tool to make sure the application work as intended. Because it actually simulates a real browser and tests the application just like a real user. It can catch the errors that can not be found in unit tests and it is the most useful tool to make sure the application work. Even though it is more resource consuming than unit tests, the benefit is still over the cost.</p><p>However, most of us only run integration tests and see the browser jumping around magically (or in headless mode). But how does it work under the hood? This article is going to introduce web-driver and selenium — the tools that make integration tests possible — and how they work.</p><h3>Web Driver</h3><p>Web Driver is a remote control interface and protocol created by W3C, supported by various browser vendors. <a href="https://www.w3.org/TR/webdriver/">W3C documentation</a></p><p>For example, <a href="https://chromedriver.chromium.org/">ChromeDriver</a> is the chrome implementation version of the web driver. We can install it on Mac by brew:</p><pre>&gt; brew install chromedriver</pre><p>and run it in terminal:</p><pre>&gt; chromedriver</pre><pre>Starting ChromeDriver 87.0.4280.20 (c99e81631faa0b2a448e658c0dbd8311fb04ddbd-refs/branch-heads/4280@{#355}) on port 9515<br>Only local connections are allowed.<br>Please see <a href="https://chromedriver.chromium.org/security-considerations">https://chromedriver.chromium.org/security-considerations</a> for suggestions on keeping ChromeDriver safe.<br>ChromeDriver was started successfully.</pre><p>You might need to update chrome to match the right version of chromedriver, also might need to <a href="https://stackoverflow.com/questions/60362018/macos-catalinav-10-15-3-error-chromedriver-cannot-be-opened-because-the-de">authorize</a> if you are using Mac</p><p>`chromedriver` will start a HTTP server process, from w3c documentation we can see the web driver interact user with http, for example, if we want to start a browser process, we can send a HTTP request to chromedriver:</p><pre>&gt; curl -XPOST <a href="http://localhost:9515/session">http://localhost:9515/session</a> \<br>-H “Content-Type: application/json” \<br>-d ‘{ “capabilities”: { “browserName”: “chrome” } }’</pre><pre>{“value”:{“capabilities”:{“acceptInsecureCerts”:false,”browserName”:”chrome”,”browserVersion”:”87.0.4280.67&quot;,”chrome”:{“chromedriverVersion”:”87.0.4280.20 (c99e81631faa0b2a448e658c0dbd8311fb04ddbd-refs/branch-heads/4280@{#355})”,”userDataDir”:”/var/folders/dh/nrc_gcpx3s19gs1t479jhj180000gn/T/.com.google.Chrome.Immsr4&quot;},”goog:chromeOptions”:{“debuggerAddress”:”localhost:57462&quot;},”networkConnectionEnabled”:false,”pageLoadStrategy”:”normal”,”platformName”:”mac os x”,”proxy”:{},”setWindowRect”:true,”strictFileInteractability”:false,”timeouts”:{“implicit”:0,”pageLoad”:300000,”script”:30000},”unhandledPromptBehavior”:”dismiss and notify”,”webauthn:virtualAuthenticators”:true},”sessionId”:”a836dcb9e2b3b664f58b3c12f8341538&quot;}}%</pre><p>Then magically, you can see a browser page opened on your machine. The return value from http request has a session id, we can use this id to further interact with the page:</p><pre>// open google<br>curl -XPOST <a href="http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/url">http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/url</a> \<br>-H “Content-Type: application/json” \<br>-d ‘{ “url”: “<a href="https://www.google.com/">https://www.google.com</a>&quot;}&#39;</pre><pre>// find input element<br>curl -XPOST <a href="http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/element">http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/element</a> \<br>-H “Content-Type: application/json” \<br>-d ‘{ “using”: “css selector”, “value”: “input[name=q]”}’</pre><pre>// enter text and submit search<br>curl -XPOST <a href="http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/element/2292f1cb-a478-40dc-9de0-00ce0019a212/value">http://localhost:9515/session/a836dcb9e2b3b664f58b3c12f8341538/element/2292f1cb-a478-40dc-9de0-00ce0019a212/value</a> \<br>-H “Content-Type: application/json” \<br>-d ‘{ “type”: “keyDown”, “text”: “webdriver and selenium\n”}’</pre><p>So we can do almost all the interactions that we can do on browser through HTTP requests, like filling up the form, resize window, dismiss alert, or even execute scripts. It is a really powerful tool that enables integration tests and even power bots.</p><h3>Selenium</h3><p>But purely interact with web driver through HTTP requests is kind of cumbersome. So <a href="https://github.com/SeleniumHQ/selenium">Selenium</a> is created to make access web driver easier. Selenium is an open source library that wraps the web driver API into an easy to use interface. You can create a session, find elements, and interact without consider the web driver implementation.</p><p>In this case, I am using the Ruby version of Selenium, in the source code it includes couple of objects that wrap the web driver:</p><ul><li>Service: find executable and run `webdriver` in the background</li><li>Bridge: sending HTTP requests to webdriver</li><li>Driver: main interface that sending commands to browser through bridge.</li><li>Element: interface for manipulating DOM element, ex: click, submit</li></ul><p>For example, we can rewrite the previous bash example with Selenium:</p><pre># create driver<br>driver = Selenium::WebDriver.for(:chrome)</pre><pre># start browser and navigate to URL<br>driver.navigate.to(“<a href="https://www.google.com/">https://www.google.com</a>&quot;)</pre><pre># find input, enter search text and submit search<br>element = driver.find_element(“css”, “input[name=q]”)<br>element.send_keys(“test”)<br>element.submit</pre><p>Isn’t this much simpler? At the bottom, it is still using the webdriver but provides a better interface and hides the complexity of settings, session id, and element id. Make writing web crawler and integration tests much easier.</p><h3>Capybara</h3><p>Capybara is a framework for running integration test on Ruby, it wraps selenium webdriver and Rack app together, and provide a set of DSL methods.</p><p>For example, you can start a Capybara session with App by</p><pre>session = Capybara::Session.new(:selenium, MyRackApp)</pre><p>And run interaction with</p><pre>session.visit(“/home”)</pre><pre>element = session.find(“input[type=submit]”)<br>element.click</pre><p>Compare to selenium, it provides a higher level abstraction with DSL and simplify settings, so it looks good when writing integration test like:</p><pre>it “visit the page and do search” do<br>  visit “/home”<br>  within “#content” do<br>  fill_in “input[type=text]”, with: “test”<br>  click_button(“input[type=submit]”)<br>  end<br>end</pre><p>The DSL methods basically forward the calls to `Capybara.current_session` which contains the current selenium session and app. It’s also possible to use Capybara directly without Rack app, it feels more straightforward to manipulate the page with Capybara DSL, but essentially it’s the same and Selenium will be easier to understand with Webdriver documentation.</p><h3>Conclusion</h3><p>After understand how Selenium and Capybara interact with browser, it helps me debug browser test issue and enables more possible for me to write the crawler to automate some daily tasks. I hope this article can help you write automated tests and tasks with web driver too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89898e84f63b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/understand-selenium-and-web-driver-89898e84f63b">Understand Selenium and Web Driver</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announce apollo-reactive-store]]></title>
            <link>https://medium.com/neethack/announce-apollo-reactive-store-78bee81b37f5?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/78bee81b37f5</guid>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 04:40:09 GMT</pubDate>
            <atom:updated>2020-11-23T04:40:09.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*j1VUBCgekAKCWNR769NqZA.png" /></figure><p>State management in frontend is always a problem. Unlike backend, the state in frontend world is pretty fragmented. Not only the local state at each component, the remote state from API, also the global state that is shared in multiple components. There is always a dilemma in react that, we want to make the component as simple as pure function and only rely on props, but passing every prop down several levels makes the props list pretty big and complicated. Another problem is how to manage data from API, do we need to put data into the global state? or we only use it locally for a component? For solving those problems, state management libraries try to pushing for different solutions:</p><ul><li>Redux (<a href="https://redux.js.org/">https://redux.js.org/</a>)<br>Redux is the most popular approach that follows a single directional data flow and pure functional solution. But in the tradeoff, it brings multiple concepts to include actions, reducers, dispatch, and selectors into the app. Can often make creating simple interaction complicate, if the user wants to manage every state into Redux as the framework suggested.</li><li>Mobx (<a href="https://mobx.js.org/">https://mobx.js.org/</a>)<br>Mobx is on another side of the spectrum, which follow object-oriented and not opinionated. Users are free to create objects and subscribe to them in the react component. But the trade-off is no single data flow, and hard to understand because the code has less structure.</li><li>Recoil (<a href="https://recoiljs.org/">https://recoiljs.org/</a>)<br>Recoil is an experimental framework for managing the global state, but a promising one. It acts as an extension of useState but depends on the atom key to share it globally. And provide a selector to create derived and handle remote state. It will be a good fit for smaller applications compare to Redux.</li><li>Zustand (<a href="https://zustand.surge.sh/">https://zustand.surge.sh/</a>)<br>Zustand is a pretty elegant and simple state management library. It provides a single store combine with methods to modify, set state, and hooks for react, without complicated settings like redux and also highly efficient.</li></ul><h4>Apollo and Reactive var</h4><p>Recently in Apollo client 3, it introduces another option for state management, which is to manage the state in Apollo cache and read by graphql query. It’s called “<a href="https://www.apollographql.com/docs/react/local-state/reactive-variables/">Reactive Var</a>”. There are several reasons to manage state in apollo cache:</p><ul><li>It makes Graphql query the source of truth, so the app only needs to rely on `useQuery` as the endpoint of the external state.</li><li>Graphql already caches the query response in Apollo cache, so it unifies remote and global states together.</li></ul><p>However, before Apollo 3, users have to use `writeQuery` API with the graphql query to write state into Apollo cache, which is pretty complicated. Reactive Var simplifies how to integrate state into Apollo cache.</p><p>About how ReactiveVar works, we can check the <a href="https://github.com/apollographql/apollo-client/blob/a975320528d314a1b7eba131b97d045d940596d7/src/cache/inmemory/reactiveVars.ts">source code</a> for more details. When we read a reactive var from the query, it read the current value in reactiveVar and store the current cache slot. And when the value is updated, it will broadcast caches that the value has been updated, and the cache will notify the subscriber to update.</p><h4>Apollo Reactive Store</h4><p>ReactiveVar provides a way to manage the state in apollo cache. But it still has a couple of problems that it is hard to use, update, and manage those vars. Therefore I created a package to manage reactiveVar with a simple and easy to use API:</p><pre>// create store<br>const store = create({<br>  counter: 1,<br>});</pre><pre>// initialize in apollo client<br>const client = new ApolloClient({<br>  uri: &quot;API_URL&quot;,<br>  cache: new InMemoryCache({<br>    typePolicies: store.getTypePolicies()<br>  })<br>});</pre><pre>// use it in component<br>function App() {<br>  const { loading, error, data } = useQuery(gql`<br>    query {<br>      counter<br>    }<br>  `, { client });</pre><pre>if (loading || error) { return null }</pre><pre>const { counter } = data;</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{counter}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; store.update(&quot;counter&quot;, counter + 1)}&gt;+1&lt;/button&gt;<br>      &lt;button onClick={() =&gt; store.update(&quot;counter&quot;, counter - 1)}&gt;-1&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>With this interface, we can see the state and query with Graphql. When updating we can use the store instead of reactiveVar, so it’s possible to manage multiple reactive var at the same time.</p><p>Using reactive var can make managing state the same as query data from API. However, it also brings some confusion about how the state is managed:</p><p>- No type and schema declarations for reactive var.<br>- On testing, it will confuse with `MockedProvider`, since the updating store will not reflect on MockedProvider in this case.<br>- For applications with a large amount of states, it might be hard to manage everything in one store.</p><p>Those problems will be tackled in the future versions, and welcome any pull request to improve the library:</p><ul><li><a href="https://github.com/rafe/apollo-reactive-store">Apollo Reactive Store</a></li></ul><p>Original from <a href="http://neethack.com/2020/11/apollo-reactive-store/">Neethack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bee81b37f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/announce-apollo-reactive-store-78bee81b37f5">Announce apollo-reactive-store</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstractions and Essential Complexity]]></title>
            <link>https://medium.com/neethack/abstractions-and-essential-complexity-2af7e46a1453?source=rss----51941ecd316e---4</link>
            <guid isPermaLink="false">https://medium.com/p/2af7e46a1453</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jimmy Chao]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 04:35:21 GMT</pubDate>
            <atom:updated>2023-11-27T14:54:40.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*BCqmoAAj34JhKRgt_k-DbA.png" /></figure><blockquote>TLDR: Inline abstractions and simplify logic to write better code.</blockquote><p>Programmer’s work today is based on different levels of abstractions in the form of APIs and modules, they hide large amounts of implementation details so we can build features and products without understanding every detail. However, abstractions also increase the complexity of our code. Lots of time I struggle with overly complex code and try to fix those pieces by removing unnecessary abstractions. But how can we tell whether the abstraction is good or bad? How much abstraction in the code is too much? This article will be focusing on some of my views about abstraction and complexity in programming.</p><h4>Power of abstraction</h4><p>Abstraction is the building block of programmers today, it frees the programmer from massive details of complexity, without it we will still be writing machine code, for example:</p><p>- Python and Ruby is an abstraction layer running on C interpreter<br>- C is a layer on instruction set.<br>- Rails provide multiple abstraction layers like MVC (model-view-controller), ORM (ActiveRecord, object-relation mapping)<br>- React hide DOM updates into declarative components and state.</p><p>In those examples, the abstractions provide a huge benefit by encapsulating details and providing a high-level syntax or API to let people understand and use them.</p><h4>Essential and accidental complexity</h4><p>Although abstraction is a really powerful tool, it also has its limitation.</p><p>In the paper “<a href="http://worrydream.com/refs/Brooks-NoSilverBullet.pdf">No Silver Bullet</a>&quot;, it defines the software complexity into 2 parts. Essential complexity and accidental complexity.</p><p>Essential complexity is the complexity inherent in the problem domain. Including the mutation of state, condition, the order of procedure, and messaging. All other complexities from the language, framework, or stack are accidental. The line between those 2 complexities might vary, but basically, you can solve the problem with different languages, and different frameworks, but the essential — the algorithm and logic to solve the problem — can not be reduced. For example, you can write the quicksort in C, python, Haskell, or even pseudo-code. The essential complexity of quicksort still stays the same. Therefore no matter how much the technology of tooling improves, there is still no silver bullet to solve the essential complexity issue to increase the productivity of programmers.</p><h4>Problem of abstraction</h4><p>Abstraction is a useful tool to reduce accidental complexity, but it also has several drawbacks:</p><p>1. It can not reduce essential complexity.</p><p>Although abstraction can largely reduce accidental complexity, make the code closer to the problem domain by providing higher-level syntax and API. However, the problem domain still inherits the complexity from the real world. Abstraction can not make it simpler.</p><p>2. It increases accidental complexity.</p><p>This is a tricky part because abstraction is not essential for solving the problem. Any extra abstractions are increasing accidental complexity. But then how does the abstraction decrease complexity? By enough usage of it. A higher-level abstraction can represent multiple lower-level concepts together. So with more usage, it can encapsulate more details and make the code focus on essential complexity but not accidental. So with the growth of the problem domain, the complexity of abstraction will grow like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kJW4-1s2VhLe0yZTKlPVg.png" /></figure><p>At the beginning of the graph, it will increase more complexity. For example, we can create the acronym “ECAC” to represent those 2 types of complexity. If I only use this acronym once in this post, it only makes this more complicated because the acronym is not essential. However, if this article got widely accepted, we might be able to call our colleague “you should look at the ECAC for your code” Then it makes the conversation simpler.</p><p>3. It might be wrong or misleading.</p><p>Abstractions are not essential, so in the worst case, they might not be correct and misleading. This graph shows how complexity grows with wrong abstractions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuzHg3NgDyBQEd9u47q-ow.png" /></figure><p>If an abstraction does not have enough usage to cover the extra complexity introduced. It only makes the code more complicated. Or the abstraction might not be able to successfully hide lower-level details, and users even have to bypass the abstraction. Both of those cases make the abstraction increase accidental complexity rather than decrease it.</p><h3>Reduce complexity</h3><p>Then how can we properly reduce the complexity of our code? Here’s a couple of suggestions:</p><p>1. Make reducing essential complexity the priority</p><p>Because, unlike abstractions, a better algorithm is basically, better.</p><p>The way I use to estimate is by inline most of the abstractions in our problem domain to see procedures, conditions, messaging, and state mutations. And try to make those steps simpler, like removing redundant steps, changing the order to remove conditions, and removing unnecessary states.</p><p>2. Always evaluate multiple solutions</p><p>Sometimes it is really hard to evaluate whether the changes are worth it or not, Therefore evaluating multiple solutions is a good guideline. We can find what is essential in different solutions, And follow Occam’s Razor principle: the simplest solution usually is the best solution.</p><p>3. Reorganize, inline, and rename code</p><p>With those methods, we can reduce extra abstractions and reduce accidental complexity, and also help you understand the logic and find a better algorithm.</p><p>4. Rule of three</p><p>A basic rule to introduce abstraction is to wait until you have 3 usages. It might vary but that is the least case for the abstraction to be useful.</p><h3>Example</h3><p>Here I am going to reuse the example in Sandi Matz’s talk: <a href="https://youtu.be/XXi_FBrZQiU">Polly want a message</a>, In this talk, Sandi explains how object-oriented and abstraction can simplify a project that read a file and print line numbers, here is the source:</p><pre>class Listing<br>  attr_reader :filename, :line_numbers, :left_just, :repository, :tag, :git<br><br>  def initialize(filename:, line_numbers: nil, left_just: nil, repository: nil, tag: nil, git_cmd: nil)<br>    @filename = filename<br>    @line_numbers = line_numbers<br>    @repository = repository<br>    @left_just = left_just<br>    @tag = tag<br>    @git_cmd = git_cmd<br>  end<br><br>  def lines<br>    all_lines = if git_cmd<br>                  git_lines<br>                else<br>                  file_lines<br>                end<br>    subset = if line_numbers<br>               lines_to_print(all_lines)<br>             else<br>               all_lines<br>             end<br>    if left_just<br>      return justify(subset)<br>    end<br>    subset<br>  end<br><br>  private<br><br>  def git_lines<br>    git_cmd.repository = repository<br>    git_cmd.tagname = tag<br>    git_cmd.filename = filename<br>    git_cmd.show.split(&quot;\n&quot;)<br>  end<br><br>  def file_lines<br>    File.read(filename).split(&quot;\n&quot;)<br>  end<br><br>  def lines_to_print(all_lines)<br>    specs = line_numbers.gsub(/[&#39;|&#39;]/, &#39;&#39;).gsub(/ /, &#39;&#39;).split(&#39;,&#39;)<br>    specs.collect do |spec|<br>      if spec.include?(&#39;#&#39;)<br>        num_spaces = spec.delete(&#39;#&#39;).to_i<br>        (&#39; &#39; * num_spaces) + &#39;# ...&#39;<br>      else<br>        edges = spec.split(&#39;-&#39;).collect(&amp;:to_i)<br>        individual_numbers = (edges.min.to_i..edges.max.to_i).to_a<br>        individual_numbers.collect { |i| all_lines[i - 1] }.compact<br>      end<br>    end.flatten.compact<br>  end<br><br>  def justify(lines)<br>    lines.map { |line| line.slice(num_leading_space_to_remove(lines)..-1) || &#39;&#39; }<br>  end<br><br>  def num_leading_space_to_remove(lines)<br>    @num ||= <br>      lines.reduce(999_999) { |current_min, line|<br>        line.empty? ? current_min : [current_min, num_leading_spaces(line)].min<br>      }<br>  end<br><br>  def num_leading_spaces(line)<br>    line[/\A */].size<br>  end<br>end<br><br>class GitCmd<br>  attr_accessor :repository, :tagname, :filename<br><br>  def show<br>    `git #{git_dir} show #{tagname}:#{filename}`<br>  end<br><br>  private<br><br>  def git_dir<br>    %(--git-dir=&quot;#{repository}&quot;)<br>  end<br>end</pre><p>And Sandi shows how to use object-oriented to refactor the previous source, I will ignore the progress and only show the result here. It is to better follow the talk for details:</p><pre>class Listing<br>  attr_reader :source, :subsetter, :justifier<br><br>  def initialize(source:, subsetter:, justifier:)<br>    @source = source<br>    @subsetter = subsetter<br>    @justifier = justifier<br>  end<br><br>  def lines<br>    justifier.justify(subsetter.lines(source.lines))<br>  end<br>end<br><br>module Source<br>  class File<br>    attr_reader :filename<br><br>    def initialize(filename:)<br>      @filename = filename<br>    end<br><br>    def lines<br>      ::File.read(filename).split(&quot;\n&quot;)<br>    end<br>  end<br><br>  class GitTag<br>    def self.git_cmd<br>      GitCmd.new<br>    end<br><br>    attr_reader :filename, :tagname, :repository, :git_cmd<br><br>    def initialize(filename:, repository:, tag:, git_cmd: self.class.git_cmd)<br>      @git_cmd = git_cmd<br>      git_cmd.repository = repository<br>      git_cmd.tagname = tag<br>      git_cmd.filename = filename<br>    end<br><br>    def lines<br>      git_cmd.show.split(&quot;\n&quot;)<br>    end<br>  end<br><br>  class GitCmd<br>    attr_accessor :repository, :tagname, :filename<br><br>    def show<br>      `git #{git_dir} show #{tagname}:#{filename}`<br>    end<br><br>    def git_dir<br>      %Q[--git-dir=&quot;#{repository}&quot;]<br>    end<br>  end<br>end<br><br>module Subset<br>  class Everything<br>    def lines(everything)<br>      everything<br>    end<br>  end<br><br>  class LineNumber<br>    attr_reader :line_numbers<br><br>    def initialize(line_numbers:)<br>      @line_numbers = line_numbers<br>    end<br><br>    def lines(possibilities)<br>      clump_specs.collect { |spec| clump_for(spec, possibilities) }.flatten.compact<br>    end<br><br>    def clump_specs<br>      line_numbers.gsub(/[&#39;|&#39;]/, &#39;&#39;).gsub(/ /, &#39;&#39;).split(&#39;,&#39;)<br>    end<br><br>    def clump_for(spec, possibilities)<br>      Clump.lines(spec: spec, possibilties: possibilities)<br>    end<br>  end<br>end<br><br>class Clump<br>  def self.lines(spec:, possibilities: [])<br>    self.for(spec: spec, possibilities: possibilities).lines<br>  end<br><br>  def self.for(spec:, possibilities: [])<br>    if spec.include?(&#39;#&#39;)<br>      Clump::Comment<br>    else<br>      Clump::LineNumber<br>    end.new(spec: spec, input: possibilities)<br>  end<br><br>  attr_reader :spec, :input<br><br>  def initialize(spec:, input: [])<br>    @spec = spec<br>    @input = input<br>  end<br><br>  class LineNumber &lt; Clump<br>    def lines<br>      expand_clump(spec).contact { |i| input[i - 1] }.compact<br>    end<br><br>    def expand_clump(spec)<br>      edges = spec.split(&#39;-&#39;).collect(&amp;:to_i)<br>      (edges.min.to_i..edges.max.to_i).to_a<br>    end<br>  end<br><br>  class Comment &lt; Clump<br>    def lines<br>      num_spaces = spec.delete(&#39;#&#39;).to_i<br>      (&#39; &#39; * num_spaces) + &#39;# ...&#39;<br>    end<br>  end<br>end<br><br>module Justification<br>  class None<br>    def self.justify(lines)<br>      lines<br>    end<br>  end<br><br>  class BlockLeft<br>    def self.justify(lines)<br>      new(lines).justify<br>    end<br><br>    attr_reader :lines<br><br>    def initialize(lines)<br>      @lines = lines<br>    end<br><br>    def justify<br>      lines.map { |line| line.slice(num_leading_space_to_remove(lines)..-1) || &#39;&#39; }<br>    end<br><br>    private<br><br>    def num_leading_space_to_remove(lines)<br>      @num_leading_space_to_remove ||= lines.reduce(999_999) do |current_min, line|<br>        line.empty? ? current_min : [current_min, num_leading_spaces(line)].min<br>      end<br>    end<br><br>    def num_leading_spaces(line)<br>      line[/\A */].size<br>    end<br>  end<br>end</pre><p>Comparing those 2 versions, I think people have different opinions about them. Some say the object-oriented version is way more complicated than the original one. Others say it provides more flexibility and encapsulates complex logic in objects. But how do we know which way is better? Here comes the essential complexity. When we compare the original code and refactored code. They are essentially doing the same things, with no duplicated code removed from refactoring, but only introducing more abstractions, which increase accidental complexity. So these refactor make the code more complicated in exchange for object-oriented and flexibility, but the goal of refactoring is not to make the code more object-oriented, but to reduce complexity, therefore this refactor is a failure from the complexity standpoint.</p><p>But from the standpoint of object-oriented, it is better because it fits all perspectives of object-oriented. Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependency Injection. But object-oriented is a programming method, not the goal of programming. Refactor to code like this is mistaking the methodology as a goal. And it will seem like a great refactor (done by top OO consultant!) until the next person comes in to try to modify this mud of objects.</p><p>So what is the alternative if refactoring into abstractions only makes things more complicated? Leave the code as it is?</p><p>The answer is no, we can still improve the original code, but instead of thinking in objects, we have to think in algorithms and logic. We need to find places to reduce essential and accidental complexity. First, we need to find what is the problem in the original code? I think there are a couple of candidates for refactoring:</p><p>1. Setup git_cmd object is not necessary.<br>2. Naming is confusing in `lines_to_print`, it introduced specs, edges, individual numbers. Those variable names introduce more confusion about what they are doing.<br>3. Algorithm for justifying space is bad, it runs `reduce` with a large number which can be avoided by calling #min.</p><p>So let’s try to solve them one by one</p><p>- For the git_cmd, we can easily inline it as a method<br>- For the lines_to_print, we can rename specs to parsed_line_numbers, edges to range<br>- For justify spaces, we can use `min` instead of calling `reduce`<br>- we can move the conditions into methods to make the workflow looks better</p><p>So the refactored version is:</p><pre>class Listing<br>  attr_reader :filename, :line_numbers, :left_just, :repository, :tag, :git<br><br>  def initialize(filename:, line_numbers: nil, left_just: nil, repository: nil, tag: nil, git: false)<br>    @filename = filename<br>    @line_numbers = line_numbers<br>    @repository = repository<br>    @left_just = left_just<br>    @tag = tag<br>    @git = git<br>  end<br><br>  def lines<br>    justify_spaces(lines_to_print(read_lines))<br>  end<br><br>  private<br><br>  def read_lines<br>    if git<br>      `git --git-dir=#{repository} show #{tag}:#{filename}`<br>    else<br>      File.read(filename)<br>    end.split(&quot;\n&quot;)<br>  end<br><br>  def lines_to_print(lines)<br>    return all_lines unless line_numbers<br>    parsed_line_numbers = line_numbers.gsub(&#39; &#39;, &#39;&#39;).split(&#39;,&#39;)<br>    parsed_line_numbers.collect do |line_number|<br>      if line_number.include?(&#39;#&#39;)<br>        spaces = &#39; &#39; * line_number.delete(&#39;#&#39;).to_i<br>        &quot;#{spaces}# ...&quot;<br>      else<br>        range = line_number.split(&#39;-&#39;).collect { |n| n.to_i - 1 }<br>        all_lines.slice(*range)<br>      end<br>    end.flatten.compact<br>  end<br><br>  def justify_spaces(all_lines)<br>    return all_lines unless just_left<br>    leading_spaces_to_remove = all_lines.reject(&amp;:empty?).min do |line|<br>      line[/\A */].size<br>    end<br>    all_lines.map do |line|<br>      line.slice(leading_spaces_to_remove..-1)<br>    end<br>  end<br>end</pre><p>Generally, I think this version is better than the previous two versions. But how do we know which one is better? After all, this refactor doesn’t change code much, it is still doing a lot of things in one object, and doesn’t fit the SOLID principle. but compared to the original code, the essential and accidental complexity both decreased, mainly by improving justifying the logic and some minor improvement for `lines_to_print` and `read_lines`. Make the program size from 86 lines to 53 lines. So if we want to introduce abstractions at this point, the code will still be simpler. We can of course introduce more abstractions, but abstractions also increase accidental complexity, `read_lines`, `lines_to_print` and `justify_spaces` can all be extracted to separate modules, but without any usage, those abstractions can not reduce complexity, therefore it is better to wait until there are other usages in the codebase.</p><h3>Conclusion</h3><p>When writing code, we need to carefully estimate the essential complexity and accidental complexity, and understand the goal is to reduce them, but not implement any patterns or abstractions themselves. When we see the opportunity to introduce abstractions, start from a simple one and make sure there are enough usages. Also, be ready to remove it when it becomes unnecessary. Last but not least figure out how to reduce essential complexity and replace it with a better algorithm to solve the problem domain.</p><h4>References</h4><ul><li><a href="https://medium.com/ni-tech-talk/caught-in-a-bad-abstraction-55bfe6634b83">https://medium.com/ni-tech-talk/caught-in-a-bad-abstraction-55bfe6634b83</a><br>- <a href="https://en.wikipedia.org/wiki/Essential_complexity">https://en.wikipedia.org/wiki/Essential_complexity</a><br>- <a href="http://worrydream.com/refs/Brooks-NoSilverBullet.pdf">http://worrydream.com/refs/Brooks-NoSilverBullet.pdf</a><br>- <a href="https://www.youtube.com/watch?v=IRTfhkiAqPw">https://www.youtube.com/watch?v=IRTfhkiAqPw</a> object oriented programming is embarrassing<br>- <a href="https://www.youtube.com/watch?v=vG8WpLr6y_U&amp;list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&amp;index=16">https://www.youtube.com/watch?v=vG8WpLr6y_U&amp;list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&amp;index=16</a> lets program like it’s 1999 <br>- <a href="http://blog.spinthemoose.com/2012/12/17/solid-as-an-antipattern/">http://blog.spinthemoose.com/2012/12/17/solid-as-an-antipattern/</a><br>- <a href="https://speakerdeck.com/tastapod/why-every-element-of-solid-is-wrong">https://speakerdeck.com/tastapod/why-every-element-of-solid-is-wrong</a></li></ul><p><em>originally from </em><a href="https://neethack.com/"><em>neethack.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af7e46a1453" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neethack/abstractions-and-essential-complexity-2af7e46a1453">Abstractions and Essential Complexity</a> was originally published in <a href="https://medium.com/neethack">Neethack</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>