DEV Community


Discussion on: 4 practices for better code

codevault profile image
Sergiu Mureşan • Edited
const goodPractices = {
  dry: true,
  wet: false,
  kiss: true,
  descriptive: true

const getParam = (param) => goodPractices[param];

This works in theory, if your object is const and instantiated right near the function getParam otherwise it might be difficult to know which fields you have in the object and which you don't. Especially if the object is not const

Using comments might be a temporary fix but if someone in your team modifies the properties of the object they will have to know that the getParam function has a comment listing all properties.

Ok, bear with one more of my critiques with

const redirect = () => this.props.history.push('/theories');    
const login = (username, password) => {
  return postApiData('/login', {username, password})
    .then(user => {
      if (user && user.token) Cookies.set('token', user.token);

const submitHandler = e => {
  login(username, password);
  if (!this.state.authError) redirect();

This is actually a good example, the concept can't be easily put into practice without hurting readability.

Functions should do something, or answer something, but not both

Yes, but they should be highly reusable. If the function itself is only used in this context it will be much harder to understand the code itself than if it was inside the submitHandler function.

Look at it this way, to understand submitHandler you will now have to understand both login and redirect. Okay, login here makes sense but redirect is oddly specific, maybe if it had parameters and was a utility function.

The rest of the examples are really good and, aside from some edge cases, they will work most of the time. Especially the first one, I learned it the hard way from a senior colleague :D

Thank you for the post. What do you think?

effingkay profile image
Klaudia Author

Great great points! Thank you so much for raising them, you actually picked up what I was worried about when I wrote the examples.

I have nothing else to say about your first point other than you're absolutely right. There can be some issues in the future with this code but then again - this was an artificial example just to demonstrate the point so I wasn't that worried about it

Second - redirect was a utility function actually, I dunno when I changed it but oh well, I'll go and correct it, great catch - thanks for noticing. And yes, submitHandler is harder to understand now but I think login and redirect are nice, descriptive names so you know what's happening when you're reading the code, plus both login and redirect are used in multiple places so they need to be utilities.

Thank you again for commenting!