r/javascript • • Dec 19 '16

~15 years trying to make everyone separate HTML, JS & CSS. And then suddenly everything went south and we’re writing code like this.

https://twitter.com/thomasfuchs/status/810885087214637057
483 Upvotes

258 comments sorted by

144

u/edanschwartz Dec 19 '16

For 15 years, we tried to separate application state management from presentation. Our best approach to this was to keep HTML, JS, and CSS code in separate places. But there's nothing magically about that approach - it's a means, not an end.

Now we have different ways to approach keeping app state separate from presentation.

50

u/parlezmoose Dec 19 '16

React isn't that much different from the old way. It's still not good practice to put logic in your markup. A well written react component will look a lot like a clean HTML template, with logic delegated to helper functions.

People just get caught up on the fact that "html" is in the same file as your JS. The biggest effect of this change is that it makes the codebase much more readable and maintainable. You no longer have to go hunting through templates to find the one your component uses.

22

u/[deleted] Dec 20 '16

Agreed. When I first saw JSX I thought the developers had gone insane, but once I used it I understood immediately - having everything in one file really is so much easier.

(I personally still exclude CSS from that, though - I'm yet to see a React/JSX styling solution that I like)

2

u/nickgcattaneo Dec 20 '16

If you're writing in React components, one of the best ways is to use less and just import css specifics (either a global css added at your entry point and/or css specific per component). So basically your React component turns in to something like (excerpt)...

import styles from './MyReactComponent.css'
const MyReactComponent = () => {
    return (
        <div className={styles['container']}>
             some stuff
        </div>
    )
}

1

u/thomad16 Mar 04 '17

I just read that and it actually blew my mind. This honestly changes a lot. I am curious how this works does it support obfuscation and minification of css class names. Are there tools that you can use with this code to refactor. Finally does this allow css to be added into webpacks tree-shaking?

1

u/nickgcattaneo Mar 08 '17

So basically the way it works is; we use webpack to process less files and bundle them together with the JS. Once the JS loads, it injects into the head traditional <style> tags with the referenced CSS. Consequently, this means the css works just like traditional style sheets referenced in the head. Likewise, we also use a randomizer on the CSS class names so all class names are ensured to be unique. In webpack, under modules our less referenced files get run through a loader that looks like this:

                     // here we do not randomize where we store our shared global and application global css (that's why we have two css loaders)
		{
			test : /\.css$/,
			loader : 'style-loader!css-loader!postcss-loader!less-loader!',
			include : [ 
				dir.src.main.shared.viewlayer.css.root,
				dir.src.main.offersportal.viewlayer.css.root
			]
		},
                    // this is where we randomize the class names (we target css that is stored specifically in component-specific css files)
		{
			test : /\.css$/,
			loader : 'style-loader!css-loader?modules&localIdentName=[name]-[local]-[hash:base64:5]!less-loader!postcss-loader',
			include : [
				dir.src.main.offersportal.viewlayer.component.root,
				dir.src.main.offersportal.viewlayer.page.root,
				dir.src.main.shared.viewlayer.component.root,
				dir.src.main.shared.viewlayer.page.root
			]
		}

8

u/tebriel Dec 20 '16

But in reality, devs are going to shit all over it like they do everything else. There'll be loads of business logic dumped into the inlined markup and you're left with the same problem.

7

u/Senthe Dec 20 '16

This. Making restraints in languages and frameworks always had a purpose of keeping noobs in some borders of sanity, not making experienced devs uncomfortable for no reason.

3

u/DOG-ZILLA Dec 20 '16

But it never works anyway. You're kidding yourself.

There will always be different types of developers. Me, I'm one who is a bit OCD about the formatting and ESLint is my God, but there are others who just want to get the job done by hacking stuff in.

You're never going to stop developers always doing what they wish.

4

u/Senthe Dec 20 '16

It's not about keeping you from doing things you want to do. It's about keeping you from doing things nobody wants to do but you don't know about that yet.

0

u/[deleted] Dec 20 '16

A well written react component will look a lot like a clean HTML template

That's simply impossible by the very nature of JSX, the bigger the component the bigger the mess.

0

u/[deleted] Dec 20 '16

[deleted]

2

u/edanschwartz Dec 20 '16

I don't know about Entity/Component architectures in game engines... But I think the Component name might come from Web Components, with the idea that you can use a React component like you would a web component (with some help from JSX).

A react Component should be usable standalone. Though if you're wiring things up with Redux, some will be less reusable than others. It's worth looking into the idea of smart components vs. dumb components

204

u/[deleted] Dec 19 '16

2 years of JSX, and even more years of hyperscript, and "we" still cling to jquery-1.0 era talking points apparently without understanding the difference between DOM and HTML, let alone the bigger picture of why we're doing this.

If you want to criticize new ways of doing something, at least make an effort to understand what problem it's supposed to solve and how.

60

u/Retsam19 Dec 19 '16

Hear hear.

The reason people have stopped following the old best practices isn't because everyone spontaneously lost their mind and decided to reject a decade of wisdom just for the fun of it. It's that they were convinced that the old best practice was flawed and that there are good reasons to favor the new practice.

But, hey, someone's really convinced that the old ways are best, nobody's stopping them from writing your code that way.

22

u/kethinov Dec 20 '16

good reasons

Such as?

4

u/codayus Dec 20 '16

The overriding goal from day one has been "separation of concerns". (Or in simpler terms, that stuff that changes together should live together, while stuff that changes independently should be split into separate files.)

There is, however, an ongoing process of figuring out what the concerns are, and how best to separate them. And as the platform changes, those answers change as well. For a desktop app, you can do really well with MVC; for a webapp it's not entirely clear that MVC is appropriate, or indeed, possible.

(Seems like about 80% of web frameworks claim to be MVC, MVVC, MV*, or some other variation. But the more you dig into the critical details of how MVC works on a desktop app, the more you start to realise that it doesn't really map cleanly onto the web.)

When you're writing a rails app, it makes a lot of sense to put all the business logic into your ruby code, and all the presentation logic into your HTML, CSS, and JS. And it would be a horrifying code smell to see, say, someone building up some HTML in their controller by concatenating strings. Languages are a good heuristic for concerns.

When you're writing a SPA, all the logic is JS. (Depending on how you're doing templating and styling, it might all be JS.) The language is no longer a good heuristic for concerns. I think anyone who has tried to maintain a large Backbone app will intuitively grasp this. :)

2

u/kethinov Dec 21 '16

I don't disagree with any of that, but it doesn't really address my question. Many people think the JSX approach of conflating HTML templates with JS is pretty gross. People keep saying there are good reasons for it, but then not outlining those reasons beyond anything other than "I dislike them being in separate files." Is that all it is?

4

u/codayus Dec 21 '16

Many people think the JSX approach of conflating HTML templates with JS is pretty gross.

That's not really much of an objection. I think you'll find the actual objection is generally phrased more like "but what about separation of concerns"?

then not outlining those reasons beyond anything other than "I dislike them being in separate files." Is that all it is?

Again, it's about separation of concerns (and the closely related single responsibility principle).

  • If a single change requires you to open multiple files, then that's 1) bad for maintainability and 2) a strong sign that you've spread a single responsibility across multiple files.

  • If there's multiple types of changes that might make you open a file then that's 1) bad for maintainability and 2) a strong sign than you've lumped multiple responsibilities into a single file.

That's really the entire argument. Anti-JSX people are (basically) suggesting that the structure will lead to more of the second, but won't stop the first. Pro-JSX people are suggesting that the structure will lead to less of the first and won't lead to more of the second.

It's not about whether you "like" them being in separate files, or whether you think it looks "gross"; it's about whether the principles of software engineer argue for or against a particular structure.

1

u/kethinov Dec 21 '16

So then you're also in support of people who mix PHP code with HTML as single files as well? Because that same argument should apply to that as well. And as I understand it, doing that was considered a pretty enormous antipattern.

3

u/codayus Dec 21 '16

So then you're also in support of people who mix PHP code with HTML as single files as well?

No, because that's entirely different in terms of everything I just wrote. I'm not sure if you don't understand PHP, don't understand JSX, or don't understand the "separation of concerns" argument, but your counter is nonsensical.

Briefly:

Mixing PHP and HTML in a single file is fine, and nobody has objected to it. PHP was developed as a templating language, and it can still be used as one. The Plates project is a well-regarded native PHP templating library that does not violate any principles and is not an example of any antipatterns.

Of course, other template libraries like Twig are much more popular, and provide a concise Mustashe-like syntax, but note that they all compile to PHP. If the objection was "mixing PHP and HTML", then a twig template would violate it. But it's not, and has never been: It's to mixing business logic and presentation.

And in a modern PHP app, your twig template (or your Plates template) has no business logic, and your controllers have no HTML, so it's fine. The antipattern you refer to was people mixing concerns, not people mixing languages.

Further, JSX is not HTML. It's a DSL which is compiled to JS. So even if the concern was purely mixing languages (and again, it isn't and wasn't; you have misunderstood what people object to), JSX doesn't actually do that. And no, this is more than mere pedantry. JSX isn't HTML, and you'll run into problems if you confuse it with HTML. And just to make that point even clearer, there are alternative template engines like Hyperscript which you can use as a drop in replacement for JSX. Hyperscript is obviously just native JS, but it's logically identical to JSX, and it's 100% identical in terms of the experience of maintenance. There's no valid argument for why JSX is "wrong" but hyperscript is "right".

On the other hand, is is wrong to intermingle business logic with JSX or hyperscript. Again, separation of concerns, not technologies.

Because that same argument should apply to that as well.

Yes, if they were the same thing. The arguments about JSX would apply to XHP, not PHP. :)

→ More replies (2)

-3

u/Vinshati Dec 20 '16

26

u/kethinov Dec 20 '16 edited Dec 21 '16

It would be helpful if people would stop linking to this 20 minute rambly video and summarize the arguments concisely in text form.

Edit:

I watched the video. The argument essentially boils down to "I want all my HTML, CSS, and JS in one file. Editing multiple files at once sucks."

There. I saved anyone else reading this 20 minutes.

14

u/CaRDiaK Dec 20 '16

TLDW; Separation of concerns is not herding code into their respective files for the sake of it, as concerns often span boundaries. My 'input' concern contains a bit of logic, bit of markup and some styling, don't make one hunt for it across multiple files.

→ More replies (5)

10

u/Senthe Dec 20 '16

Yep it's a plague in our modern internet, I have no idea how watching videos became easier than reading texts that take 10 times less time and have the same content. I guess writing takes too much effort.

6

u/ferrousoxides Dec 20 '16

Easy. The people who have the most time to participate in discussions also have the most time to watch videos.

Relevance and brevity were replaced with Twitter, and long form replaced with let's plays. [screams internally]

2

u/youtubefactsbot Dec 20 '16

Separation of concerns RANT - MPJ's Musings - FunFunFunction #47 [20:08]

Separation of concerns is pretty misunderstood concept, in programming in general, no just JavaScript and web development. I talk about separation of concerns in the context of React and combining HTML, CSS and JavaScript in one place, but also in the more general programming sense in function extraction.

^funfunfunction in Science & Technology

16,220 views since Aug ^2016

bot ^info

-7

u/ForlornSpirit Dec 20 '16

Such as?

Fuck beginner friendly, easy to understand code. Its too much trouble.

0

u/[deleted] Dec 19 '16

[deleted]

1

u/jax024 Dec 20 '16

Yep. Its abstraction, plain and simple.

3

u/[deleted] Dec 20 '16

I'm not sure it's an abstraction either. It's definitely a new organization, and it's arguably a new representation (even though it's still just HTML, JS and CSS).

9

u/SamSlate Dec 19 '16 edited Dec 20 '16

what problems can't be solved a with clear separation of html and css?

edit: I see why that wording is confusing

what are the cases that prevent web devs from separating their HTML and css?

103

u/[deleted] Dec 19 '16

How is CSS even relevant here? Inline CSS styling is an HTML thing. You don't have to use it in JSX any more than you'd use it in HTML.

The main difference is interaction between HTML, DOM and JS.

The very old way is to build DOM using HTML, and then tie it to JS logic by querying the DOM for CSS selectors and attaching event handlers to resulting DOM nodes.

The less old way is to build DOM using HTML templating and then tie JS logic to it using magic strings e.g. in "ng-onClick" magic strings.

The new way is to build DOM in JS, completely bypassing HTML, and tie JS logic to DOM nodes directly, right when you're building them. Usually this goes through a virtual dom library for performance, but that is strictly speaking not required, and irrelevant for this discussion.

11

u/SamSlate Dec 19 '16

How is CSS even relevant here

idk, it was in op's headline. I'm asking if anyone is suggesting inline css over classes- and if so, why?

15

u/[deleted] Dec 19 '16

The problem with CSS classes is that they're global, so naming collisions will eventually cause styles to apply unexpectedly to other components or to child components if you're not careful.

You can limit this by scoping your selectors to the component's class name, and using child selector instead of descendant selector. Inline styles have their own problems (e.g. lack of natural inheritance), and there are libraries that address these to some extent.

The actual tweet does not include any CSS because in React inline styles are typically only used for dynamic styling (e.g. to achieve what you'd do with jquery's show/hide methods). Using inline styles everywhere is generally discouraged.

9

u/SamSlate Dec 19 '16 edited Dec 20 '16

so naming collisions will eventually cause styles to apply unexpectedly

imo this is a problem when people don't scope* their css well, as you said.

Ok, animation is a pretty good example of when to use inline. You could do it in css, but sometimes inline is easier..

8

u/TheCoelacanth Dec 20 '16

Yeah, poor scoping is the cause of the problem, so why not let a compiler take care of it for you to make sure that it always gets done well?

2

u/Senthe Dec 20 '16

Which compiler does that? Genuine question.

5

u/[deleted] Dec 20 '16

So, the main contenders right now are:

  • Angular 2

  • Svelte

  • Vue

The above all have in-built style-scoping that will generate scoped classes for you.

There's also CSS Modules. This is one that I originally loved but am a little more wary of. CSS Modules is essentially a specification that defines some syntax extensions to CSS:

:local(.myStyle) {
  color: red;
}

If you were to import this into a JavaScript file when using a plugin for your preprocessor (babel/webpack/whatever) that supported this spec, you'd get back an object of class names to randomly generated ones - something like this:

import classNames from './style.css'
console.log(classNames)

> { myStyle: '1237984192rasdhoasdh' }

You'd then use that as your class name rather than the original one. The reason why I'm wary of this is because it is not part of any CSS specification and so is volatile and is not actually on the roadmap of being adopted by any browser or native version of CSS, which means I am implicitly tying part of my build process to a third party dependency.

Of course, you can make the same argument for JSX (and you'd be right), but JSX is supported enough IMO that it's acceptable currently (first class support in TypeScript and plugins for Babel exist).

→ More replies (2)

15

u/leviathan123 Dec 19 '16

I wish I could upvote you more than once. Thanks to your post I now understand the WHY of JSX. It makes perfect sense now, thanks so much!

2

u/tebriel Dec 20 '16

This was happening in Dojo years ago, and you didn't need to inline markup to do it...

4

u/[deleted] Dec 20 '16

I haven't used Dojo, but from a quick look it seems to fall into "the less old way" I described above, similar to Angular. Template strings with string variables magically bound to model properties.

If you want you can definitely avoid inlining JSX into JS:

// myTemplate.jsx
var React = require('react);
module.exports = function myTemplate(foo, bar) {
  return (
    <div onClick={foo}>{bar.baz}</div>
  );
}

Presentational React components are an extremely thin wrapper over this, allowing for better code organization.

1

u/tebriel Dec 20 '16

Yeah I know Dojo wasn't exactly the same as react, but it was doing things a better way, like 10 years ago... So everyone always compares things like jquery against angular and react, when jquery was always the shittiest solution out there - it was just the easiest.

1

u/calvers70 Dec 20 '16

JSX is just syntactic sugar you could scrap it altogether in fact and not change how react works. I hardly think it's some grand third stage in the oversimplified evolution you mention. It's like coffeescript or something. A convenience tool that can increase efficiency but it comes with the same tradeoffs that any pre-compiled abstraction does (learning curve, more moving parts, less visibility, more complex workflow etc)

1

u/[deleted] Dec 21 '16

Like I said, the "grand third stage" is a combination of build DOM in JS and tie JS logic to DOM nodes directly, right when you're building them. Both JSX and Hyperscript fit into this pattern. Previous string-based templating systems do not. It's a pretty sharp distinction.

This "grand third stage" is not related to compilation in any way, and all the compilation/build-tool tradeoffs you mentioned are only required by JSX, not by React, and not by Hyperscript. You can do React or Hyperscript or both together without any compilation or build tools, just by requiring a couple <script> tags, if that's what you want.

24

u/averyvery Dec 20 '16

My complaint, even before React, was that this idea of "separation of concerns" is not fully considered on the web. Sure, there was a time when HTML was "content", CSS was "styling", and JS was "behavior", but in modern applications the three are completely interdependent. If JS is applying a class to a UL and that class collapses the list, you're just spreading your problem across three files (and connecting them with a global naming system that's hard to enforce and easy to break).

React's component structure moves your "concern" — the component itself — into a single file or folder where it can be easily understood, modified, moved, and even reused with ease. I think React acknowledges what a lot of us have thought for a while; that languages aren't separate concerns, features are.

4

u/SamSlate Dec 20 '16

you have a client and a server and neither want to give excess information. That's like.. the fundamental problem of communication on the web.

languages aren't separate concerns, features are.

yea, hearing this quoted in this thread.

I'd have to build something in react with a lot of "concerns" to get a better intuition on this.

8

u/averyvery Dec 20 '16 edited Dec 20 '16

Yes — but I think we've reached a point in web dev where "excess information" is harder to define.

If I need to serve a user a pageable image gallery, myself, the product manager, and the users would define this feature as "a group of images that shows one image at a time and advances when the page buttons are clicked".

Splitting this feature into HTML (view a stack of images), CSS (view them nicely arranged) and JS (enable click-to-page behavior) doesn't do anything for me, because none of those things on their own define an image gallery based on the specs I have been given. The full feature is all three things combined, and the simplest way to manage a combined feature like this is to put it, if not in the same file, then in the same location.

I think the web's idea of separation across language barriers comes from an early philosophy that CSS and JS were "extras", and HTML was the heart of the web, but if you look at modern web interfaces I think you'll see that all three are essential. React is a library for rendering interfaces (any interface, not just web), and as such, I think it takes an appropriate step by moving these interfaces out of separate places — loosely connected by classnames — and into single locations.

Still, it does feel very alien (and at first, inconvenient) to build this way, and I understand the shock the web community has been feeling seeing a lot of these long-held ideas get thrown away.

1

u/Senthe Dec 21 '16

"a concern" is not always "to render a thing that has some data and which will behave such and such". It can be also "pull some data for later use" or "compute some things in a way reusable in many parts of the app", this is the reason we invented services, factories etc. etc.

I think it's very shallow to assume the frontend is all about what renders and absolutely nothing else. Most apps will have some "frontend backend" part. If you put all this logic to templates/components it will be a huge huge mess. Are there any service-like things in React?

1

u/averyvery Dec 21 '16

True, and React (usually) depends on a data layer like Redux for fetching information and managing state changes, and reusable libs for processing/filtering data. Reselect is a nice example of a library that helps compute values from state, which is a common task when working with React.

1

u/Senthe Dec 21 '16

So without external libraries you can't actually DO anything reasonable in React, can you?

1

u/averyvery Dec 21 '16

You can do what it says on the box - render components. It's not a framework for developing websites, it's a library.

→ More replies (1)

13

u/fnovd Dec 19 '16

What problems can't be solved using assembly and years of dedication?

3

u/[deleted] Dec 20 '16

1

u/xkcd_transcriber Dec 20 '16

Image

Mobile

Title: A Bunch of Rocks

Title-text: I call Rule 34 on Wolfram's Rule 34.

Comic Explanation

Stats: This comic has been referenced 386 times, representing 0.2743% of referenced xkcds.


xkcd.com | xkcd sub | Problems/Bugs? | Statistics | Stop Replying | Delete

2

u/SamSlate Dec 19 '16

point taken, but my point is (imo) inline css should be a method of last resort.

6

u/fnovd Dec 19 '16

But what happens when I don't want my styles to cascade? I write React components as self-contained modules that I can plug into the virtual DOM. I don't mind styling them individually as long as #1 it works and #2 nothing else breaks.

3

u/[deleted] Dec 20 '16

Not wanting your styles to cascade is like not wanting an engine to cycle. That's fundamentally how the technology works. You can't just change it and expect the world to work properly.

2

u/Senthe Dec 20 '16

What if I don't want the world to work?

2

u/fnovd Dec 20 '16

Styles exist outside of CSS. You can have non-cascading styles. It's part of the HTML spec. You are wrong.

→ More replies (4)

1

u/fforw Dec 20 '16

Zero-install web applications in a program the user already knows?

9

u/Retsam19 Dec 19 '16

This is the wrong question, as others have pointed out. (Even assuming you mean "html and js", not "html and css")

The better question is "Is clear separation of html and js the best way to do web development?" For years that was thought to be the case, but React made a convincing enough counter-argument that a lot of people have changed position.

3

u/SamSlate Dec 19 '16

I meant CSS, ops headline implies inline-css is the future, I shudder to imagine trying to reuse/restyle that code.

I'm unclear on the vernacular here: If I build js elements and attach them to the page is that un-separated js and HTML? or do they mean php-style replace/attach {your code here}

maybe a better question:

what were you doing in react that changed your mind?

8

u/Retsam19 Dec 19 '16

I'm unclear on the vernacular here: If I build js elements and attach them to the page is that un-separated js and HTML? or do they mean php-style replace/attach {your code here}

The idea of "separate HTML and JS" was just that you shouldn't put JS in your HTML (e.g. putting JS code in your event handlers) or HTML in your JS (using JS to construct HTML elements and add them to the page). JSX violates this, since it's all about embedding HTML snippets into JS code.


The original React: Rethinking Best Practices talk does a great job explaining why React deviated from those practices. Here's just the slides if you don't care to watch the whole video.

4

u/SamSlate Dec 19 '16

React: Rethinking Best Practices

At one point he's suggesting inline styling be used for elements (specifically alternating element colors). There is CSS for styling alternating elements, but assuming he means nested elements, you can still use classes to define those styles instead of adding explicit styles inline. By making your style inline people have to dig through the react code to change style that could have much more easily been changed in the CSS file.

I know it sounds like i'm nitpicking here, but it's a big red flag to me when a library/framework claims to be about separation and efficiency creating completely unnecessary extra work for themselves and seem entirely unaware of any alternative.

putting JS code in your event handlers

I must be missing something here. what's the alternative? what can you attach to event handlers that isn't JS?

using JS to construct HTML elements and add them to the page

you mean, innerHTML vs appendChild?

if you're not adding elements to the page, and your not using event listeners, wth are you doing with javascript?

2

u/Retsam19 Dec 19 '16

At one point he's suggesting inline styling be used for elements (specifically alternating element colors). There is CSS for styling alternating elements, but assuming he means nested elements, you can still use classes to define those styles instead of adding explicit styles inline. By making your style inline people have to dig through the react code to change style that could have much more easily been changed in the CSS file.

I know it sounds like i'm nitpicking here, but it's a big red flag to me when a library/framework claims to be about separation and efficiency creating completely unnecessary extra work for themselves and seem entirely unaware of any alternative.

Arguing about classes vs inline-styles is a really a tangent, since that debate is entirely orthogonal to the question of whether or not you use React or a more traditional "separation of concerns" approach. A lot of people primarily use CSS with react, while some people favor inline-styles, and a lot use a mix of both. It's not particularly relevant to the question of whether React has value or not.


Just to keep the threads clear: these are responses to responses to my attempt to define what "traditional separation of concerns" looks like.

putting JS code in your event handlers

I must be missing something here. what's the alternative? what can you attach to event handlers that isn't JS?

To clarify, by "event handlers", I meant "HTML event handlers": part of HTML/JS SoC was that you shouldn't do things like <button type="button" onclick="doSomething('Foo')">Foo</button>.

using JS to construct HTML elements and add them to the page

you mean, innerHTML vs appendChild?

No, innerHTML vs appendChild is irrelevant. The point is that (according to traditional SoC) you shouldn't have HTML in your JS files. So no stuff like:

 function doSomething() {
      someElement.innerHTML = "<div><span>Hi Mom</span></div>"; 
      //using createElement isn't any better as far as separation of concerns goes.
 }

2

u/SamSlate Dec 19 '16

question of whether React has value or not.

i was under the impression this post was a commentary on nearly all of the framework libraries.

<button type="button" onclick="doSomething('Foo')">Foo</button>

so, you're "ideally separated button" would have no onclick function?

your examples depict a "pre-javascript" web. Removing javascript entirely is not a "separation of concerns", you're describing a completely different medium.

where is the javascript?

3

u/Retsam19 Dec 19 '16

i was under the impression this post was a commentary on nearly all of the framework libraries.

No, most frameworks (Angular, KO, Ember, Backbone) maintained a far more traditional JS/HTML separation, until React came on the scene. It wasn't until React and JSX showed up that the "keep HTML and JS separate" idea was challenged.

so, you're "ideally separated button" would have no onclick function?

your examples depict a "pre-javascript" web. Removing javascript entirely is not a "separation of concerns", you're describing a completely different medium.

where is the javascript?

It's in the JS file, using JS to attach events to the HTML elements. Like this:

HTML:

<button id="look-ma-no-js">Pure HTML button</button>

JS:

var buttonEl = document.getElementById("look-ma-no-js");
buttonEl.addEventListener("click", function () {
    doSomething("Foo");   
});

This is what "properly separated HTML and JS" has looked like for the last ~15 years. It looks a bit different if you use a framework, but it was always the same idea: HTML in one set of files, JS in others.

9

u/edwardmsmith Dec 19 '16

Ok, but why was that separation maintained?

I started writing web pages in '93, so I've been all up and down the progression of "separation of concerns" over the years in web dev, and for the most part, it was really about not mixing your DB access with your HTML in server-side templates, but when it was applied to HTML/CSS/JS it was done for the "HTML describes the structure, CSS describes the style, and JS describes the behavior" reason.

Now, at that time, when you were talking about the "behavior", you were talking about progressively enhancing a static website to add some (small) client side behaviors to a functional static website.

You had functional anchors that would submit to the server, and you'd tack on a bit of behavior, such as client-side validation, and eventually AJAX, as a progressive enhancement for the browsers that supported it (IE6 to start..).

So you have your static website served from the server, and if the browser supported javascript decently and had decent functionality, you'd add interactive behavior by tacking on the JS - you wanted to separate the JS so your server-side HTML generation didn't have to produce the JS.

It all made sense at the time, and if that's the kind of web site (although, we're really talking web apps now...) you're making, then this sort of "separation of concerns" still works.

But, if we're creating webapps that are large, complicated and don't really work without javascript enabled, the code in your example above, with that old idea of separation of concerns, is silly because without the actual behavior, the button is useless - it does nothing at all.

The idea being that the coupling between the element and the behavior is so tight now that in almost every conceivable circumstance of developing or modifying the code, you're going to be editing the element and the behavior at the same time.

This goes even further when you're working with something like React, where you're not even dealing with HTML at all, but instead you're dealing with (a virtual) DOM.

When I'm writing React, with the exception of my leaf components, and wrappers around component collections, I'm not really thinking in terms of HTML anyway, but instead, composing components.

The concerns of structure and behavior have blended, and therefore maintaining separation between them no longer really makes sense.

The concerns I want to keep separate now, in my modern web applications, are the concerns of dumb display components (that may or may not have hooks in the DOM event system) and smart components that act on those events and modify application state.

→ More replies (5)

2

u/dmitri14_gmail_com Dec 20 '16

Any reason for switching from hyperscript to JSX?

Andre Staltz e.g. considers JSX inferior: http://staltz.com/some-problems-with-react-redux.html

2

u/[deleted] Dec 21 '16

In my book they're an identical pattern – building (virtual) DOM nodes with JS. I personally kinda like hyperscript's natural syntax more than JSX, but don't care that much. Also, Staltz is the man. Cycle.js rocks.

2

u/dmitri14_gmail_com Dec 22 '16

Philosophically yes -- they are identical. ;)

Otherwise, one is a proper JS and the other is a hybrid of HTML with JS plus overheads, such as extra noise (as nicely illustrated by Andre), additional notation, messed up editor syntax highlighting and the need for plugins to do anything.

13

u/faaace Dec 19 '16

I thought Polymer was a really good project, but google managed to kill its popularity with their shitty attitude towards open source and not building the thing into npm.

3

u/[deleted] Dec 20 '16

Polymer deserves a special place in hell and even that gives it too much credit. Actually working with it made me absolutely hate it with a passion. Polymer sucks. But their conferences are nice.

1

u/i_spot_ads Dec 20 '16

They focused on angular, keeping another framework would be stupid

1

u/[deleted] Dec 20 '16

Then they should've set it free and not basically kidnap the whole project. Here we have a perfectly fine proxy for node but we don't have that for bower and our proxy doesn't work well with it. And our IT (for some reason) doesn't want to make a bower exclusion as well, so we can't do any prototyping to show how fine it works. Also they kinda stopped the big progress of the project by not having people constantly working on it anymore that previously added a lot of content.

I don't mind that they prefer Angular, but it seems that because of this they ran Polymer into the ground and now it has lots of problems gaining enough traction.

3

u/i_spot_ads Dec 20 '16

It will never gain traction, and honestly I'm okay with it, there is no particular reason for it to exist when angular solves the same problem and way better.

2

u/[deleted] Dec 20 '16

I found webcomponents to be more future-ready than Angular really. Or how they go about getting each component a decent readme and example. Seems more fit for big projects and company frameworks.

1

u/Ajedi32 Dec 20 '16

Not true. Polymer's still being actively developed by Google, and they're even starting to use it internally in some of their larger products like YouTube. Not to mention the 2.0 release is coming soon.

35

u/MisterGergg Dec 19 '16

I still like Vue's approach of writing .vue files that have sections for HTML, JS, and CSS and then get transpiled out. It feels like a good mix of separation without that meaning having 3 files open in an editor just to get one thing to happen.

17

u/Isopaha Dec 19 '16

So native webcomponent approach? :)

4

u/cosmicsans Dec 19 '16

What came first, though? lol Vue.js or the Webcomponent?

I honestly don't know. I tried the googles but it failed me.

13

u/wickedmike Dec 20 '16

Web components came first, I heard about them many years ago. VueJS is what, 2 years old?

From wikipedia: Web Components were introduced by Alex at Fronteers Conference 2011 for the first time.

2

u/cosmicsans Dec 20 '16

TIL. Thanks!

2

u/Isopaha Dec 19 '16

Not sure, but it doesn't really take away from my point. Either the Vue approach was great enough for all the big shots to make it a (hopefully) native, or the big shots came up with an approach and it was great enough for Vue to copy it. :) Either way I like it!

5

u/mini-pizzas Dec 19 '16

As ECrispy points out above this is still just separation of technologies, not concerns. The video he linked is worth watching if you haven't seen it: https://www.youtube.com/watch?v=x7cQ3mrcKaY

1

u/elingeniero Dec 20 '16 edited Dec 20 '16

If only I could find a way of getting my editor to use the right linter and syntax checker for each section. I ended up using component folders with a . js, .html, and .css file in each and used webpack to mash them all together.

→ More replies (2)

41

u/ECrispy Dec 19 '16

Separate HTML, js, templates are separation of technologies, not concerns.

People really need to watch https://www.youtube.com/watch?v=x7cQ3mrcKaY

2

u/Senthe Dec 20 '16

Can you tl;dw? I don't really watch videos and I'm interested in what it has to say.

0

u/Magnusson Dec 20 '16

Separate HTML, js, templates are separation of technologies, not concerns.

→ More replies (1)

1

u/[deleted] Dec 20 '16

Someone get that man a cup of water.

1

u/nickwebdev Dec 19 '16

This is what I always quote! Too true.

21

u/sime Dec 19 '16

"What changes together, belongs together." is the rule of thumb I use when organisating code. It has served me well over the years.

(I don't know who said it first though.)

28

u/edwardmsmith Dec 19 '16

Every time somebody trots that old "Separation of Concerns" horse (especially that HTML/CSS/Javascript nag) out for another walk around the paddock, they always completely fail to demonstrate how it should, in their opinion, be done.

11

u/DzoQiEuoi Dec 19 '16

I'm in favour of seperating HTML/JSX and CSS.

Take a look at the CSS Modules approach. It allows for better code re-use, and your markup doesn't get cluttered with inline styles.

https://github.com/css-modules/css-modules

4

u/[deleted] Dec 19 '16

Ah, similar to Vue's scoped CSS? Because I love that.

5

u/DzoQiEuoi Dec 19 '16

I haven't used Vue yet, but CSS Modules does enable locally scoped namespacing.

The typical set up is to have a file for your component and a file for its styles then import the class names.

Let's say you have a CSS class called .cancelButton that composes another CSS class called .button, but changes the colour. You import cancelButton and use it as your component's class attribute, then at build time the class attribute becomes something like "component_cancelButton_2w9vK common_button_bBN0O" and both of those classes are emitted into a styles.css file.

This means you can use intuitive class names without fear of collisions, and the code for your button class can be reused by other types of button - and it really is reused, not just copied like with Sass mixins.

You end up with a smaller css file and more maintainable code.

5

u/Silhouette Dec 20 '16

One fundamental problem is that we can't separate HTML, CSS and JS completely with some of the more dynamic rendering requirements that we need to meet today.

When we were mostly writing static web pages with static styling, and occasionally we'd attach some JS to do some simple action and perhaps change between one clearly identified state and another, that three-way separation mostly worked OK.

But now let's say we're writing a modern web app with several different panes showing related information, and the user can drag some sort of sliding divider between panes to resize them. How are we going to represent the size and position of the underlying HTML elements with any combination of predetermined CSS rules?

We can't, because now we have continuously varying attributes for things like size and position values. Those are necessarily going to be set either by applying inline styles or by directly updating other (non-style) attributes of the relevant elements.

These dynamic aspects tend to be few in number, at least in my experience, and I still prefer to predefine most styling using CSS rules the same as always even when I'm working on a more dynamic and interactive page. But sometimes that literally can't do the job.

A related consideration that is also relatively rare but valid is that sometimes you want to specify values to use for things like dimensions or colour schemes, but for the same reason as above, you might want to know those values in both CSS and JS contexts. So far I've found this rare enough that I do just define a named constant in both contexts and add comments linking the two, and this has yet to cause any serious problems. However, it's perfectly reasonable to argue, as some do, that this is duplication and a maintenance hazard, and it's perfectly reasonable to explore different tooling that might overcome that duplication.

0

u/hash12341234 Dec 20 '16

One fundamental problem is that we can't separate HTML, CSS and JS completely with some of the more dynamic rendering requirements that we need to meet today.

What is an example?

→ More replies (2)

8

u/franksvalli Dec 19 '16 edited Dec 19 '16

That's because most of these folks aren't in the trenches. They're evangelists and speakers at conferences where they go and talk about stuff and best practices from when they were in the trenches years ago. Some of it's still applicable, some of it's not. (I could name a few names, but you can take some guesses)

I guess it's natural that these folks tend to be outspoken, but it does get annoying after a while. They bang the frontend best practices drum like it's immutable gospel truth. Why shouldn't best practices be re-evaluated every ten years or so? Things change - we should at least take the time to see what worked and what didn't.

But folks will continue to preach and make names for themselves as speakers and opinion-havers.

In all fairness to Thomas, this tweet of his is spot-on and hilarious: https://twitter.com/thomasfuchs/status/708675139253174273

1

u/Silhouette Dec 20 '16

There's an old saying that "the best is the enemy of the good". I think we'd do well to remember that one a bit more often. Or maybe just set auto-correct in our editors so that "best practice" gets turned into "pretentiously titled and excessively hyped screw-up-in-waiting" or something, so we're never foolish enough to describe anything important that way.

3

u/acbabis Dec 19 '16

Allow me to be the first person to explain how they think it should be done. IMO, Angular 1 does a very good job of Separation of Concerns with respect to HTML/CSS/JavaScript. The controllers are pure JS and the services only manage data. Yes, the templates have some JavaScript, but it's the bare minimum amount of coupling you can have between a view and a controller and still have the application be interactive. AngularJS applications generally use separate CSS files. This promotes semantic HTML and theme-ability, meaning you can have multiple layouts and colors without needing restructure your JavaScript.

2

u/GBcrazy Dec 19 '16 edited Dec 20 '16

Dude, you are missing the point.

We can still have multiple layouts, instead of having a styles.css file, we are having a styles.js file

.myClass
{
    color: blue
}

vs

var myClassStyle = { color: "blue" }

This example is just for the sake of simplicity, we don't have to declare anything global nowadays. We are going to import it and apply it inline. But if we want to make a change it's not on the component itself, and nor in its logic. It's literally the same shit, but we can use JS logic to inherit CSSs and create mixings and etc. We have a bit more power in some aspects.

By the way, JSX is really similar to angular templating. Instead of twearking html strings and adding fake directives, we are using html as objects, which gives us better DOM control overall...

4

u/parlezmoose Dec 20 '16

What about things like pseudoselectors and media queries? I've experimented with inline styles but found them to be unworkable in practice.

1

u/Dooraven Dec 20 '16

using aphrodite basically solves all that for us. https://github.com/Khan/aphrodite

3

u/[deleted] Dec 20 '16

Good luck getting modules like this maintained for longer than 2 years.

1

u/Dooraven Dec 20 '16

Agreed, plus two years is huge in terms of web dev- though considering Khan and Airbnb both use it in production sites, I'm pretty comfortable with using it for us in production so far, it's made our codebase of components super easy to maintain

3

u/[deleted] Dec 20 '16

Oh i'm sure it works well now and that big companies use it so its a bit better maintained than others. But like i said: i still need to provide support in the future on projects i did ages ago. And while it might work fine now, i still need to work with it in the future. Having to require various modules to accomplish tasks/features/hacks is not what i can really advice to my managers of which we should use.

Also having big corporations using them is nice, but is hardly a guarantee that it will last. Those big corps (especially the big startups you mention) are often switching around because they are still looking for that optimal way to do things. I wouldn't be surprised that they move on to Vue or something else in the future as well

2

u/Dooraven Dec 20 '16

That's just the nature of web dev though - modern stack changes. Sites and applications get written and rewritten again and again.

I agree with you entirely that nothing is a guarantee because in webdev every thing changes.

3-4 years ago LESS was considered a primary stylesheet precompiler. Ruby on Rails was the hot tech stack etc. Go back even further and you have Flash/ActionScript sites entirely.

You should pick something that solves problems for your team. If it's older tech, then use that (we still use jQuery a lot in our React/Redux/Webpack/Aphrodite websites). If it's bleeding edge tech then use that. There are caveats and drawbacks for each technology you choose - you just have to weigh the risks and benefits.

1

u/parlezmoose Dec 20 '16

Nice! I'll check it out

→ More replies (5)

2

u/[deleted] Dec 20 '16

You're right on the money on all of this, but I still prefer regular CSS over js objects. :x

1

u/[deleted] Dec 20 '16

I already see that you add quotes and probably other stuff to make it behave in Javascript...

1

u/azium Dec 20 '16

Is adding quotes a problem? In exchange for quotes we get runtime css functions

let button = color => ({
  border: `1px solid ${color}`,
  padding: `5px 3px`,
})

1

u/[deleted] Dec 20 '16

Still not sure why you would prefer inline css over external css file. Especially when debugging the dom is much easier to read if you keep it simple with classes. Also: how many symbols do you really need for your code? It feels like soon we need to start remembering all kinds of alt+codes in order to write some Javascript because somebody found "æ" to be a handy bootstrapper name.

2

u/fnovd Dec 19 '16

Angular 1 does a very good job of Separation of Concerns with respect to HTML/CSS/JavaScript.

Angular 1 was so flawed that 2 is basically a different framework. The creators themselves decided the project wasn't worth maintaining as-is.

4

u/acbabis Dec 20 '16

Yes, but I don't think separation of concerns was the reason why. The concept of templates and controllers still exist in Angular2, just under different names. Here's a snippet of code showing how template, logic, and style are still separate in Angular2:

https://angular.io/docs/ts/latest/cookbook/a1-a2-quick-reference.html

@Component({
  moduleId: module.id,
  selector: 'movie-list',
  templateUrl: 'movie-list.component.html',
  styleUrls: [ 'movie-list.component.css' ],
})

2

u/[deleted] Dec 20 '16

I think there's more to it than that. They wanted to utilize the power of ES6+ which required a rewrite anyways (like with all ES5 projects).

1

u/edwardmsmith Dec 19 '16

Great! So, what would the ideal Angular 1 version of the linked example look like?

5

u/ECrispy Dec 19 '16

If you really think about it, DOM is an implementation detail and should really be opaque.

We've been dealing with it directly because that was the only way, and browsers are optimized for it.

Virtualdom is also an implementation detail and is strictly not necessary.

Templates and HTML snippets are a bridge to the browser world. Technically you could write a version of react or any other lib that takes any component definition syntax and internally generates markup. It's just that HTML happens to be the most familiar and popular markup.

5

u/Zinlencer Dec 19 '16

This sums it up pretty well: https://youtu.be/gsffg5xxFQI?t=27m59s.

Instead of seperation by concerns we get data in -> component out, in my opinion this is much easier to reason about. You can just use default javascript instead of reinventing the wheel with some sort of template syntax.

0

u/[deleted] Dec 19 '16

[deleted]

1

u/PitaJ Dec 20 '16

Yeah I don't think OP was saying that the way that ClojureScript does it is the best way, but that what the guy in that talk is saying is applicable to both templates vs JSX and templates vs CJS

4

u/Daniel15 React FTW Dec 20 '16

I can't see the tweet because Thomas Fuchs blocked me a few years ago, for reasons I still don't understand (I probably said that MooTools was better than Prototype)

You are blocked from following @thomasfuchs and viewing @thomasfuchs's Tweets.

Cool.

1

u/syropian full stack @ felix health Dec 20 '16

I'm pretty sure I've never interacted with him, and he blocked me. lul.

15

u/PickerPilgrim Dec 19 '16

I mean you literally can't have dynamic content without mixing HTML with a language of some sort, and this is an example of React from a tutorial without Redux or another state management tool. I'm sure I could cherry pick some horrid example of whatever this guy's favorite library, framework or pattern is.

9

u/[deleted] Dec 19 '16

Having written Javascript for the last 20 years, I'm quite surprised that someone wouldn't know who Thomas Fuchs is, I suppose that says more about me than you, however.

You whippersnappers and your frameworks.

*edit: comma

4

u/franksvalli Dec 19 '16 edited Dec 20 '16

No more surprising that few people know what scriptaculous is. No one seems to have mentioned it here yet.

I think this really is a generational thing. The old folks want to keep doing things the way they know how, because that's worked for them all their lives, and that's how their generation agreed to do things.

The young folks recognize that model worked ok, but want to try new and exciting things that may end up being just as good or better. And they want to make a name for themselves in the process, and in order to do that, you have to create new stuff.

Then the old folks kneejerk against the new unfamiliar stuff as if the kids are idiots. Because what reasonable person would ever go against the gospel truths established by the parents' generation?

6

u/themaincop Dec 20 '16

I think this really is a generational thing. The old folks want to keep doing things the way they know how, because that's worked for them all their lives, and that's how their generation agreed to do things.

I honestly think it's more a representation of how much of a role Javascript plays in your day to day programming life. If you're mainly a server side coder who writes a bit of JS here and there to spice up your Wordpress themes you're probably looking at the past two years of Javascript and thinking "why are they ruining this thing I was starting to understand?"

If you're primarily a front-end dev who has been running up against the limitations of Scriptaculous, and then jQuery, and then Backbone, and then Angular, you're probably thinking "oh thank god libraries and frameworks that just do the things I need are starting to come out in droves."

3

u/Senthe Dec 20 '16

This is just not true, Angular vs React vs Ember vs Vue is not some random people battle, it's purely front-end devs' battle.

2

u/themaincop Dec 20 '16

I don't see Angular vs. React vs. Ember vs. Vue as a battle at all. In a sense I know they're all competing for mindshare, but as someone who hitched their wagon to React I don't feel threatened by the emergence of Vue at all, because it's based on concepts I understand and if it looks like the community is going to make a big shift over to Vue it won't be a big cost for me to learn it. Anyone putting a lot of thought into writing Javascript applications is doing good for the ecosystem as a whole.

The battle that I'm seeing is procedural jQuery vs. learning a real Javascript toolkit. What I see a lot are devs who felt pretty good about their Javascript ability taking a look at the landscape and realizing they've been left behind. I know the feeling, two years ago it was me, (semi-)happily writing so-so jQuery in Coffeescript classes, keeping state in data tags, separating all my concerns like a pro dev, and never giving a thought to all this flash in the pan stuff like gulp, bower, Angular, knockout, React, ES6, Javascript modules, etc.

I wasn't the type to really get upset about it, I just ignored it until it clicked in that I needed it if I was going to build better products. But a lot of people in the same position are seeing all this stuff, feeling bad that they don't know what any of it means, and then lashing out at "hipsters" and "hype" because that's mentally less daunting than realizing that you have a lot of learning to do if you want to stay current in your profession.

1

u/Senthe Dec 20 '16

Lol I don't know who are you working with but I certainly don't see people who argue jQuery is the best way to do frontend around here.

2

u/themaincop Dec 20 '16

Try subscribing to /r/frontend or /r/webdev, it comes up every couple of weeks. If you use webpack you're a hipster, if you're interested in Vue you're a sucker for hype, yadda yadda. It's not a big majority opinion, but they're out there.

14

u/deadcow5 Dec 19 '16

The thing is, this is not a horrid example, this is literally what's considered "best practice" these days.

7

u/tidder112 Dec 19 '16

From my experience, it appears that "best practice" is throwing spaghetti against the wall and whatever sticks is acceptable.

3

u/deadcow5 Dec 20 '16

Sadly, it seems you are right on the money.

2

u/PickerPilgrim Dec 19 '16

Not really though. This example is setting state in a component rather than using Redux. Writing React without Redux or something similar certainly wouldn't pass for best practices on my projects.

13

u/[deleted] Dec 19 '16

Then your team doesn't know what the best practices are. Even the creators of Redux and React constantly point out that you don't have to use Redux, and using component state might be fine depending on your situation. Here's Dan Abramov (co-creator of Redux) reinforcing that same point just today. I didn't even have to scroll down on my twitter feed to see this.

People like you are the reason we see so many people express their distaste towards these programming guidelines and practices. You see a solution, try to apply that solution to literally everything without any common sense, and when that inevitably doesn't work, you conclude that the practice is bad, when the correct answer is that you're trying to use a chainsaw to cut a piece of paper.

3

u/PickerPilgrim Dec 19 '16

Ok fair enough. Component state doesn't make sense on any React project I'm involved in. The To-do example is simple enough to get by without it. It's also simple enough to get by without obsessing over separation of concerns as in the original tweet. I shouldn't have implied that not using Redux is wrong. But if you care about separation of concerns, component state probably looks pretty ugly. I still think it's silly to post that example of mixing JS and HTML as if it has set back years of progress.

4

u/[deleted] Dec 19 '16

I still think it's silly to post that example of mixing JS and HTML as if it has set back years of progress.

Oh, definitely, I can't argue with that.

I don't agree that component state gets in the way of separation of concerns though. Even without redux, you can make a container component that concerns itself with only managing the data, and passes it down to other components that concern themselves with displaying that data. Just because both of those concerns are solved with React components doesn't mean they're not being separated. What's wrong with this code, for example?

class App extends React.Component {

	componentDidMount() {
		this.loadCats();
	}

	loadCats() {
		fetch('/api/cats').then(res => res.json()).then(res => {
			this.setState({ cats: res })
		})
	}

	render() {
		return <Cats cats={this.state.cats} />
	}
}

class Cats extends React.Component {
	
	render() {
		return this.props.cats ? (
			<div>
				{this.props.cats.map(cat => <div>{ cat.name }</div>)}
			</div>
		) : (
			<Loading />
		);
	}
}

3

u/PickerPilgrim Dec 19 '16

That makes total sense. The pattern of distinguishing between containers and presentational components is in my mind associated with Redux, but it doesn't really belong to either library it's just a standard to adhere to.

1

u/[deleted] Dec 20 '16

Code samples like this look fine but thats because they don't really hold any value for real world use cases. where are the exceptions to display x or y? Where are the different stylings for certain cats? And where the hell is the comment explaining what you are doing and why?

Add all these things and it becomes much more complex and more difficult to read.

2

u/ECrispy Dec 20 '16

Its true that state is best left outside components, esp for large projects.

Redux is an amazingly boilerplate heavy solution to this with tons of meaningless mechanical code and is a total mess without using a hundred additional libs such as thunk/saga/reselect/middleware etc. This is not good engineering.

React is successful because of its big scope but small api surface area. We need a better abstraction than Redux. e.g. I think an immutable graph data struct should have been the default React state representation, thus making the whole thing far more efficient without needing shouldComponentUpdate.

1

u/PickerPilgrim Dec 20 '16

That makes sense. The boilerplate is a bit obnoxious to write in Redux, but FWIW, the boilerplate is clear and easy to follow I find it makes for pretty handy documentation when I'm debugging.

1

u/spacejack2114 Dec 20 '16

IMO the todo list, while trivial, isn't unrealistic. An app may be made up of a lot of simple components with localized state.

1

u/PickerPilgrim Dec 20 '16

I don't doubt it. I just haven't encountered that use case in my work, having a single store has been critical to the React apps I've worked on.

1

u/deadcow5 Dec 19 '16

If the only tool you have is a hammer, every problem tends to look like a nail.

0

u/SamSlate Dec 19 '16

whatever this guy's favorite library, framework or pattern is.

vanilla javascript

3

u/e_man604 Dec 19 '16

Well, you can still design it MVC style. Where jsx (HTML + js) is the view. The CSS part is probably still external anyhow.

3

u/dmitri14_gmail_com Dec 20 '16

If you don't use components, inline styles and javascript do not scale, nothing changed here. But with components they do, which is why the old best practice does not apply.

3

u/hellectronic Dec 20 '16

I think this comment from Rob Eisenberg on Hashnode, is good answer to this.

7

u/franksvalli Dec 19 '16 edited Dec 19 '16

Separate HTML (content), CSS (styling), and JS (functionality) is a mantra I've heard since the beginning, usually a drum banged by outspoken folks like Zeldman.

In theory this sounds nice, but in practice it actually makes the job harder, as you often need to hunt down the relevant HTML, then the relevant CSS, then the relevant JS. And to fix problems or implement new features, you will end up probably touching all three at once, and switching between them a lot, as explained in this video: https://www.youtube.com/watch?v=0ZNIQOO2sfA

At the root of the "separate HTML, CSS, JS" philosophy is the separation of concerns, which I think is common ground here. Most folks agree with separating concerns, especially since more functional-style programming is becoming popularized in the JS community.

I think the disagreement here is over what a "concern" is. In the case of the React code author, they may imagine that their "concern" is the TodoList itself. It's a unit of code that depends on a specific HTML structure, requires JS to function, and has some minimal styling, still allowing for different CSS themes. This is just how things are in reality: no matter how you structure your code, your JS needs to know where to hook into the HTML (with ids or classes), and your CSS also needs to know where to hook into the HTML (with ids or classes). Sometimes your JS needs to be able to read out properties applied to HTML elements via CSS.

E.g.

HTML <-> CSS

HTML <-> JS

JS <-> CSS

Everything is interlinked.

In the real world, we think of "concerns" as things that usually require HTML AND CSS AND JS. For instance, if a coder needs to add new button functionality to a form, they will have to 1) add HTML for the new button, 2) add new styling for the button, and 3) wire up the button to JS. Bug fixing may involve any combination of the three.

In Thomas' world, the code maintainer will need to hunt through the TodoList code in three artificially separated, but implicitly interlinked contexts. They will add the button HTML, then add the CSS which implicitly relies on the HTML being structured a certain way, then add the JS which also relies on HTML structure.

What's stopping us from thinking of this TodoList itself as a concern, and keep it separated from other app concerns (other modules on the page)? The TodoList is one concern with the HTML/CSS/JS inescapably intermingled. I'm not saying React is necessarily the best way to do this. Polymer seems to have the same concept of bundling together these little modules (what used to be called widgets in bygone days).

Would honestly be interested in rational criticism of my view, and why "separate HTML / CSS / JS" still holds up.

2

u/Senthe Dec 20 '16

They're still separate technologies and I think it's important to recognize that they are very different and handled by browsers in entirely different ways. It lets you understand what will be efficient.

2

u/adenzerda Dec 20 '16

Does tabbing between files (or arranging them side-by-side) really take up so much of your day that this is a major concern? And having to "hunt" for things only tells me that your project structure isn't sensible.

There are many arguments to be made for the new way of doing things, but this one seems silly.

6

u/KPABA Ham=>Hamster == Java=>JavaScript Dec 19 '16

has it taken two years for the creator of Prototype.js to chime in on jsx with a contrived example? I find that somewhat ironic, given how Prototype extended natives and was new and controversial and whatnot, yet it helped change JS

8

u/[deleted] Dec 19 '16 edited Dec 19 '16

This example actually contains no HTML, and no CSS either... What ends up running on the browser is all JS........

A nice way to represent what eventually comes down to the DOM api is a good thing no?

2

u/Slogo Dec 19 '16

I wonder how many people who are yelling about seperation of concerns are using an MVC framework and writing HTML-based templates on top of that.

I would think grouping the same concern should be as important as separating different ones.

2

u/jbscript Dec 20 '16

FYI, the code in this hot take is from the front page of the Preact website (notice that props and state are being passed to render(), which isn't the case in React):

https://preactjs.com/

2

u/Helvanik Dec 20 '16

This is just syntaxic sugar. Behind the scenes, JSX is plain JavaScript. So JS is still separated from HTML.

0

u/[deleted] Dec 20 '16

[removed] — view removed comment

1

u/bart2019 Dec 21 '16

Right. We'd rather see the opposite: separate sources and merged into a single delivery file for the browser.

5

u/sallark js/beer Dec 19 '16

But keeping them in separate files doesn't automagically make it better.

3

u/amdc !CURSED! Dec 19 '16

4

u/dwighthouse Dec 19 '16

15 years trying to convince programmers to do something when they don't want to? You need a more interesting hobby, preferably one with a chance of success.

3

u/eggsandbeer Dec 19 '16

Old man yells at cloud.

2

u/griffin3141 Dec 20 '16

My concerns are components, not style/markup/javascript.

2

u/parlezmoose Dec 19 '16

It's so much better this way.

1

u/spxctr Dec 20 '16

i don't see any css in there. that component's about to look REAL shitty...

1

u/neoginn Dec 20 '16

OP - check out web components/polymer, it will make you happier.

1

u/Jarzka Dec 20 '16

2 years of ClojureScript and everything makes sense once again.

1

u/FoldLeft Dec 20 '16 edited Dec 20 '16

Separation of languages is easier to recognise than separation of concerns, but the latter was always the goal. He just hasn't realised that yet.

1

u/Nerdenator Dec 20 '16

I'm fairly new to this whole thing the kids are calling "world wide web development", but I'm sitting here re-writing a website front-end that runs on a Django back-end at a company where large portions of the developer community would probably take RoR as a spouse if the laws in Missouri and Kansas allowed it. They also love the idea of building out UI and layout helpers with the back-end.

From where I'm sitting, React is Turing Prize-worthy, because our big UX/UI resources project will be open-sourced and done in React. No more conflicts between RoR and Django projects... we turn the back-end interface into an API, make React components that consume and manipulate that data, and slap it all together using a common, defined toolkit (Webpack, NPM, ESLint, etc.) which eliminates a lot of second-guessing on my end. It also eliminates a lot of jQuery and formalizes the manipulation of state in the application.

Maybe I'm missing something here (probably, I haven't been in this game as long as most of you), but... if we can eliminate the intermingling of back-end concerns and make reusable components that fit into a common design framework as a company, that's a massive win.

1

u/syropian full stack @ felix health Dec 20 '16

The author of that tweet apparently blocked me on Twitter, and I've never interacted with him at all AFAIK :/

2

u/franksvalli Dec 20 '16

Got to maintain that filter bubble

1

u/angus_the_red Dec 20 '16

Yeah we are!

1

u/gleno Dec 20 '16

Because this is the most efficient way, when you can create component abstractions. Basically when there's just a screenful of code per component, and the idea is to compose components with no side-effects - just jamming all kids of code produces terse apps that are easy to manage.

1

u/NatteringNabob69 Dec 20 '16

The vast majority of our JSX components are pure functions that take props and return react elements as JSX. Most of our business logic and state management is implemented in Redux and Redux-Saga.

In the few cases where a component manages its own state, there are local functions in the component that handle UI events and state transitions. This logic is entirely linked to the specifics of that component, and is in no way shape or form re-usable. To pull that logic out of the component would just move it someplace else, and create a 1-1 association between the component and its associated logic. This is not separating two concerns, this is dividing a single concern into two files.

1

u/bart2019 Dec 21 '16

Enterprise idiots have taken over Javascript and are enforcing their madness onto the rest of us.

1

u/temp60498230982 Dec 20 '16

Christ, this again. It's frustrating how little people think about this before taking a stance then sticking to it come hell or high water.

Just answer this. Why do you separate HTML, JS, and CSS? Because you do what you do because it's what you do? No, you're a logical person, you see benefits. Write them down, make the list good and complete so you won't want to revisit it. Now, look through a project written in the style of the above code. Does it lack those benefits?

1

u/ScoopDat Dec 19 '16

That snippet is impossible for me to understand. So much dissection needed as a noob :(

3

u/themaincop Dec 20 '16

You'll get there!

1

u/gaoshan Dec 20 '16

I don't see any HTML or CSS in that code... just javascript (and JSX).

1

u/spacejack2114 Dec 20 '16

The question is why are people trying to write Javascript in XML?

1

u/g00glen00b Dec 20 '16

I come from a Java/PHP world so I asked myself that as well when I first encountered React, because things like this were considered bad practice in those languages:

<?php for ($i = 0; $i < 10; $i++) { ?>
    <span>foo</span>
<?php } ?>

Many people say that "it's JSX, so it's actually OK because it's all JavaScript". In my opinion, that's wrong, because both JSP and PHP are just "Java" and "PHP" as well. However, the main difference between those and React is that we're now evolving to component-driven design, so we just chose to separate in a different way.

I like the component-driven design, though even with components, I still prefer to separate my logic as much as possible from my view, so I guess that's why I prefer Angular/Aurelia/..., though I completely understand why React went the way they did.

0

u/lhorie Dec 20 '16

Seeing lots of the old "React-is-maintainable" parroting here, but I think Thomas has a point: fat components are relatively common in the wild, and not good for logic reusability, and css-in-js is neither composable nor reusable. Although React can help write better code, it doesn't automagically make everything better (and it's still quite possible to jump on bandwagons that don't apply to you, and write bad React code)

It'd do a lot of people good to remember that questioning "best practices" is a requirement for continuous improvement, and that remains true even after React came along, and will remain true after the next big thing comes along.

4

u/jdauriemma Dec 20 '16

I agree with everything you said, except the idea that somehow styles expressed as JS objects a la react aren't composable or reusable.

// buttons.js
export const button = {
  backgroundColor: 'gray',
  borderRadius: '3px',
  padding: '.5em 1em'
};

export const primaryButton = Object.assign({}, button, {
  backgroundColor: 'blue';
});

export const warningButton = Object.assign({}, button, {
  backgroundColor: 'red';
});

2

u/lhorie Dec 20 '16

Yeah, sorry, I should've qualified that I meant coupling the css to a component (e.g. like in .vue files), following logically that the OP was taking a stab at monolithic components.

While your example is technically code reusability, it is so in the same way cascading and OOP inheritance is. Personally, my gut tells me that's the wrong direction to go to. Tachyons for example take a completely different (and better, imo) approach.

-1

u/phantom-of-the-oprah Dec 19 '16

12:45 restate my assumptions: 1) web development is crazy and 2) some web developers are retarded sometimes. My hypothesis: these web developers make things needlessly complex so they look smart because HTML and CSS aren't programming languages and real men program in C++.

Evidence: In $year_before_web_2_0 I'm taught that it's a good idea to write my code in 3 separate files because separation of concerns. This seems crazy to me because now I must read and write in at least 2 or 3 files to get anything done. Then in 2016 I'm yet again finding bugs because I'm not a computer and I can't keep track of so many class names across so many files without typos and I'm going to cry if I have to type !important one more time. I propose experimenting with the new ideas and tools that have become popular in recent times but it's shot down by various wisemans because lol css in js and separation of concerns. 12:50 hit return.

1

u/eyko Dec 20 '16

I'd just urge developers to develop some critical thinking skills. They shouldn't blindly follow dogma. It would avoid most rants...

-5

u/daliz Dec 19 '16

This "new style" is a horrible mess and I can't wait for people to realize it's completely f***ed up. We need something else.

4

u/turtlecopter Dec 19 '16

This "new style", specifically, is ReactJS. And, depending on your application's complexity, it's actually incredibly useful.

-1

u/daliz Dec 19 '16

Yes, I know React and React Native. I'm not denying how useful and convenient they can be. I just think they will need to go under serious redesign in the next major releases, because right now they are destroying years of best practices.

2

u/DOG-ZILLA Dec 19 '16

And what does that matter if you get the job done quicker, better and less buggy? Better for everyone all-round! I'd say 'best practices' perhaps need updating.

2

u/daliz Dec 20 '16

And still, I have the feeling in two years nobody will talk about React and I hope people will remember their down votes to my words ;)

→ More replies (1)

-4

u/Javlin Dec 19 '16

I'm going to pretend this didn't happen. I was never here.

0

u/ttolonen Dec 20 '16

Yeah, I think that's kind of true that the React -approach is not the best possible way. But it is hard to create components if they do not maintain some kind of state, which usually requires also state of the UI visuals. It's pretty hard to create a usable component without any visual system or local model.

You can and maybe you should separate those, but the code is not as pretty and the components don't "feel" as modular, because they have so much external dependencies. The better solutions are yet to come and they most likely can address this separation of concerns in a totally unexpected way we currently can not imagine even.

The problem with React is that it introduces a tight coupling between a framework, language and environment. You don't see that before you start to think about how to port the code to some other system, perhaps a native system or similar. If you compare that to for example HTML standard. You can take any HTML editor and edit text, components and visuals using that editor and move the same code to some other editor on almost any platform. You don't need to bundle any support libraries with it, it is easy to parse and understand everywhere. However, if you take a React -component, it is possible that you can not open that in HTML editor and you can not run that component in your browser even without some pre-compilation process, which takes care of the JSX. If you have CSS embedded in the React components, the standard CSS processors do not understand what to make of it. And what is worse, it has also the functional javascript included, carrying the runtime requirements with it like the worst kind of ... like a PDF with macros or something as evil as that. It's horribly not portable.

So, with React -approach you kind of throw away years of standards development and replace it with your own development "convenience". Some people have argued that momentum for the open standards development has died some time ago. And maybe there is no need for them, perhaps we can live fine so that we follow big corporations and the API's they provide to us. I don't know, that's just one possibility of the many possible universes.

Personally, I believe that open standards should win and they will win, but to create something new sometimes there is also need for intermediate approaches and React is a perfect example of technology that has shaped the landscape for new ideas and possibilities.

0

u/klemenkeko Dec 20 '16

Vanilla.js guys I recommend this framework, so much customization and all, it's simple, nice and you can do everything.

-6

u/pagalvin Dec 19 '16

I was saying almost exactly the same thing to a colleague the other day.