Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
When or If (meyerweb.com)
131 points by todsacerdoti on March 14, 2022 | hide | past | favorite | 93 comments



Allow me to recommend "perchance", to make it sound extra fancy:

    @perchance supports(display: grid) as-well-as media(min-width: 33em),
      @why-then-of-course:
      {
      }
    @on-the-other-hand
    {
    }
Seems obvious, really.


   @perchance ...
     @thusly {}
     @contrarily {}
:)


Reminds me of the "essays" I wrote in English classes/technical reports. Full of fluff and no substance, just to sound fancy.

It took me a while to learn that writing is not just putting words together and filling the page, but actually to tell something, to convey an argument. That meant learning to get rid of all unnecessary conjunctions and keeping it simple and clear.


I had an "audience" problem in English class.

My teachers all knew whatever boring book/topic backwards as we'd all just spent weeks discussing them in class. Now go write an essay!

Knowing my audience, I skipped the details, got the concepts right and put it down in a page or less because I know my teacher knows the details so I don't need to rewrite them.

Consequently, I didn't do well in English class.


Every once in a while I'm tickled by an author who manages to juggle ornate prose deftly.


There is a precedent for this: British PHP.

https://aloneonahill.com/blog/if-php-were-british/



We could even - shock horror - use a non-English word like `si` or `kama`.


What about "while"?


I don't think the CSSWG should care one bit about Sass's syntax. Just use if...else if that's what makes sense (and I think it does make sense). Sass is interpreted into CSS, so CSS is the authoritative language, and Sass is a derivative.


Yes, sass should change now that css will support conditionals.

sass stepped on css' toes by reusing the @xxx syntax from css instead of creating their own syntax.


> sass stepped on css' toes by reusing the @xxx syntax from css instead of creating their own syntax.

Yes and no - they're accepting that there may be future compatibility breaks (like this very case) but using some arbitrary other glyph as a marker is also dangerous. Whenever you're working on a second layer tool you're limited in how much future compatibility you can guarantee (and the limit is 0).


A given piece of working SASS never has to have a compatibility issue, because it's processed through SASS and the SASS goes away. (Only some backward-incompatible upgrade to SASS can break the code.) The fact that CSS evolves to introduce constructs that look exactly like SASS doesn't in and of itself break anything from the point of view of the old code which doesn't use those new CSS constructs.

SASS code is written in the SASS language, with CSS as a back-end; the only thing that can break a piece of existing SASS code (in terms of making it either fail to generate, or generate different CSS) is a backwards-incompatible upgrade to the SASS processor. For instance, someone has SASS code which relies on certain @-things to be passed through to CSS, but an upgrade to SASS claims some of them for itself.

(A change in CSS could break the generated CSS code, which is a different issue.)


To the extent that SASS wishes to remain a superset of CSS, and/or allow expressing any possible output CSS, a change in CSS can break that aspect of SASS and force SASS to make an incompatible change if it wants to preserve those properties.


It’s not just @-rules, but also other things like functions, where they’ve introduced their own that end up definitely incompatible with CSS and it’s just no end of pain as you try using now-ordinary CSS features and discover that a technical decision made fifteen or more years ago prevents you from doing so. (The deprecated LibSass is significantly CSS-incompatible; Dart Sass, I’m not sure: even a year ago it was still significantly incompatible, but they have definitely landed some important fixes since then so that it’s possible that their long-standing claim on https://sass-lang.com/ that “Sass is completely compatible with all versions of CSS” is no longer a blatant lie.)

I think most of the trouble is actually that Sass accepted the theoretical compatibility breaks on behalf of their users, who didn’t realise they were signing up for this, and end up discouraged when breakages happen and they have to resort to ever weirder and wackier workarounds that should work but somehow break things in some other part of their toolchain, et cetera ad desperationem.

I think it would have been much better if every piece of Sass syntax had used been clearly denoted by the use of the $ symbol ($@ instead of @ for its at-rules, a $ prefix on its functions, &c.), except probably for nesting (though not bare mathematical expressions, I’d force them to be wrapped in $(…)—they’re the worst to find when trying to port away from Sass syntactically rather than compilationally). $ was and is not used by CSS and could probably be agreeably reserved for such tools, and even if not, the unquestionable superiority for tooling (that it makes identifying Sass rather than CSS parts of the stylesheet textually trivial rather than absolutely requiring a compiler that is unlikely to be designed for general tooling use) would even make switching from $ to something else (e.g. a -sass- prefix, which would also be a reasonable choice, though slightly more verbose) genuinely easy.

But of course, that ship has long sailed, and I have no time machine.


Sass should just have been a python (or your fav lang) library. Express the entire CSS as objects and then finally compile it. There was no need for yet another DSL. DSLs seems like the easy way out but it puts a lot of burden for users to learn it. It is pretty compact and clean though. So there's that.


It saddens me whenever a core web spec picks a sub-optimal solution purely because a 3rd party tool already picked the optimal one.

I find it ironic that the css "when/else" draft spec uses "if" for describing the conditional scenarios in plain english. As if the spec itself admits the syntax they are choosing is clearly sub-optimal.


Would if/else have been considered optimal to you if you hadn’t already been conditioned (ha!) that way by other programming languages?

“When” actually seems better in a purely declarative language.


Maybe it's prior exposure to lisp, but I wouldn't expect "when" to have an "else" clause. Can't think of an idiomatic natural-language case with that structure either.


I have never used SASS and if/else is obviously better than when/else.


It was the same with Array includes and contains, wasn't it?


Also, Array.flat was chosen instead of Array.flatten because of a popular 3rd party library's function of the same name. I think it was Lodash.



... And underscore/lodash use the _(...) wrapper approach pioneered by jQuery’s $(...) precisely to avoid monkey-patching builtin objects like Mootools did (as well as some others I think, but I don’t really remember).


PrototypeJS also had the monkey-patch approach.


I initially thought that “if” should be the obvious choice, ignoring sass entirely. However, it’s clear that “when” makes more sense than “if” given CSS’s interpretation anyways. “if” sort of implies a more “one-time” use like in a template/macro or preprocesser. “when” really captures the temporal invariance of CSS’s conditionals.


I think it's fair to acknowledge the clash, but "if" is our word for that thing - "when" could have been that word - every time you do a conditional jump you're only doing it when certain conditions are met "when x > 5 { y += 3; } elsewise { y -= 1; }" that reads perfectly fine - but it's common convention to use "if" for this condition.

I don't really have a strong opinion on the when vs. if fight w.r.t. yielding support to SASS but I think that "if" is just a better keyword to use in this instance based on language usage alone.


I think the difference is that, if x later becomes > 5, y doesn't suddenly get increased by 3.

By contrast, in CSS, if the condition later becomes true, the declarations in it do start to apply. So I also think "when" (in the sense of "whenever") makes more sense than "if".


CSS is evaluated (probably) in some sort of event loop in the browser - you can also evaluate the code I included above in an event loop - there is nothing inherently instantaneous or continuous about CSS and, given that it is deterministic, it's only actually recalculated on certain event triggers.


I think `when` would be a good name for this even if Sass didn't exist - CSS is not a procedural language, it is a flow language. That is, the conditional block is applied reactively to the condition changing, not just the first time the file is evaluated. Sass's usage of `if` is the latter, which is how a programmer intuitively thinks about `if`, and since the CSS construct is the former, it makes sense to use a different word to highlight that there is a difference.


There are many non-procedural languages or environments that still have 'if'. E.g. SQL's IF-THEN-ELSE, XSL's 'xsl:if', or C preprocessor's '#if'. Is there a language similar to CSS that uses something different than 'if' to solve a similar problem?


All of those things are procedural in exactly the way I described. SQL is the very definition of procedural, I don't know what you're getting at there. Each thing you mentioned has an `if` statement that runs at one defined point in its execution. If it executes multiple times that's because it's part of a construct that runs everything inside it multiple times. XSL is the closest thing to a CSS-style rules engine, but you still use it once to create a new document, whereas the CSS rules are reevaluated live as anything about the context changes.


> SQL is the very definition of procedural, I don't know what you're getting at there

I assumed you were referring to programming paradigms. "Procedural" is part of the "imperative" paradigm [1]. "declarative" is different from "imperative" [1]. SQL is, for the most part, "declarative" [2].

> If it executes multiple times that's because it's part of a construct that runs everything inside it multiple times.

How is that different from CSS? Aren't CSS rules also part of some larger construct and they get run multiple times (i.e. once the context changes)?

[1]: https://en.wikipedia.org/wiki/Programming_paradigm

[2]: https://en.wikipedia.org/wiki/SQL


As an outsider to web development, @when would be a weird choice. If CSS wants to enable 3rd party tooling to take some of the syntax space, then it should declare some parts of the syntax never to be taken by core CSS (if it's not already done this way). Then this syntax clash would never be a problem between a 3rd party tool like sass and CSS.

In this case I think it's on sass to introduce the awkward workaround on the syntax clash.


I'm not sure whether arguments about other programming languages are relevant - most of those aren't declarative style sheets that operate under changing conditions. @when block may suddenly start to apply when the user resizes browser window, that name isn't as awkward as it may seem without context.


Fun fact: when and if have two completely different meanings in Yu-Gi-Oh. "When" means that an effect has to happen precisely after the trigger (so if some other mandatory effect happens in between, the "when" effect doesn't happen). "If" is much more flexible and just has to be on the same stack as the triggering effect.


Do other tabletop games use different definitions? I ask because I've always assumed this to be the operative distinction when reading rule books, but, come to think of it, I can't necessarily defend that assumption.


Semantically, "when" and "if" describe different modes of thought even in everyday English.

"When" usually describes an event that is likely to happen in some future time. "If" describes something that may or may not be true.


   @case {
      supports(display: grid) and media(min-width: 33em) {
       
      }

      otherthing(arg: whatever) {

      }

      otherwise {

      }
   }
You're welcome.


Are @switch, @case and @default available? Because that'd be even more in line with general programming language knowledge.


Note that you don't need any @ sigil inside this @case because it contains condition { CSS } pairs; where something like "default" or "otherwise" can be recognized as a special condition word without a sigil. Selectors do not appear there; "otherwise" isn't syntactically a selector for some <otherwise> tag.

I got it down to one @ sygil to write a long conditional ladder with any number of conditions and a default.

It could be called @cond, in the Lisp style; not a lot of people know that though.

The first condition that is true fires; the rest are then ignored, so the order of the cases matters. Many languages call that sort of thing using "case" terminology.

Probably a diagnostic in the browser console is worthwhile if the always true "otherwise" condition is followed by anything.


Not a native English speaker, but I learnt that if and when have different meaning and also to translate them to different, non-interchangable words in my mother tongue. The Cambridge dictionary seems to support that view:

"We use if to introduce a possible or unreal situation or condition. We use when to refer to the time of a future situation or condition that we are certain of."[1]

Could you really replace the if as used in a programming language context with when?

To me, when doesn't make sense in that context at all, but again, English is not my first language.

[1] https://dictionary.cambridge.org/grammar/british-grammar/if-...


It's kind of interchangeable if you consider not a single execution of your program/method, but every execution of your program/method.

When you run it with "this" value, it'll do "this". When you run it with "that" value, it'll do "that". Because, eventually, all code paths will be run.

It would also be semantically valid to say: When you execute this program/method, if the value is "this", do "this".

At the end of the day, English rules are more what we like to call guidelines.


That makes sense indeed. I think what you described is the declarative viewpoint whereas I was thinking strictly imperative, where we are talking about a decision in one particular moment.

> At the end of the day, English rules are more what we like to call guidelines.

Tell that to my English teacher;-)


As a native English speaker I'd say that's spot on. In particular, at least in British English, 'when' is never paired with 'else' - you might instead pair 'until' and 'when' and I suppose one could contort oneself into making a case for those keywords to create havoc!


Also a native english speaker.

I was about to disagree with you, that we use "when" when several things might be true, but then I realised that in those cases each of the possibilities will happen, but at different times, like "when the light is read you stop, when it is green you go".

It's fascinating how many quite subtle rules you internalise about your native language without realising it.


We even have little jokes based on the subversion of this expectation.

Developers will stop arguing about arbitrary syntactical nuances when pigs fly!


How about

  when light_is_green {
     go
  } when light_is_red {
     stop
  } otherwise {
     go_very_fast
  }
:)


‘If’ is never really paired with ‘else’ in natural language either.


Maybe I misunderstand sass, but wouldn't they be able to just remove their specific "if" implementation and just allow sass users to use the CSS "if" implementation?

Will the two "if" implementations have dramatic differences in how they act?


There are indeed significant differences.

The main one is that Sass is, basically, a "code generator". It's a sort of template language that generates CSS code. And so, a "Sass-if" works at code generation time, that is, when you execute the Sass command:

    sass-if (some logical condition) {
        <some CSS code>
    } else {
        <some other CSS code>
    }
Depending on the condition and at compile time, sass would spit out the first block of code or the second. The condition is, basically, a calculated expression that applies to values and variables available at compile time.

Then -after deployment and when a client visits your website- that CSS code is served to the client. Clients are varied and so CSS wants to have its own if structure that applies at runtime. The conditions generally would check the current runtime conditions (i.e. is this running on a large screen? is this browser in vertical orientation? etc)

    css-if (some condition pertaining this specific current browser) {
        <some CSS code>
    } else {
        <some other CSS code>
    }
So, yes, they are clearly and necessarily different, both in scope and usage. And so you'd generally need both if because they do different things. And that where the problem arises, because if you want to have both, their syntaxes need to be distinguishable.


Very good description, thank you.

One thing I don't understand is why not: 1) change Sass implementation to support "sass-if" and backport these changes to some older versions if necessary 2) upgrade the Sass's version and do a mass replace which sounds kind-of simple 3) use CSS's if happily


Yeah, personally that's the option I would choose too. It should fall on Sass to change whatever they may need to.

It's not completely "kind-of simple" though, as there is, potentially, a fair amount of code written with Sass in currently running projects. It is a cost to consider.

Also, there have been some precedents in the JavaScript community, mainly with Mootools -an old library, mostly irrelevant today but with some existing code still running in the wild- and the name of a couple of methods such as includes and flatten. The thing is that TC39 really pushes for "not breaking anything at all", and by proximity the CSS community seems to have some people with a similar opinion.


I assume the CSS if is not a compile time construct.


Oooh, fascinating. If I recall correctly, this happened once before in JavaScript. One of the Array.prototype methods has an unintuitive name because dojo, a very popular utility library at the time, monkeypatched the Array object with the method name they would have chose, and adding it to ECMAscript would have “broken the web” because so many sites used dojo.

Anyone remember the method name?


Not sure of the dojo conflict, but I did see this article recently that I thought was interesting: https://2ality.com/2022/03/naming-conflicts.html


Ah, it was MooTools, not dojo! It’s the examples cited in that article (e.g. String.prototype.contains()). Thanks!


And now MooTools is obsolete and people wonder why certain methods have strange names. An example of the tail wagging the dog.


Came to post that there is something incredibly soothing in the small illustrations that the author uses to end their blog posts.


Isn't this just the ecosystem problem/paradox again?

"If you're product exists to correct a deficiency in some other product, don't be surprised when that product makes your product native functionality."

If CSS chooses "if", it's up to Sass to deal with that. What Sass uses shouldn't be a concern for CSS.


Short is good but it shouldn't be to short. I would like to be able to search the web when I run into some syntax.

It doesn't seem like it is considered often.

For example: searching for "js ..." doesn't product results for spread operator or destructuring assignment. You would have to ask someone what is going on and the answer would have to not confuse the 2 eventho they share syntax.

"CSS if/else" obviously does produce many search results and for "CSS when" I get only 3. It seems everyone already knows what they are talking about. This is how we build human languages.

Personally I would prefer it if CSS was frozen and a new style type was introduced to contain all the heretical Turing-equivalency A style sheet should probably never have without disappointing those who really really want it.

Then we could say: You shall not load this x-domain.


Another case where 3rd party tools collided with the proposed standard name: https://developers.google.com/web/updates/2018/03/smooshgate


> nobody wants to have to type @conditional and @otherwise, so the WG went in search of shorter names.

I guess nobody in the working group uses an editor with tab completion? Unless you're going to be writing CSS on a whiteboard, this seems like a non-issue to me.


This is how we ended up with elif.

https://twitter.com/secretGeek/status/7269997868


No, `elif`, `elsif`, and `elseif` exist to solve a real grammatical problem. They occur in languages that don't have an explicit block statement with its own delimiters and instead allow a sequence of statements directly inside the then and else branches of an if statement, with some terminator like `end` at the end (or dedent in Python).

In those languages, without something like `elif`, you get an endless march to the right when you chain a series of ifs:

    if c1 then
      s1
    else
      if c2 then
        s2
      else
        if c3 then
          s3
        else
          if c4 then
            s4
          else
            s5
          end
        end
      end
    end
C doesn't need this because it only allows a single statement for the then and else branches, and `{ ... }` is a statement. Therefore, you can chain its directly by having the else statement be an if statement.


You could make `else if` a special sequence of tokens that works like `elif`.


You can, yes. However, doing that requires making the newline between the `else` and `if` significant:

    if c1 then
      s1
    else
      if c2 then
        s2
      else
        s3
      end
    end // <-- Two "end"s
Versus:

    if c1 then
      s1
    else if c2 then
      s2
    end // <-- Only one "end"
If you don't make the newline there significant, then every if statement at the beginning of an else clause would be interpreted as chained:

    if c1 then
      s1
    else
      if c2 then
        s2
      end
      s3
    end
Here, the parser will incorrectly treat the first "end" as closing the outer "if" when it's intended to close the inner one. It will then think "s3" is outside of the "else" clause and then consider the second "end" to be a parse error.

In principle, this isn't actually ambiguous and if the parser had unbounded lookahead it could probably find the second "end" and rollback and figure out what's going on. In practice, languages with unbounded lookahead are hard for humans to parse too.

Having an explicit "elif" token avoids all of this weirdness.


Why are people upvoting this as if it wasn't just explained why that's not true? That's only possible when you have (mandatory) block delimiters. That was the entire basis of the comment—that `elif` is used in "languages that don't have an explicit block statement with its own delimiters".


How is it not possible? Here's a simple grammar:

    if_stmt <- "if" expr INDENT stmts DEDENT ("else" "if" expr INDENT stmts DEDENT)* ("else" INDENT stmts DEDENT)?
It does require one-token lookahead, but it's unambiguous.


Are INDENT and DEDENT here describing whitespace sensitivity in the vein of Python, which "uses whitespace to delimit control flow blocks"[1] (elsewhere[2]: "Python uses whitespace indentation, rather than curly brackets or keywords, to delimit blocks")?

We're specifically talking about the subset of languages where these blocks _don't_ have their own delimiters[3].

1. https://en.wikipedia.org/w/index.php?title=Python_syntax_and...

2. https://en.wikipedia.org/w/index.php?title=Python_(programmi...

3. There is a reading of Bob's original comment such that it's suggesting that Python and end-if languages are among languages without them (or something—I can't make total sense of that part of the comment; it gets kind of garden path-y), but they're not.


It doesn't matter how indentation is parsed. What I wanted to say that you can simply replace "elif" with "else" "if" in the grammar.


You're right, you could do this in Python because it uses indentation for block delimiting. That means this is unambiguous:

    if c1 then:
      s1
    else if c2:
      s2
    s3
Without significant indentation, it's not possible to tell if "s3" is indented to be part of the the second if's then branch.

In other words, "else if" and "else INDENT if" are unambiguously different in Python.

That's not true in other languages that use "elif"/"elsif"/"elseif" where only newlines are significant and not indentation.


Certainly true. I was more making a bit of a joke about naming things though since that was kind of the OPs original point (which was subtle hinted via the twitter link).

Thanks for Dart, absolutely lovely language.


I might be misremembering, but I thought it was to keep it 4 chars, so that it aligns with `else`

    if ...:
        # ...
    elif ...:
        # ...
    else:
        # ...


A bit unrelated, but I was immediately reminded of a Marcus Brigstocke story from when (if?) he travelled to Svalbard.

> We had our safety briefing last night – all pretty obvious advice like "don't fall in the sea, it's cold". I wrote that one down.

> Barbara, our second skipper, is Dutch so the word for "if" is the same as "when". "When the boat catches fire" was not exactly reassuring and "when we turn over in a big wave" even less so.


The distinction between when ("wanneer") and if ("als") is there in Dutch, just like in English.


It's so confusing how the % character is used in Lex and Yacc. ISO C should introduce a modulo keyword to graciously get out of the way of these tools.


I don’t see why this is a problem. Sass users already name their files .scss. Why would there be overlap with .css files?


Wasn’t there such ambiguity once in Less with the calc function. When both Less and CSS supported their own version of calc() and Less would sometimes actually attempt to compute what was in the calc function instead of just leaving it for CSS to handle, and sometimes it wouldn’t.


OCaml has _when_ but Haskell has _where_. I used to think it was because OCaml was designed by people who's first language is French. Now I'm doubting my theory.



Adding to the mix: `when` is used for “guard clauses” in pattern matching in Ocaml, Erlang, and Elixir, so it’s not entirely unheard-of in programming languages.


Since the syntax is getting more verbose anyway, let me suggest @provided and @otherwise.

Or do a 180 and go the C ternary operator route. ;)


Semantically, "when" implies that something will happen, whereas "if" implies that it could happen.


When pigs fly I'll accept that "when" implies that something will happen.


Why would you write a when statement for something that can't happen?


If you're talking about in english "when pigs fly is" a common idiom.

If you're talking about code - sometimes it's nice to have extra-defensive code even if it's mostly inconceivable it will ever be triggered (especially if this will be used as a library for a lot of folks) but mostly you wouldn't.


When you write conditionals for events that will never happen in your CSS you are doing it wrong.


The draft was written 6 years ago, and didn't get updated for 4 years.

Isn't it abandoned?


As an adverb `when` is used mostly to refer to a time or moment. So semantically speaking `when` should be reserved for time conditionals only.


_When_ browser developers start caring about the semantics of one version of English grammar, then we'll have a lot of other work to do.


Is sass widely used nowadays?


> currently debating what to name a conditional structure, and it’s kind of fascinating

What's also fascinating (or, rather, horrifying) is how bad the whole thing is.

SASS is 15 years this year. Its concepts have proven their worth over, and over, and over again (and reimplemented several times in Less, PostCSS plugins etc.). W3C's own design system uses SASS [1]. How much of that did we get to see in CSS in the past 15 years? Maybe, just maybe we'll finally get nesting some time in the next 10 years or so.

Conditionals? Hahaha. If you're betting on getting them sometime before 2045, you're a fool.

The same thing repeats all across other tech in browsers. Detecting ambient light in browsers? Oh, w3c got you fam [2]. Providing usable styleable common components? Ahahahaha, even w3c relies on third-party implementations [3].

Most of the people on these committees have never developed a website in their life. Those that did only maybe implemented a blog or two a few decades ago. And the rest of browser implementors? Oh, they've never touched anything beyond C/C++ code in browser engines. And trying to get people who actually do this for a living there? It's a rather tough endeavor [4]

So, I wouldn't hold my breath for a decision on conditionals. Or for conditionals in general.

[1] https://design-system.w3.org

[2] https://www.w3.org/TR/ambient-light/

[3] https://design-system.w3.org/third-party-plugins/

[5] See "Solutions https://www.quirksmode.org/blog/archives/2021/08/breaking_th...




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: