Smells in React Apps

Recognizing code smells is an important skill that helps you build maintainable software.

This talk is about code and design smells in React applications, based on the experience working in a 2-year-old project with more than 900 components.

Presented at JSConf.Asia 2018

Slideshttps://speakerdeck.com/dtinth/smells-in-react-apps

Slides (with edited transcript)https://speakerdeck.com/dtinth/smells-in-react-apps-with-edited-transcript

Transcript

[00:00] Opening

Sawasdee krub! Good afternoon, everyone. This is my first time giving a full-length talk at a JSConf — a conference outside of Thailand.

First, I'm really grateful to the organizers for having invited me here. The past two days were really awesome, and I'm really excited for today. So let's begin.

[00:46] Code smells and three books

Today I'm going to talk about smells in React apps.

When you talk about code smells, there are several books that talk about code smells and design smells as well. Unfortunately, I don't read many books, so I usually read the articles on the internet and piece them together. These three books — I haven't read them yet.

Slide listing three books about code smells

[01:00] The three books on the slide: Refactoring: Improving the Design of Existing Code, Clean Code: A Handbook of Agile Software Craftsmanship, and Agile Software Development, Principles, Patterns, and Practices.

The contents that I'm going to present today are mainly based on my experience, so maybe they are not perfectly aligned with those books, and maybe I use different terms than them, but I really hope they will be useful to you.

[01:31] About me

My name is Thai, and I come from Thailand — I'm a Thai person.

About me slide: Thai Pangsakulyanont, @dtinth

[01:35] About me: Thai Pangsakulyanont (@dtinth).

This is my Twitter ID, @dtinth. If you have any feedback about this talk, please tweet it to me — I would really appreciate it. You can also find me on GitHub as well. With that said, let's start.

[01:59] Building software for fun

I really like to build software for fun, just like Tim Holman said in his previous talk. In my free time I really like to work on side projects. This is one:

Slide showing dtinth/midi-instruments, a web-based musical instrument

[02:12] dtinth/midi-instruments — web-based musical instruments.

This one is a web-based musical instrument, and there are several instruments you can choose from. I demoed it in a lightning talk at JSConf Asia 2016.

Sometimes I feel like doing something a bit silly, so here I created a Windows 2000 theme for the Atom text editor:

Slide showing dtinth/atom-aesthetic-ui, a Windows 2000 theme for Atom

[02:25] dtinth/atom-aesthetic-ui — a Windows 2000 theme for the Atom text editor.

The main challenge here was to replicate the tree view in Windows in a pixel-perfect way, using just CSS, so this was really fun.

Other times I want to play a music game like a DJ, so I need a turntable. I put a phone in a dish and let it send the gyroscope signal to the game:

Slide showing the Gyroscratch project: a phone in a dish used as a turntable

[02:55] Gyroscratch — dtinth/GyroscratchAndroid and bemusic/gyroscratch-web.

[03:06] 7,000 lines of untestable code

That's some of my projects. For me, the fun part is really important, because that makes coding a fulfilling thing to do and makes it feel good. And coding as a hobby also improves my professional coding skills.

I'm also really interested in how to make software maintainable. In one of my old projects, about 10 years ago, I put a lot of effort into developing it, but at that time I didn't know about software engineering stuff. I kept on coding and coding and coding, and over time it became less maintainable, until we had 7,000 lines of untestable code.

At that point, when I did something or fixed something, another bug appeared. You remember the last demo — the bug simulator? So now maintaining it was not fun. Later I learned about software engineering, so I felt like I wanted to improve the codebase and add tests, but I had 7,000 lines of untestable code, so that was also not fun.

A side project, I think, should be fun — not a burden and this huge boring task. So I started to feel that I'd rather do something else, and the development of that project stopped. That's sad, because I spent years working on it.

What I learned here is that sustainability really matters. So now, when I work on a new project, I have to make sure that it will not end up like that one.

[04:36] Many paths to maintainability

That's why I'm really interested in this stuff. As you know, there are so many contributing factors and so many techniques you can use to make software maintainable.

Slide listing maintainability techniques: object-oriented analysis and design, clean architecture, functional programming, automated testing, continuous integration, linting, type systems, modularization, componentization, code smells

[04:52] Some of the techniques for maintainability: object-oriented analysis and design, clean architecture, functional programming, automated testing, continuous integration, linting, type systems, modularization, componentization, code smells, …

[05:00] Bemuse (2014): setting up for maintainability

In 2014, I started working on a new project, and it's called bemuse. It is a web-based, open-source music game using HTML5 technologies.

Slide showing gameplay of bemusic/bemuse, a web-based music game

[05:05] bemusic/bemuse — a web-based, open-source music game.

I have the game with me as well, so if you want to try a demo, you can approach me. I want to make it great — I want people to play this game — so I need to make sure that this project is maintainable. I organized my code into modules and used Webpack to bundle them together. I set up ESLint to catch common errors and enforce a consistent coding style. I set up unit testing, continuous integration and deployment, and I track my code coverage.

Slide showing the bemuse source tree organized into modules, bundled with webpack

[05:30] The bemuse codebase organized into modules and bundled with Webpack.

That took me three weeks to set up. I just spent three weeks setting up the project without doing any game development. That sounds pretty long compared to other projects, but the result is that it made a huge impact.

The unit tests helped me switch from one library to the other without fear that I would break the game. A decoupled architecture allowed me to try out different view libraries — I tried two times without having to rewrite the whole app. And putting implementation details behind an interface lets me switch to a new backend service without having to make a sweeping change across the whole codebase. Also, some features I can prototype in one night.

In that project I learned that a good codebase is like a clean table, where I can experiment quickly and prototype new ideas right away without having to first move so much stuff that's getting in my way. After I implement the idea, if the experiment was successful, I try to refactor the codebase to be clean again, ready for more experiments to come in the future. I've been maintaining this for about three years now, and I'm still maintaining it.

[07:05] Taskworld (2018): React and Redux at scale

Now I'm working as a frontend architect at Taskworld. Our app is based on React and Redux. We have many features. This is our tree view, and this is just the Redux store.

Stage screen showing the Taskworld Redux store tree and 900+ React components; over 2 years, 20+ engineers worked on it

[07:32] The Taskworld app: the Redux store, 900+ components — over 2 years, 20+ engineers worked on it.

We have more than 900 components, and over two years, more than twenty engineers have worked on it. It is a challenge for us to keep innovating new features and at the same time make sure the code is maintainable. We have to strike a healthy balance between minimizing technical debt and shortening the time to market. Pretty challenging.

[07:48] Communication: a hack behind an interface

As I said, there are many contributing factors to maintainability, but the things that I've listed here are technical stuff. When I worked in a team, I learned that the most important thing really is communication.

You're going to see a lot of code starting from this slide, so let's see an example now. I created a module called MusicPreviewer, and it exports five functions.

Slide showing the MusicPreviewer module exporting five functions: preload, enable, disable, go, preview

[08:16] The MusicPreviewer module exports five functions; each delegates to getInstance().

The rest of the app only needs to know about these five functions to use it. They don't need to know that behind the interface of those five functions lies a big, complicated, ugly hack.

Slide showing the complicated implementation code of createMusicPreviewer

[08:35] The complicated hack behind the interface — nested loops, ifs, and try/catch blocks.

You can see a for inside an if, and an if inside an if inside a for in here. And there's a catch block inside a try inside an if in another if in the for.

In principle this would work fine, because the code stays behind the interface and other parts of the software are not affected by it. But in practice, another developer may be looking for a technical solution and stumble upon my hack. Since I didn't clearly communicate that the code they are seeing is a hack, it got duplicated.

So it's really important to communicate with other developers: when you're writing code, you have to communicate why you're doing it, and whether it is the best practice — whether it is the way other people should take as an example.

Another important factor is having effective code reviews. And to do effective code reviews, in my opinion, we should learn to recognize smells inside our code. And this is what I'm going to talk about today.

[09:41] Smell #1: Information leaks

The first kind of smell I call it information leaks.

Slide reading: Information leaks

[09:46] Smell #1: “Information leaks”.

Let's see another example. In our project we have a standard user interface toolkit which contains the components that are used across the app. One of them is the UserAvatar component. We can use this component to render a user's avatar by specifying the image and the size. We have three sizes to choose from: small, medium, and large. Maybe that's a bit too large. Okay.

Slide showing UserAvatar rendered with size small, medium, and large

[10:15] <UserAvatar> with size='small', 'medium', and 'large'.

Later, as we develop our app, we need to implement new features, so the code changes over time. We have to implement the messaging system, and we got the design — this is how a message should look like. On the left we have the avatar; on the right, some text. This should be straightforward.

Slide announcing a new feature: the messaging system, with a message design mockup

[10:26] New feature: the messaging system — avatar on the left, text on the right.

So I looked at the UserAvatar component, and I saw that the size that we need to use is not there. To fix this, we need to add a new size. But we already have small, medium, and large — what should we put in here? Medium-large? Quite large? Okay, so we did the most obvious thing that makes perfect sense: we name it appropriately, message, because it's only used in one place — the message, right?

Slide showing UserAvatar used with size='message'

[11:20] The new size is named size='message' — after the one feature that uses it.

Does this smell a bit to you? Yeah. Let's keep going for now. A few months later, I start seeing this everywhere, in other places that are not related to the message at all. So what happened here? Let's step out a bit. We have the Message component, which belongs to a specific feature. We have the UserAvatar, which is a generic user interface component. The message wants to show an avatar, so it uses that component. In turn, that component knows how big the avatar should be — so it's aware of the messaging system.

Diagram: the specific feature Message uses the generic component UserAvatar, which knows the avatar size

[11:45] The leak: the specific feature (Message) uses the generic component (UserAvatar), but the knowledge of how big the avatar should be lives in the generic component.

When I see this, I think that some information is leaking here, because now the message knows how to render itself, but it doesn't know how big the avatar should be. Instead, that knowledge is leaked into the UserAvatar component. The leak here is that information about a specific feature leaked into a generic component, making the component less generic and more awkward to reuse.

[12:27] Making the generic component more flexible

Another reason why this happened is that maybe our generic component is not flexible enough. So we're going to try to make it more flexible to fix this. We used to have four sizes; now we have eight sizes. Now the message can pick a size from the catalog, and we don't need to make any awkward change to it anymore.

Slide showing the Message feature picking size M from the UserAvatar size catalog

[12:50] With a fuller size catalog, the Message feature simply picks size M from the generic UserAvatar.

But there's still a pitfall here. What would happen if we want to make a new size between L and XL? We may need to adjust the size table again, and maybe we have to go through the codebase and move XL to XXL, XXL to XXXL, and so on. Fortunately, at Taskworld this is flexible enough for us, so we don't have to do that.

But if you really want to make it really flexible, you can let the user specify the size in pixels. That's really flexible, but it may go out of control, right?

Slide showing UserAvatar propTypes with size as PropTypes.number

[13:30] Maximum flexibility: size: PropTypes.number — the size in pixels.

To keep things under control, you can specify a list of allowed sizes.

Slide showing UserAvatar propTypes with size as PropTypes.oneOf of allowed pixel values

[13:45] Keeping it under control: size: PropTypes.oneOf([18, 24, 30, 36, 48, …]).

So, you know, there are trade-offs to all of these three approaches. This is an example where a smell calls for a bit of code restructuring.

[13:50] A naming problem: the MenuButton

But sometimes all you have to do is just change the name. Let's see another example. Again, we have a standard user interface toolkit: we have a Button which the user can click, and we also have a pop-up menu that the user can select an item from. So help me with this: I have a button, I have a menu… MenuButton! Okay, we're just putting it together.

Slide showing an Upload file button with its pop-up menu: Select file on computer, Dropbox, Google Drive, Emergency alert

[14:13] A Button plus a pop-up menu: the “Upload file” MenuButton.

This menu button — you can click on it, a menu opens, and you can select items from it. But the catch here is that the button must appear to be pressed while the menu is open. Only when the menu is closed can the button return back to the original state.

At first thought, we may again start with the most obvious thing here, which is to make Button accept another prop called isMenuOpen, so that if it's true, then it appears to be pressed.

Slide showing Button.propTypes with children and isMenuOpen

[15:00] Button.propTypes = { children: PropTypes.node, isMenuOpen: PropTypes.bool } — the Button is now aware of the menu.

But again, does it smell a bit? That's because now the Button is aware of the menu, which is an entirely unrelated concept. Thinking a bit deeper, we see that the button doesn't really need to know about the menu — it only needs to know whether the button should appear to be depressed.

Slide showing Button.propTypes with isMenuOpen renamed to isDepressed

[15:32] Renamed: isDepressed: PropTypes.bool — the Button no longer knows about any menu.

This example shows us that a simple naming change can entirely communicate a different thing. So when people say "it's just a name" — you know, naming is really important. For this kind of smell, when I review code, I try to ask myself: does this really need to know about that?

Slide reading: When reviewing code — Does this really need to know about that?

[15:48] The review question for information leaks: “Does this really need to know about that?”

That's how I do it.

[15:59] Smell #2: Low cohesion

The second smell I call it low cohesion. Cohesion here means that related things stay close together.

Slide reading: Low cohesion

[15:59] Smell #2: “Low cohesion”.

Let's see more examples here. Now for our app, we need to create a navigation bar, and it looks like this.

Slide showing a navigation bar mockup: My app, Home, Explore, Search

[16:20] The navigation bar to build: “My app” with Home, Explore, and Search.

If I use React Bootstrap, implementing this should be straightforward. First I need a Navbar; inside it, a header which contains the app's name, and then several items, which are shown here.

Slide showing the Navigation component rendering Navbar, Navbar.Brand and NavItems with React Bootstrap

[16:27] The Navigation component with React Bootstrap: Navbar, Navbar.Brand, and NavItems.

So that's it. So far so good. Again, we need to implement a new feature, and this time it's going to be the authentication system. We need to update the navbar to display these two guys at the right.

Slide showing the navbar when logged out (Login) and when logged in (Logout), circled in red

[16:45] The authentication feature: Login when logged out, Logout when logged in.

So let's do it. First, I'm going to take in some props so that we can figure out how to display the navbar correctly — we're going to figure out whether the user is logged in or not. And then at the right side of the navbar, we're going to add the navigation item accordingly. Okay. And now this is our presentational component, but we also need to connect to the Redux store. We can do that using the connect function from the react-redux package.

Slide showing the connect() enhancer selecting currentUser and binding onLogin/onLogout action creators

[17:30] Connecting to the Redux store with connect() from react-redux.

So that's it. Now, looking at the component, we can see that it cleanly separates into three concerns: selecting data, dispatching actions into the store, and our rendering logic, which is the presentational component.

Slide annotating the three concerns with colored bars: selecting data from store, dispatching action to store, rendering logic

[17:38] Three concerns, cleanly separated: selecting data from the store, dispatching actions to the store, and rendering logic.

[17:46] Cross-cutting concerns

Again, we need to implement new features — this time, two new features. Now we need to update the navbar again: when the user is logged in, we need to display the number of unread notifications and messages.

Slide showing the logged-in navbar with Notifications (9) and Messages (9) circled in red

[18:00] Two more features: unread Notifications (9) and Messages (9) in the navbar.

Coming back to our code, we already see the pattern here, so let's go with the flow. First, I'm going to select some data from the store and bind the action creators here. And then here, I'm going to take in some props according to the code at the top. Now going down to the bottom, here's the rendering logic — we are going to add two more items here: the notifications and the messages. That's it.

Maybe we can zoom out a bit here. We can see the pattern that our code is cleanly separated into three concerns. But these concerns are cross-cutting — that means they have to do with many different functionalities of the app.

Slide titled Cross-cutting concerns, with colored bars spanning the whole Navigation component

[18:48] Cross-cutting concerns: each concern spans many functionalities of the app.

But if we look from another perspective — from a functionality standpoint — we are going to see that many functional parts are intermixed inside the code.

Diagram showing User, Notification, and Message concerns intermixed inside the Navigation component

[19:21] From the functionality standpoint: User, Notification, and Message code is intermixed inside Navigation.

This can make it a bit hard to navigate the code. If we want to look for the code related to the notification, we have to jump and skip over a lot of unrelated code.

[19:21] Real-world example: Bemuse's options panel

Let's see a real-world example. This is the options panel from my project bemuse. I need to add a new option here. This is the existing code — don't worry about it. But to implement this, here's where I need to add the code: the first one there, the second one in the propTypes there, and I have to jump down 80 lines to add new code here.

Slide showing the bemuse Player Settings panel next to its code, with annotations marking where a new option must be added

[20:03] Bemuse's Player Settings: adding one option means editing places 80 lines apart.

Seeing this, I start to think: as I add more options, what would happen? These parts would spread even more apart, and I have to scroll up and down a lot more to implement more options in the future. Some cohesion is lost here.

You can tell that when you code, when you need to do something simple, you have to jump up and down a lot — or maybe you have to go between different files, or even sometimes different repositories. You can also smell this when reviewing a PR: when you start to notice "I read this piece of code, but I don't understand it — I have to jump down and jump up and down and up again to fully understand a particular feature."

[20:30] Files organized by type

This can also happen when files are organized by types. In this example, if I want to implement a new feature, I have to change six files.

Slide showing a file tree split into components/scoreboard and modules/scoreboard with actions, reducer, selectors

[20:45] Files organized by type: components/scoreboard/ for the view, modules/scoreboard/ for actions, reducer, and selectors.

While grouping files this way can make the app's architecture more obvious — it's obvious we have entities, interactors, IO, and UI here —

Slide showing a file tree grouped into entities, interactors, io, and ui folders

[21:08] Grouping by architectural role: entities/, interactors/, io/, ui/.

in a small project like bemuse, I would say this is a pretty good way to structure. But once you have like 200 files of each type, this approach doesn't scale very well for us.

[21:23] Aiming for functional cohesion

So what we can do is we can try to aim for functional cohesion: we try to group things by the purpose of the code, instead of grouping by responsibility — not "I'm going to select data from the store, I'm going to dispatch," but "this part is for messages, this part is for notifications." Let's do that.

Slide reading: Let's try aiming for functional cohesion instead of logical cohesion

[21:23] “Let's try aiming for functional cohesion instead of logical cohesion.”

Coming back to our code, here's the Navigation component. First, I'm going to remove stuff not directly related to navigation. This one is gone, propTypes gone, and the rendering logic that has to do with user, message, notification — I replace them with specialized components here.

Slide showing the Navigation render method using NotificationsNavItem, MessagesNavItem, and LoginLogoutNavItem

[22:10] Navigation now renders specialized components: <NotificationsNavItem />, <MessagesNavItem />, <LoginLogoutNavItem />.

[22:27] Delegating the rendering logic

These specialized components are smart in a way: the login/logout nav item, for example, would know how to figure out the current authentication state on its own and render the right thing. So let's now look at it. Again, we connect to the Redux store, we select some data, we bind the action creators, and here's our rendering logic. That's pretty simple, and this looks pretty good, because now most of the code is concerned with authentication and the current user — except for these two lines which render the nav item. They are still concerned with the navigation, right?

So we are losing a bit of cohesion here again, because if in the future we need to replace the nav item component with something else, we need to jump from the navigation component at the top down to the other components that render the nav item.

What can we do here? Well, we can delegate the rendering logic. Instead of hard-coding the rendering logic here, we let the user of this component specify its own rendering logic as a function.

Slide showing the component calling props.renderLoggedIn and props.renderLoggedOut, with both calls highlighted

[23:32] Delegating rendering: the component calls props.renderLoggedIn / props.renderLoggedOut. It is only concerned about the current user and authentication — not about how to render it.

I'm going to add some propTypes to make it more clear. Now this component is only concerned about the current user and their authentication state. It's no longer concerned about how to render it — that belongs to someone else now. So this component is no longer related to navigation; it's just authentication, so I'll just name it Auth.

By doing it this way, the Auth component can be reused in other parts of the app, such as maybe displaying some kind of content only when the user is logged in. By the way, this technique that we delegate the rendering logic to the users of the component is now officially known as render props, and just a few weeks ago, this got into the official React documentation.

Slide labeling the Auth connect component as the Render props pattern

[24:31] The Auth component — an instance of the “render props” pattern.

[24:31] Grouping the nav items with Auth

Let's come back to our Navigation component. At the bottom, instead of using a specialized component — thus moving the nav item down to other parts of the code — we can use the Auth component here and specify how to render when the user is logged out and logged in accordingly.

Slide showing the Navigation JSX using Auth with renderLoggedOut and renderLoggedIn functions returning NavItems, plus Auth propTypes overlay

[25:00] Navigation uses <Auth renderLoggedOut={…} renderLoggedIn={…} />; the nav items stay grouped in Navigation.

Now you can see all the nav items are grouped here. All we have left to do is change the notifications and messages to use the same pattern. Then all the nav items are going to be grouped in the Navigation component.

[25:13] Data connector components

Finally, the Auth component here — if we look at it, the objective of this component is to connect the user interface, which is here (the navigation bar, but it can be something else as I said), to the data source, which is here (the current authentication state).

Slide showing the Auth component with a green box: Objective — connect UI to data source

[25:35] The objective of Auth: connect the UI to the data source.

At Taskworld, we call this kind of component a data connector component.

To recap: once a component grows bigger, it can be hard to maintain. If we try to split the component in the most obvious way — maybe doing something like this, separating the logic part from the view part — this can lead to the code losing its cohesion, especially when one part would not make sense without the other.

Diagram showing NavigationContainer split from NavigationView

[25:50] The obvious split — NavigationContainer (logic) vs. NavigationView (presentation) — can lose cohesion.

We can try to split the code by the functional goals that it's trying to achieve. And if we do this right, it's easier to make these components reusable in other parts of the app.

[26:20] Conclusion: review for smells

In conclusion: in code reviews, we usually review code for consistency, for readability, and for logical correctness. These qualities are relatively simpler to review. But design smells are quite subtle, and it's pretty easy to see the code as correct but miss the subtle design issue — unless we are aware of them and actively look for them.

Slide listing what we review code for: consistency, readability, logical correctness, and smells

[26:45] What we review code for: consistency, readability, logical correctness — and smells.

To build maintainable software, I encourage everyone to develop the sense of code smells and be mindful of them. Today I shared two kinds of smells, and these are the kinds of smells that I encountered most in my professional coding.

I don't know of any ways that we can detect these smells automatically, especially when it's concerned with naming. We can check that we are doing camelCase, right? But we cannot check automatically whether this component should know about the other component. Some human expert is required here.

So when writing and reviewing code, I would like to encourage you to look for this kind of smell — and other smells as you can find on the web — and take note of them.

[28:00] Not all smells are bad

Last but not least, not all smells are bad. For example, duplicated code is a well-known code smell, but duplicated code can sometimes be easier to read than code that's not duplicated, because duplicated code is more explicit and contains less abstraction. Once you increase the level of abstraction, it can be harder to see what's going on.

Slide reading: Not all smells are bad — duplicated code can sometimes be easier to read

[28:20] “Not all smells are bad. Example: duplicated code can sometimes be easier to read.”

And also, that's why I duplicate all my slides instead of using animations, and end up with more than 200 slides here.

[28:41] Everything is a trade-off

In the end, everything is a trade-off.

Slide reading: Everything is a trade-off

[28:41] “Everything is a trade-off.”

By making your modules smaller, you're going to have more modules. By reducing the amount of code you have to maintain, you are increasing third-party dependencies. We have to make a lot of choices when developing software. And to see if we have made the right trade-off, look for feedback from other developers. After all, we make code maintainable so that other people can maintain it. So let's look for their feedback.

Slide reading: Look for feedback

[29:10] “Look for feedback.”

[29:17] Thank you

That's all I want to share today. Thank you, everyone, for listening.