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

Java

Why use attributes instead of cookies from request objects

I'm sorry if this is a dumb question. I just finished the Using Filters And Request Attributes video and watched how Craig set an attribute for each request that is handled before any response or request. Here is the code:

before((req, res) -> {
            if(req.cookie("username") != null) {
                req.attribute("username", req.cookie("username"));
            }
        });

We then refactored our code so that anywhere the request's "username" cookie is called, it now calls the request's "username" attribute.

I think I understand Craig's code, but I don't understand the advantage of assigning the "username" cookie to the an attribute before each request. Why can't we just call the "username" cookie in all of our code instead of assigning the cookie to an attribute and then calling the attribute? It just seems like the longer road to me, but I'm sure I'm not understanding something.

Thanks for your help!

1 Answer

You can, but I think his point was that perhaps the cookie implementation will replaced by something else later and so it was best to gather up all access to cookie in one function. It's also simplifying things a bit since now you don't have to check everywhere if you have a username or not, again you can do that from one spot