Refactoring code has become one of my favorite things to do as a developer. It can have a major impact on code cleanliness, readability, and mainta...
For further actions, you may consider blocking this person and/or reporting abuse
So cool that more than one of your favorite refactoring strategies specifically clarify intent of the code! This is so fundamental to good code. Having code communicate intent is so much more important than having code that is a few lines shorter.
Exactly. Code is meant to be read by developers. Computers don't need to understand the code to execute it, they only have to follow instructions.
Hi thanks for the article.
Regarding 1. Replace Conditional with Polymorphism I would rather think carefully before introducing PizzaUser and IceCreamUser for this concrete example. I know that this is probably not a real world example but I would rather point out few things before people start to go wild with inheritance π
So lets consider a new requirement: As an user I would like to receive emails for my favorite music and sms notifications for my favorite tv shows. So we have user.favorites.music, user.favorites.food, user.favorites.tvshow.
With our current implementation we are running into an obvious issue because we need something what is capable of sending pizza emails, favorite music emails and sms notifications. If we stick to our inheritance model then we will end up with many different classes like: (PizzaNirvanaGOTUser, IceCreamDoorsNarcosUser...). But we can do better with the command pattern π. Example:
Happy coding!
That's a good point Marian and the crux behind the composition vs inheritance thinking but I think there's a place for both. My main decider (and it's beside the point to the one the author is making) is asking if that method really belongs on the class. So classes inheriting from Animal (Dolphin, Cat, Elephant) would all "make sound" (their own sound) so that would be a great case for inheritance but if the functionality is not related, eg. "send mail" (sorry, it's contrived but let's say in a talking animals universe, like Zootropolis, where animals can send letters either by running, flying or the postal service), the sending of emails is not intrinsic to being an animal and the same functionality could be rightfully applied to companies, people and other types of class that don't inherit from Animal, then composition is a better way to go. In my opinion, of course :-)
reading both the original recommendation as well as the alternative, I really have a strong feeling to stick with the conditions. Also, why not move simply move/abstract the condition inside the sendmail function? The information we need is already inside the user object. I find creating the extra classes for each type of favorite food overengineered TBH. And adding one new favorite food type, means we need a whole new class for it?
In example number five you use
hasUserPaidThisWeek
before you assign it. Does it still work because of hoisting or something like that? Isnβt it a bit counterintuitive for people who read the code later?Hey Olivier, good catch! Yes that would be an issue - it would need to be a function declaration which would make it work via hoisting - I'll update the example (I'll admit I didn't actually run any of this code - it was more to illustrate the concepts - so there may be other runtime errors π¬).
But, I do think that declaring a function right after it's used is a good pattern. It follows the "Stepdown Rule" described in the book Clean Code. The idea is code should read like a top-to-bottom narrative, which I do kind of like. More examples here: dzone.com/articles/the-stepdown-rule
Generally I think the most important thing is that related functions live close together in the code...whether they are before or after is less of a concern.
I agree with you: the top-to-bottom narrative works better. Declaring such functions before they are used makes you wonder whatβs happening, before you see the usage, when you read the code.
And I think the way the code is set now is good. My brain is not bothered by the function being declared after itβs used, even if itβs inside the current scope, because itβs a function declaration.
P.S. no worries about not having run the examples. Youβre right, theyβre illustrations. I was just curious about that particular case as I found it surprising (then again, programming languages are full of surprises) and Iβm not a JS expert.
Thank you for the article!
I also like to store gigantic conditionals in a meaningful variable π
As for the example number 4, I suppose it's an implementation of the Value Object pattern, for elements that do not have a specific identity?
martinfowler.com/bliki/ValueObject...
Yes that looks very similar!
very nice patterns, but I think on the number 6 you wanted to put it this way:
A useful extension to (1) is the null pattern: providing an implementation which has the right methods but does nothing, instead of a conditional at the point of doing the required thing (eg a NoEmail user facade in the example above)
I love #6 (single object param) hands down one of my favorite coding practices! Works great with TS too :D
I would prefer to modify it to below. In this way the signature of method is clear. It also tells what kind of objects are acceptable. It also tells what kind of properties should be bound together as an object. The grouping of properties is domain specific. It is not anonymous.
I am taking clues from
Replace Anonymous Function with Expression
.Note: I am not satisfied with
personPair
as variable name. Feel free to suggest better variable name.Thank you for the article. Really interesting subject.
However, I would like to suggest to be very very (!!) cautious with the advises 4, 2 and 1, because of KISS and Yagni. Always think twice or better thrice before introducing a new abstraction level to your code.
Always ask yourself: Do we really need this now and what are possible costs of the abstraction?
While still refactoring I'd suggest to replace in the second example (example 5)
with
and don't forget, that arrow functions don't create their own this-scope.
For #3, my usual suggestion for refactoring is to create a function instead of a const variable - in this case user.isSubscribed().
The nice thing I see in having a const variable is when there is a complex calculation used multiple times. Then sure, do the calculation once, store in a const and fire away.
This might be my functional programming bias talking.
But... in example, 4, 2 and 1 you managed to turn a few lines of code into many lines of code.
What is better in these examples?
6 tend be fragile in none-typed languages in my experience.
3, 5 are great tips, they increase verbosity tremendously. :)
About #1, how do you implement "getUser(userData)"?
I'd probably use a switch statement to instantiate the appropriate user type - so something like:
You might have included this snippet in the article
This is like the #1 #1 part of the article... You might want to add it.
Switch statement itself sometime bound you, we can use factory pattern to return the desire class object ;)
Thanks, Abdul. Could you provide an example of what the code might look like? Most factory functions I've seen still involve a switch statement or a series of if/else statements.
and all these techniques should make unit testing easier too π
Great article but for number 6, did you actually introduce an object parameter or am I reading that wrong, looks the same?
Thanks. I did, it's using object destructuring. They do look very similar but in the "after" version there are brackets around the params.
Ahhhh, thanks for the reply, learned 2 things from this article so! Many thanks again, great article
Nice article!
Great post, very interestingπ I can't say I'm very good at refactoring yet (I'm a beginner still) but I'd love to improve because clean and readible code literally makes me happy!
For #4, TypeScript has enums, which are a lightweight and legible alternative to let a class do the heavy lifting.
Just read the article and pretty sure I'm about to use some of these 15 mins from now :D
Thanks for this, it's really helpful to read as a beginner.
I find as a good rule of thumb, if I'm having to write comments to explain what the code is doing, I probably need to refractor it!
Love it!
Great article and well explained Bryce!