Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Improving the Application Code Refactor 2: Readable Branching Logic

mark scholes
mark scholes
9,343 Points

This is just an observation rather than a question.

The idea that anything we have done in this section has made code easier to read or easier to understand is laughable to me. If I was handed the code written before this exercise I would be able to see quickly what is going on. We seem to have gone out of our way to remove all human language elements of our code. Case in point the nameActionsaction; refactor. Before it made perfect sense, the if statement follows the way in which we reason. It may be the case that I am a noob and therefore do not see the pattern as quickly as will in a few months time but where is the advantage of making my code less readable? Before our event listeners were simple with one event following another, now it jumps from one section to another. I am sure that I will eventually see an arrow function and just understand it as a function but the advantage of arrow to previous seems extremely limited. Are we aiming to get rid of many times when we use words as possible. I understand that what we have done would have been quicker to write if we had written it this way from the start, but we didn't we just spent extra time refactoring it. The whole process was longer and is now more complicated.

I know this is just a moan and things are the way they are and as such we have to learn how things are done but this seems mad to me

Lucian Dumitru
Lucian Dumitru
Courses Plus Student 13,024 Points

I totally agree with you Mark! I'm also a novice so reading this code and understanding it is a little difficult for me either. I think I'll review this part of the course in 2-3 months, maybe will make sense at that time.

David Avila
seal-mask
.a{fill-rule:evenodd;}techdegree
David Avila
Full Stack JavaScript Techdegree Student 5,410 Points

Hi Mark!

I feel now how you felt 7 month ago and I'm wondering if at this point in your learning path you have anything to add to your own post? Any feedback you can give us regarding your experience with digesting all these refactoring concepts and techniques will be much appreciated.

Cheers

Jeff T
Jeff T
9,672 Points

I guess it just depends on what your're familiar with. The code is much more readable to me now

7 Answers

Tom Geraghty
Tom Geraghty
24,174 Points

I like Tri's answer of working on a large team with thousands of lines of code, but I don't think that totally explains this and the other code refactoring videos.

What I think Guil is trying to do is break the code down into smaller modules each of which only do one specific thing. In doing so, he's trying to make the big picture of the flow of logic across the entire program easier to understand. Let me explain.

You hide the details of what each step is by putting them in another function and giving that function a descriptive name. This way when you are skimming down a program you can see the higher order overview without getting bogged down in specifics.

If you use a code editor it's likely you have those collapse icons you can use to collapse down code blocks (such as functions) but still see the function declaration and name. Those are hugely helpful when trying to understand a large piece of software. If you can follow the logic by reading the names of the function declarations alone, that to me is a well-written piece of software.

If you then want to know how the individual steps are undertaken, you can expand the collapsed/hidden functions and delve into the logic of them as individuals themselves. This is a big part of software architecture as opposed to just coding and something we should all work on (as an aside, check out Koestler's idea of a "holon" as it relates to refactoring, OOP, and other coding analogs).

Tri Pham
Tri Pham
18,671 Points

If 100 lines of code was your whole project and the only programmer is you, then yes it would be easier to just write it like that. However, when you got tens or hundreds of thousands of lines of codes spread out throughout different files and folders, you want a lot of organizations of ideas. For example, if I worked on your code and it is not saving properly, I can just scan it and then I'll be drawn to action and then to save. If you didn't organize it like that, I might have wasted thinking determining that the two code blocks i read were for editing and creating. The idea isn't to save time in the beginning (you most likely won't) but to make it easier to edit later by someone else or when the project gets much larger and you forget your own code.

Allen Redding
Allen Redding
5,486 Points

I can completely see your point and I agree that making code easier to read and understand early on is important for the future of a project. However I would agree with the original point. Right now I am trying to understand how to manipulate the DOM, there is already many new concepts to learn and conceptualize. Having to also consider the concept of refactoring while still digesting these new concepts feels like a distraction at this point.

I was taking a course in ruby not long ago and the instructors felt it was necessary to teach us how to test our code before we even learned what our code did because they felt it was important to learn it early. It only confused and distracted me. As a general concept, I think a better approach is to first teach how to create. Then only after that has been mastered to a degree, teach how to control and make that the focus.

I feel like refactoring should have its own section, and maybe it does later on in this course, so it does not distract from the main point which is the DOM.

Tri Pham
Tri Pham
18,671 Points

Yes, I agree its more important for a beginner to learn how to write working code and then worry about testing it and properly refactoring it. Refactoring and testing (maybe not necessarily test driven development) are VERY important concepts though and it probably works better if the code is fresh in your mind. If you separate refactoring and testing into other sections later, you might not really feel the importance of them. You might get the idea that the pre-refactored code is actually okay to write and publish for your team to see. Better to hammer down good practices over and over than to let you develop bad practices (at least not unknowingly).

Anyways don't take everything you hear as facts you have to believe but personal opinions. Some opinions have a lot more supporters than others but they are just biases at the end of the day. Here's an article by DHH (CREATOR of ruby on rails!) where he clearly shows he does not believe too much in following Test Driven Development. There's also a 1hr video RailsConf 2014 video of him talking about it on youtube if you prefer watching.

I totally agree. This whole refactoring actually makes the code more difficult for me to write / read / understand, but I do see the importance of refactoring, especially on larger projects where you may have thousands of lines of codes.

I can only hope that thru enough practice, and repetition, that I will eventually get the hang of it so I can understand it naturally without banging my head against a desk.

Bonnie Martin
Bonnie Martin
13,671 Points

I just posted a similar comment on the video before this one. Glad to see I'm not the only one who feels this way. As others have said, I understand the reasoning for this refactoring, but it makes it all so much more muddy.

This has been bad enough that I'm now literally wondering if I just don't like programming and should stick with CSS and other more design-related work. It's really disappointing. I feel like I've wasted hours upon hours getting to this level of understanding for it to all be taken away again.

Tri and Tom already addressed the benefits of refactoring. Everyone should know that refactoring is EXTREMELY valuable, do not dismiss it simply because you don't understand.

I will just add this, to everyone feeling frustrated at not understanding, keep in mind that programming is HARD. That's why they pay software engineers a lot of money. It is NOT easy. It is ok if you don't understand, in fact if you're a beginner and you're breezing through all of this than you're a genius. Even the smartest people struggle when first learning these concepts, NO MATTER how it is presented. Being uncomfortable at learning a new concept is exactly how you get BETTER. In fact that is a sign that you're expanding your knowledge of programming.

I guarantee if you stick with it, everything will make sense. Come back to this video in a couple of months and you will see how the refactoring made things much simpler.

Chris Collier
Chris Collier
17,774 Points

I'm about halfway here. I really like condensing into functions. I think that step made the if/else statements a lot more readable and added some context. When it got to using bracket notation (which is impressive and a really cool feature of Javascript), I think it started to obfuscate things.

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

After reading this post i understand how important this refactoring is, but is there any one who can advise/suggest to overcome the issue for beginners? as we have so much on our plate already to get our hands on and grasp and retain all we have learned to get to this stage.but now it feels like if this was the "best practise" then why wasnt it explored at earlier stages, step by step and gradually instead of bombarding with these concepts all at once.point is it could have been made a bit simpler to make beginners life easy. would appreciate any recommendations from those who have learned this refactoring, and how have they managed to do it!!!

Why and When should I refactor my code?

Here are some points that made the concept of refactoring easier to understand.

Why should you refactor?

  • To achieve separation of concerns in your code
  • To make your code more readable
  • To make your code easier to debug

For example: In a restaurant your waiter doesn't take your order and then cooks as well. The waiter takes order and the chef cooks. Same thing in code, makes everything organized.

When should you refactor?

  • When you see repeated code
  • When your function is doing more than one action e.g. creating AND modifying an object
  • When your function is really long (A good rule of thumb is 10-15 lines per function)

To hammer the point home. This is much harder to read:

function createElement(element) {
    /* For the sake of making my post short, I made the function a few lines of code on purpose
    */
    // Creates a new elements & finds another element
    let newElement = document.createElement(element);
    let childElement = document.getElementById(Id);
    let parentElement = childElement.parentElement;
    let inputValue = document.getElementsByTagName('input')[0].value;


    // Checks the element's class name
    if (childElement.className === 'someClassName') {
        if (parentElement.textContent === 'something') {
            parentElement.textContent = inputValue
            childElement.textContent = inputValue
        } else if (parentElement.textContent === 'something else') {
            parentElement.textContent = inputValue
            childElement.textContent = inputValue
        } else {
            parentElement.textContent = inputValue
            childElement.textContent = inputValue
        }
    } else {
        parentElement.textContent = inputValue
        childElement.textContent = inputValue
    }

    // Appends child element to new element
    newElement.appendChild(childElement)

    return newElement;
}

Easier to read:

function createElement(element) {
    /* For the sake of making my post short, I made the function a few lines of code on purpose
    */
    // Creates a new elements & finds another element
    let newElement = document.createElement(element);
    let childElement = document.getElementById(Id);    
    let inputValue = document.getElementsByTagName('input')[0].value;

    // Checks the element's class name
    let childElementsClass = checkElementsClass(childElement);

    // Assigns text content
    assignTextContent(childElement, childElementsClass, inputValue);

    // Appends child element to new element
    newElement.appendChild(childElement)

    return newElement;
}