Background on the Falcon 9 Launch - <AUTHOR> http://www.spacex.com/news/2015/12/21/background-tonights-launch <comment><USER3> My favorite way to describe orbits is 'constantly throwing yourself at the ground but moving so fast that you just keep missing', hence the constant free-fall/zero-g.

<comment><USER4> There is an XKCD "what if" that explains this: [https://what- if.xkcd.com/58/](https://what-if.xkcd.com/58/)

"The reason it's hard to get to orbit isn't that space is high up. It's hard to get to orbit because you have to go so fast."

<comment><USER5> How fast do you have to go? Easy. Look out at the horizon far enough that you can see it drop (for example a mountain etc). You have to go _so_ fast that in the time it takes you to reach that point, you only drop by the amount the horizon falls.

<comment><USER6> Could you make a cruise missile that didn't need any wings or other surfaces for lift - only forward propulsion - that just went so fast that it was effectively in orbit, but nor far above the ground?

<comment><USER7> The loss from atmospheric drag would be enormous. If you were on a planet with no atmosphere it would be no different from any other orbit though.

<comment><USER8> You could do this on the moon, for example

</comment></comment></comment></comment></comment></comment><comment><USER9> Clearly this man's intellect is through the roof. Reading this post and him explaining these concepts in such first-principle terms (despite not being a physicist/rocket engineer) indicates his in-depth understanding (nothing new there). I know he has a Bachelors in Physics but bear with me.

But, I'm just in awe and I keep thinking 'how does he do it?'.

He's running two intensely technical and risky companies. Yet he seems involved in and knowledgeable about every aspect of their operations and tech. And finds the time to write a post like this before what is an incredibly important and defining endeavor.

What can us, mere mortals learn from him? We can't change our baseline raw intelligence (which effects how quickly and deeply you can learn new things), but are there other patterns we can replicate in our lives?

<comment><USER10> This hero worship is utterly stupid. It's also a disservice to children. We're teaching them that there are heroes, and then everyone else.

Bull. Work as hard as Elon did, and you'd make the same progress. It also required luck. No PayPal, no Elon. And there could only be one PayPal, at precisely that time in history.

A better question is, why did Carmack fail where Elon succeeded? Armadillo Aerospace was supposed to be SpaceX.

<comment><USER11> Carmack invested about $2 million into Armadillo in its first 6 years. Elon invested $100 million in that time frame (actually, the first 4 years of SpaceX).

Armadillo did OK actually, they just were on a completely different trajectory. It was very much a hobby project for Carmack.

<comment><USER12> Not only that, but wasn't Armadillo one of the "straight-up-to-100KM-and- return" (suborbital) designs? If so, then there is no money to be made in that (except for wealthy people that want a 20 minute thrill ride). It is the "lateral velocity of Mach 25" type of rocket that gets you satellite launch contracts.

</comment></comment></comment></comment><comment><USER13> Elon's whole gravity explanation is essentially a textual version of this excellent video/demonstration: [https://www.youtube.com/watch?v=MTY1Kje0yLg](https://www.youtube.com/watch?v=MTY1Kje0yLg) (19 million views). Highly recommended, very memorable.

<comment><USER14> Yep, came here to post this. The funny thing is that there was a post about that video a while back, and the HN crowd criticized it pretty heavily for being a bad way to explain gravity. But... whatever. :)

<comment><USER15> Here is the discussion, which was interesting but inconclusive about the merits of this rubber sheet model: [https://news.ycombinator.com/item?id=8542244](https://news.ycombinator.com/item?id=8542244)

</comment></comment></comment><comment><USER16> If we can land the rocket accurately enough to put it down on a tiny barge only slightly larger than the rocket itself, then why do we need to tolerate the weight of the landing legs?

We already have industrial robots that can move and grasp heavy weights relatively quickly over distances of several metres -- it doesn't take much imagination to conceive of a similar contraption being used to arrest the descent of the rocket over the final few tens of metres of its' descent - <USER2> sort of brobdingnagian robotic catcher's mitt.

Granted, this might be a bit on the expensive / elaborate / bizarrely over- engineered side -- but it _would_ look utterly awesome.

<comment><USER17> There are several reasons why landing legs make more sense:

– Any flat chunk of cement is a landing spot. That means more places to land in case of contingencies. For yesterday's mission, SpaceX had one primary and four alternate landing zones.[1]

– I doubt industrial robots can withstand rocket exhaust. As helicopter footage shows, the landing pad got lit-up pretty good.[2] Remember, the first stage is over 40 meters tall. Those are some _massive_ flames.

…and most importantly:

– Landing legs work on other planets.

1\. Map: [http://www.americaspace.com/wp- content/uploads/2015/12/LZ1.j...](http://www.americaspace.com/wp- content/uploads/2015/12/LZ1.jpg) (from [http://www.americaspace.com/?p=89910](http://www.americaspace.com/?p=89910))

2\. [https://www.youtube.com/watch?v=ZCBE8ocOkAQ](https://www.youtube.com/watch?v=ZCBE8ocOkAQ)

<comment><USER16> Who cares about what makes more sense ... giant robots, dude! :-)

</comment></comment></comment><comment><USER18> Nice article, but I couldn't pass up a chance to correct Elon Musk's math:

 _It is important to note that the amount of energy needed to achieve a given velocity increases with the square, so going from 1000 km /h to 2000 km/h takes four times as much energy as going from 0 km/h to 1000 km/h, not twice as much._

Three times, not four--you already spent a quarter of the energy getting to 1000 km/h. Getting the rest of the way to 2000 km/h takes the remaining three quarters.

<comment><USER19> I believe you've misunderstood his English. If it takes 1 Joule to accelerate the mass from 0-1000km/h, it will take 4 Joules to accelerate the same mass from 0-2000km/h.

Elon is calling that _four times as much as_ because he's considering the total energy required to accelerate from 0 in both numbers. I think you're just accounting for it differently by saying it takes 3 times as much as the original energy input to go from 1000km/h to 2000km/h.

I'm a complete physics novice, I'm open to being schooled on this if I'm completely missing both yours and Elon's concepts here.

<comment><USER20> I think panic is correct. "from 1000 km/h to 2000 km/h" means from 1000 km/h to 2000 km/h, not 0-2000 kph. Though presumably Elon was thinking of the latter.

<comment><USER21> Read it as "going from target velocity of 1000km/h to 2000km/h".

</comment></comment></comment></comment><comment><USER22> Just for the record, the biggest newspaper in Brazil has an incredible picture of the launch/landing on its front page today :-) [http://f.i.uol.com.br/folha/homepage/images/1535742.jpeg](http://f.i.uol.com.br/folha/homepage/images/1535742.jpeg)

<comment><USER23> There are a few more here [http://imgur.com/r/spacex](http://imgur.com/r/spacex)

</comment></comment><comment><USER24> One thing I've not seen mentioned in the coverage so far: how much payload is sacrificed by the need to keep fuel in reserve for the return to base?

I'm guessing the sacrifice is roughly equal to the mass of unburnt fuel in the booster at the point of booster separation, but don't much trust my intuition on these things.

<comment><USER25>
       > how much payload is sacrificed by the need to keep fuel
       > in reserve for the return to base?

Simple answer: None.

A more detailed answer is that building a system which can be reused is an economic proposition. So that the Falcon 9 can lift X Metric tons to orbit for $Y. The way in which they keep the value $Y low is by re-using the first stage. Every satellite project knows the throw weight of all the common launch vehicles and their cost per kilo. And that is how you plan you satellite design.

Now at the moment SpaceX gets 9 merlin engines and the first stage booster back for "free" (which is to say that the cost paid assumed it would be consumed in the launch) but as they learn what they can do they will use that cost savings to offer cheaper launch services (more business) until they have a full launch schedule and then keep any excess value for re-investment.

But an interesting question is this, given that they have a "used" first stage, who would be willing to launch on it? It has no track record and no reliability statistics other than it worked at least once before. To develop that information you need to re-launch them. And I'm hoping that SpaceX will make available some higher risk but lower cost "seats" on those test flights.

<comment><USER26> SES already said that they're willing to be the first customer for a used booster[1].

Before they get that far, it'd be interesting to see if SpaceX flies a used engine, since they've got "one engine out" capability. Which has already been tested twice.

1: [http://spacenews.com/spacex-early-adopter-ses-ready-to- reuse...](http://spacenews.com/spacex-early-adopter-ses-ready-to-reuse- falcon-9-%C2%AD-for-the-right-price/)

<comment><USER25> That article raises an interesting point I really hadn't considered, who owns the first stage? If you pay "full price" for a launch and SpaceX recovers the first stage to re-use, did the person who paid to launch it own it or does SpaceX? It was presumed lost of course. No doubt there is language in the contracts about that. Would be interesting to see a launch contract.

<comment> Alain-lf SpaceX own the first stage.

You pay to get your payload delivered to a specified orbit. You don't actually buy the rocket.

It's like flying, you buy a ticket, not the plane.

<comment><USER25> Just for reference, I got an inside look at what it took to get OSCAR16[1] launched and it isn't like flying :-). Now I don't doubt things are more streamlined now but every launch starts with a basic contract and that contract has to cover everything from contingencies to insurance to liability to disposal.

Trying to search for a boilerplate launch contract I found an article[1] where it discusses that Spaceflight Industries _bought a Falcon 9 launcher_ [emphasis mine] which suggests that one buys the entire rocket. That would imply that if they land it, you still own it does it not? Can you then go over to the landing zone pick up your rocket and resell it for parts to offset your original purchase price? :-)

I am really confident that ownership of the first stage is covered in the launch contract if it is returned to the landing field. And the math there would no doubt be really interesting to an insurance company since you have the possibility that the launch is a success and the first stage lands, the launch is a success and the first stage crashes, the launch effectively fails (second stage failure) but the first stage successfully returns, and both stages are lost. That is a number of different outcomes to insure.

Frankly my mind is boggling at the potential legal complexity here.

[1] [https://en.wikipedia.org/wiki/AMSAT- OSCAR_16](https://en.wikipedia.org/wiki/AMSAT-OSCAR_16)

[2] _" SpaceIL has purchased launch services from Spaceflight Industries; an American space company who recently_ purchased a SpaceX Falcon 9 launcher _and will manifest SpaceIL's spacecraft as a co-lead spot, "_ \-- [http://lunar.xprize.org/press-release/israeli-google- lunar-x...](http://lunar.xprize.org/press-release/israeli-google-lunar-xprize- team-first-sign-launch-agreement-private-mission)

<comment><USER27> I think the real answer is that there will be a complex contractual relationship that "ownership" is too simple to describe, in either direction. E.g. I say I "own" my flat, but actually I am a shareholder in a company that owns the building and have a lease contract with that company (this is the standard (only?) way of "owning" a flat in the UK, because multiple flats stand on the same piece of land - you can't truly "own" something you don't have the right to destroy, but obviously you don't have the right to destroy a flat with someone else's above it).

> And the math there would no doubt be really interesting to an insurance > company since you have the possibility that the launch is a success and the > first stage lands, the launch is a success and the first stage crashes, the > launch effectively fails (second stage failure) but the first stage > successfully returns, and both stages are lost. That is a number of > different outcomes to insure.

The insurance industry already deals with far more complex scenarios. A ship on an ocean voyage will often have the hull and cargo insured separately, different loss layers insured separately (e.g. first 10% of losses, 10-20%, 20-100% all separate), with multiple underwriters on each layer (and sometimes the same underwriter on multiple stamps).

<comment><USER28> "this is the standard (only?) way of "owning" a flat in the UK"

Maybe in England - its never worked like that for any flat I've owned here in Scotland, we have completely separate legislation covering such things:

[http://www.gov.scot/Topics/Justice/law/17975/11023](http://www.gov.scot/Topics/Justice/law/17975/11023)

</comment></comment></comment></comment></comment></comment></comment></comment><comment><USER29> This all seemed reasonable except this paragraph:

"The reason they are floating around is that they have no net acceleration. The outward acceleration of (apparent) circular motion, which wants to sling them out into deep space, exactly balances the inward acceleration of gravity that wants to pull them down to Earth."

There is no "outward acceleration". The weightlessness is because the craft they are in is accelerating towards Earth with exactly the same acceleration. The reason they don't hit the ground is that they have a suitably high tangential velocity.

<comment><USER30> Both you and the article are right - you are analyzing it in the frame of reference where the center of the earth is stationary, while the article analyzes in the frame of motion where the center of the rocket is stationary.

Since the frame where the center of the rocket is stationary is a non-inertial frame, Newton's law doesn't apply [1]. However a modification of Newton's law that includes a so-called "ficticious force" applies [2] (I don't think this modification has a name). This is why the article says there's an outward acceleration, because in the frame where the center of the rocket is stationary, the outward acceleration is caused by the ficticious force.

[1]: [https://en.wikipedia.org/wiki/Newton%27s_laws_of_motion](https://en.wikipedia.org/wiki/Newton%27s_laws_of_motion) begins the laws with "when viewed in an inertial reference frame"

[2]: [https://en.wikipedia.org/wiki/Non- inertial_reference_frame](https://en.wikipedia.org/wiki/Non- inertial_reference_frame) quotes, "One might say that F = ma holds in any coordinate system provided the term 'force' is redefined to include the so- called 'reversed effective forces' or 'inertia forces'."

<comment><USER29> Right, of course I understand that - but two points.

1) The whole original post appears to be worded for the layman to try and dispel myths around what orbit is. I don't think the layman is going to think about inertial frames of reference, rather I genuinely think the common misconception that there's really something 'pulling' the astronauts up will continue, much like many people think a car is throwing them out of a bend in the road, rather than the vehicle pushing them away from a straight line.

2) In any case, even if Musk implies the frame of reference, there's a reason a 'centrifugal force' is also referred to as a 'fictitious force' [1]

[1]: [https://en.wikipedia.org/wiki/Fictitious_force](https://en.wikipedia.org/wiki/Fictitious_force)

</comment></comment></comment><comment><USER31> "[100Km altitude] is the equivalent of the starting line of a race. The race itself is the kinetic energy."

Did you get that, Jeff?

The truth is, they have both achieved an astonishing amount.

<comment><USER32> Blue Origin is cool but it's certainly not astonishing to me that a billionaire is able to send a rocket on a suborbital trajectory and recover it. It's certainly more than I've ever done by a long shot, but it's not a very interesting achievement unless you're interested in five-minute space tourism. I don't think BO's achievement here has many implications for space travel.

<comment><USER33> I wonder its implications for terrestrial travel, though? We are in a post- Concord era, after all, but suborbital flight could get you to any point on the planet pretty quickly if the price is right.

<comment><USER34> This may be interesting to you: [http://www.antipope.org/charlie/blog- static/2015/01/why-were...](http://www.antipope.org/charlie/blog- static/2015/01/why-were-not-going-to-see-sub-.html)

</comment></comment></comment></comment><comment><USER35> Elon is actually great at explaining things in simple terms. The writing on WaitbutWhy.com is very similar.

<comment><USER13> Elon has said himself that he is a fan of WaitbutWhy.com

<comment><USER35> Waitbutwhy did a few in-depth articles about him and his companies after Elon invited him over for interviews.

</comment></comment></comment><comment><USER36> haha they gave the drone ship a Culture ship name! SpaceX just became my favourite company

</comment><comment><USER37> Not trying to nit-pick, just trying to confirm my own understanding. But actually, accelerating a mass from 1000km/hr to 2000km/hr should take _three_ times as much energy as from 0km/hr to 1000km/hr, right? I assume the quantity of "four times as much" was just used to get across the notion of energy being proportional to the square of velocity.

<comment><USER21> It ment going from 0-1000 to 0-2000, i.e. increasing target speed twice will increase total energy neede four-fold.

</comment></comment><comment><USER38> > Getting back to everyday reality, the impression that most people have is > that gravity stops once you reach a certain altitude above Earth, at which > point you start floating around in "zero g", but, as we just talked about, > this is obviously not true. The force of gravity drops proportionate to the > square of the distance between the centers of two objects.

I'd like to meet the person that is both uneducated enough to think that gravity suddenly stops and after that is "zero g", and also undestands what "proportionate to the square of the distance" means!

</comment><comment><USER39> The article mentions that the water landing requires less fuel to return the rocket because it doesn't have to spend fuel overcoming its initial ballistic trajectory. In the water landing scenario, how far away from the launchpad is the landing barge? I'm wondering about the economics of launching from a site where your first stage trajectory is entirely overland, to avoid the complications of landing on a barge that's being tossed in the sea. Though it might be hard to find such a site in U.S. territory that's both near the equator and sparsely populated.

<comment><USER40> I found a reference that the barge was 320 km downrange in the earlier tests. The Bahamas look to be an appropriate distance from Florida, although to the southeast of Cape Canaveral. From SpaceX's planned Texas spaceport, there's nothing at that range but gulf.

<comment><USER33> Hypothetically, I imagine they could anchor a stable ocean platform out there if they find it's easier than the barge. No idea if it actually would be easier than the barge though.

</comment></comment></comment><comment><USER41> It's a good summary, but I'm not sure the repeated digs at Bezos are really necessary. I think anyone who would bother to read this already gets the differences. Not sure that he really needs to point out, twice, that height doesn't matter at that stage of testing.

Edit: Just got to the end and saw this was prior to launch, so before Bezos' "welcome to the club" tweet. I guess in that context it's a bit more subtle at least, but still seems like he was making a point of the difference from Blue Origin.

</comment><comment><USER42> I'm having some trouble with the opening salvo here:

"Now imagine placing a marble somewhere on that slippery sheet -- it is guaranteed to fall into one of the funnels. "

This holds for the case where there are two objects initially at rest, but I don't see it as obviously true if there are more than two objects in the universe.

<comment><USER43> I see two aspects to your question/comment: at-rest, and two-objects.

The whole point of that comment was to apply only to at-rest things (he goes on to contrast it with objects with velocity), though I think maybe you got that.

If you have a marble and two other objects, the other objects make two funnels, and there is a saddle (itself curved) where the two objects's funnels are equipotent. That's the three-body case. If it were possible to balance perfectly on this line of equipotence, you'd just slide to the lowest point on that line, and stay there, out of the funnels. This, IIUC, is one of the Lagrange points... L1, I think. In theory it's possibly-stable, but its stability exhibits negative feedback, so in practice it's impossible (although with station-keeping rockets, it's cheaper to hover there than most places).

As you add more funnels, you just get more of these saddle lines intersecting. There are many infinitely-fussy places in the universe where you could in- theory-but-not-in-practice hover without falling into a funnel (if it weren't for brownian motion and maybe some other quantum effects that disturb your infinitely-difficult equilibrium).

Of course, this whole analogy doesn't account for the fact that all of the bodies are acting on each other, not just the funnels acting on the marble.

<comment><USER42> Right, the fact that all the bodies are acting on the other is what makes me feel the analogy is not kosher. The funnels are going to start moving around based on their mutual attraction, and I could see the marble being ejected to infinity, for example. It's less clear to me (but possible) that it could enter a stable orbit.

</comment></comment></comment><comment><USER44> Great and easy to understand article, thanks for posting it. Does anyone know it the spacex team uses the imperial or the metric system for development? Elon switches between both systems and it's messing with my head.

<comment><USER45> Fwiw, on their public webcast, they had on-screen telemetry showing km/h for speed and km for altitude (and no downrange distance). Not necessarily what they use internally, though.

Aerospace engineers traditionally uses knots, thousands of feet and nautical miles. SI units typically have km/s (not /h).

</comment></comment><comment><USER46> "nitrogen attitude thrusters" Think that was supposed to be altitude?

edit: just saw this at the bottom and it made me smile; "Apologies for any typos in the above."

<comment><USER47> Attitude is correct. It refers to thusters controlling the orientation of the rocket.

[https://en.m.wikipedia.org/wiki/Attitude_control](https://en.m.wikipedia.org/wiki/Attitude_control)</comment></comment>


But why is a sphere's surface area four times its shadow? [video] - <AUTHOR> https://www.youtube.com/watch?v=GNcFjFmqEc8 <comment><USER2> Haven't watched yet but an obvious lower bound is 2 times it's shadow (one for each side) - in fact a coin achieves this.

<comment><USER3> And 6x is a good upper bound (achieved by a cube). It's nice that the correct answer is halfway between these.

<comment><USER4> The cube surface area is 4 times the average size of the shadow across all rotations, according to the video.

<comment><USER5> In fact, the video states this for all convex shapes.

I've been trying something similar for 2D, but there it doesn't quite seem to hold.

Consider a very thin rectangle of size 1 by epsilon. Then it has circumference 2 (ignoring the epsilon). The shadow it casts at angle phi has size |sin phi|. Now, if we average |sin phi| from 0 to 180 degrees, (or 0 to 360 or 0 to 90) we get (2 / pi).

I haven't checked whether this average holds for things other than thin rectangles, but I'd imagine so. I then find it weird we get a trancendental number in 2D but an integer in 3D.

<comment><USER6> Not a surprise to see pi in there really, since we're averaging over "surfaces" of circles/spheres. In general (spoiler), it does generalize to arbitrary dimensions. We get a rational factor for odd dimensions, and 1/pi * rational for even.

See sections 6-9 here for demonstration: [https://arxiv.org/pdf/1109.0595.pdf](https://arxiv.org/pdf/1109.0595.pdf)

</comment></comment></comment></comment></comment><comment><USER7> It maybe answers a different question, but I always thought it was neat that the surface area for a sphere is just the derivative of its volume. Beyond that, I guess I never thought about it much.

<comment><USER8> Fun fact: by the same logic, the perimeter of a circle is the derivative of its area.

<comment><USER9> Does this relationship generalize? Hypothetically carrying further, if you take the derivative of the area (wrt radius) you get 2pi. A one dimensional circle is a line segment of length 2*r right? So how is 2 pi related to a line segment? Is it in some way analogous to the way perimeter and area are for 2d or surface area and volume? I don't know the answer.

<comment><USER10> > Does this relationship generalize?

Yes, the fundamental theorem of calculus guarantees this will be true. It's the same phenomenon as that if your "volume" is the definite integral of f(t) from fixed _a_ to variable _x_ , then the rate of change of the volume (= the surface area) is f( _x_ ), the length of the infinitesimal sliver you're about to add to the volume.

You can think of the solid sphere as an infinite stack of concentric infinitely thin hollow spheres. Each layer contributes volume to the solid sphere equal to its own area. (And this is what it means to calculate the volume of a sphere as the integral of the area of a spherical shell as the radius goes from 0 to r.)

<comment><USER11> > You can think of the solid sphere as an infinite stack of concentric > infinitely thin hollow spheres.

This is dangerous logic. For example a similar argument might lead you to think that a staircase in 2d between two points would have the same length as the Pythagorean distance between the two points, as you can make the steps arbitrarily small.

<comment><USER10> ...no? The same logic will tell you that you can think of a _triangle_ as being a linear stack of infinitely thin line segments, and there, as here, you'd be completely correct. The logic you're calling "dangerous" is just the principle behind [https://en.wikipedia.org/wiki/Shell_integration](https://en.wikipedia.org/wiki/Shell_integration) .

But no similar argument will let you call the diagonal line an aggregation of little right-angled jags. A one-dimensional line is an aggregation of zero- dimensional points, not other one-dimensional lines.

</comment></comment></comment></comment></comment></comment><comment><USER12> I'm really impressed with the level of quality of some of the educational videos on youtube. The author here clearly spent hours preparing each of these diagrams and animations, and he's not unique among the popular youtube educators for doing so. I'm envious of the resources today's youth have in the classroom.

<comment><USER13> If I recall correctly 3blue1brown is actually a team of people, and it's founder created a python library which helps generate the animations.

<comment><AUTHOR> That was a temporary experiment to see if more people enabled Grant to produce more videos, but the Mythical Man-Month rang true again. It's just Grant now, like it was when it started.

[https://en.wikipedia.org/wiki/Brooks's_law](https://en.wikipedia.org/wiki/Brooks's_law)

<comment> too-soon-ago I didn't realize that happened. Kind of a shame. But he did get that interactive page for visualizing quaternions built with a collaborator.

<comment><AUTHOR> He's still experimenting with different approaches, trying to find the optimal flow like any startup would. His approach as of late has been to collaborate more with other channels, like he did on the Feynman video and the interative quaternion page you referenced above.

</comment></comment></comment></comment></comment><comment><USER14> As a huge fan and patron of 3blue1brown's videos, does anyone have recommendations for similar high-quality channels covering other topics? Personally I'm interested in at least:

* History/biographies

* Sciences (physics, chem, astronomy)

* In-depth nonpartisan analysis of political situations, especially current ones. The breaking news cycle does a poor job parsing out useless or incorrect information.

* How we've managed to create the insanely complex technology we have today, starting at the basics

<comment><USER15> Applied science. He doesn't cover things in documentary style, but recreates quite a lot of interesting science that one would assume is beyond the level of garage science, and does an excellent job explaining all the concepts.

</comment></comment><comment><USER16> Very well done, as always. As someone who is probably below the intended audience level my one complaint is that it wasn't clear to me why the fact that the square on the sphere has the same area as its projection on the cylinder implies that the total of all these areas is the same, i.e. why do we know the projections don't overlap, when each is cast from a light at a different height on the pole, as it were?

<comment><USER17> Imagine the sphere's surface is divided into one million little rectangles. Their total area is meant to approximate the surface area of the sphere. If each one of those were projected onto the cylinder, and we showed that each of those projected rectangles has the same area and that they don't overlap, then the total area of all million of the projected rectangles would be there same as those on the sphere. Therefore, the cylinder has the same area, since it is comprised of all those projected rectangles.

<comment><USER16> Thanks, so it's the overlapping issue I'm left struggling with (sorry, I elaborated on this in an edit after you'd already started replying, by the looks of it). It's not obvious to me they don't overlap, if the 'light' is at a different point for each one.

<comment><USER18> You're intuition is correct that the rectangles would overlap if projected by a light like shadow puppets. Instead, imagine a series of lasers up and down the vertical axis positioned so that their beams are parallel to the plane that contains the sphere's equator. And imagine that the lasers spin 360 degrees around the vertical axis but their beams always stay parallel to the plane of the sphere's equator. That's the projection being described here.

<comment><USER19> Right. Effectively, we're projecting every horizontal slice of the sphere laterally to a fixed distance from the vertical axis. It's a stack of 1D projections, not a single 2D projection.

<comment><USER19> I realized after the fact that the more useful terms would be "orthogonal projection" and "perspective projection". The novelty of the orthogonal projection at hand is that it's projecting (flattening) in a cylindrical space.

With an orthogonal projection, you can usually think of it as taking two planes and squashing whatever object your want to project between them. In the scenario here, the ambient space has been wrapped up, so one of these squashing planes has been wrapped into a cylinder, and the other has been wrapped into a line (the degenerate case).

In either event, an orthogonal projection is indeed a collection of orthogonal projections of one dimension less. But that's not really the whole picture.

</comment></comment></comment></comment></comment></comment><comment><USER20> Another considerably unexpected, not to say mindblowing property, in that context:

VCone + VHemisphere = VCylinder

[https://en.wikipedia.org/wiki/Cavalieri%27s_principle](https://en.wikipedia.org/wiki/Cavalieri%27s_principle)

[http://blog.zacharyabel.com/tag/cavalieris- principle/](http://blog.zacharyabel.com/tag/cavalieris-principle/)

</comment><comment><USER21> In a spirit of rough-quantitative reasoning...

Because pi is 3, modulo a 5% error we'll so easily ignore, we all know the volume and area of a ball are 1/2 those of the box it came in. And the area and perimeter of a circle are 3/4 those of its bounding square. So a unit-wide ball in a box has an area of 3, and its shadow on the bottom of the box has an area of 3/4\. QED.

How often does education leave students struggling with half-remembered "was it 4/3 pi r^3... or was it 4 pi r hmm...", and bereft of any clue that the ball's simply half its box. It's like education never uses it to engage with the physical world, so there's no selection pressure for being able to apply it as other than a math tidbit.

<comment><USER22> We all know? I think that's a fact that isn't well known.

<comment><USER23> Reminds me of the math lectures during university:

"Since we all know that ... it is obvious that ..."

and I kept thinking "no we don't and no it isn't"

<comment><USER24> Those are just stepping stones to "It can be shown" and "Left as an exercise for the reader."

</comment></comment></comment></comment><comment><USER25> FYI, if you like 3b1b's videos, you can support him on Patreon: [https://www.patreon.com/3blue1brown/posts](https://www.patreon.com/3blue1brown/posts)

</comment><comment><AUTHOR> While we're on the topic of curves and spheres...

Does anyone here know of any theorems that relate the curve of a cycloid [1] to the curve of the horopter [2] (in particular, the empirical horopter)?

In my continued quest to connect curious properties of the cycloid, I noticed hints of potential correspondences between the two curves beyond just their shape, particularly in the ways the curves of the cycloid and horopter both relate to the path of light.

A few years back, Grant did a 3Blue1Brown video with with Steven Strogatz on the cycloid Brachistochrone curve : [https://www.youtube.com/watch?v=Cld0p3a43fU](https://www.youtube.com/watch?v=Cld0p3a43fU)

And Vsauce did one with Adam Savage on the Brachistochrone [3] where they build a mechanical model of one that shows it's the fastest/optimal path among different curves, and their experiment also shows the cycloid Tautochrone [4] invariant property where objects begin up the curve at different distances apart and yet all arrive together simultaneously in constant time. [https://www.youtube.com/watch?v=skvnj67YGmw](https://www.youtube.com/watch?v=skvnj67YGmw)

Some other interesting properties and places the cycloid shows up...

* The arclength of the cycloid curve is 8R, a rational value given a rational radius.

* The shape of the closed universe [5]. While we don't yet know if the shape of the universe is open or closed, we do know that if the universe is closed the shape of its evolution is precisely the shape of a cycloid.

* Spinors [6], octonions, and the epicycloid [7]. Electrons, protons, neutrinos, and quarks are spinors. The Rolling Spinor is like a ball, but "thanks to the 'double' in the double cover SU(2)→SO(3), a 360∘ rotation does not act like the identity. Instead, we need to rotate by 720∘ degrees to get back where we started" [8]. The two balls have a 3-to-1 ratio, and the path traced out around the larger ball is an epicycloid.

[1] Cycloid [https://en.wikipedia.org/wiki/Cycloid](https://en.wikipedia.org/wiki/Cycloid)

[2] Horopter [https://en.wikipedia.org/wiki/Horopter](https://en.wikipedia.org/wiki/Horopter) , Hering–Hillebrand deviationn [https://en.wikipedia.org/wiki/Hering- Hillebrand_deviation](https://en.wikipedia.org/wiki/Hering- Hillebrand_deviation)

[3] Brachistochrone curve [https://en.wikipedia.org/wiki/Brachistochrone_curve](https://en.wikipedia.org/wiki/Brachistochrone_curve)

[4] Tautochrone curve [https://en.wikipedia.org/wiki/Tautochrone_curve](https://en.wikipedia.org/wiki/Tautochrone_curve)

[5] MIT 8.286 The Early Universe: Introduction to Non-Euclidean Space [video] [https://www.youtube.com/watch?v=YfbXB_MSkSY](https://www.youtube.com/watch?v=YfbXB_MSkSY)

[6] Spinor [https://en.wikipedia.org/wiki/Spinor](https://en.wikipedia.org/wiki/Spinor)

[7] Epicycloid [https://en.wikipedia.org/wiki/Epicycloid](https://en.wikipedia.org/wiki/Epicycloid)

[8] G2 and the Rolling Ball [https://golem.ph.utexas.edu/category/2013/06/g2_and_the_roll...](https://golem.ph.utexas.edu/category/2013/06/g2_and_the_rolling_ball.html)

Split Octonions and the Rolling Ball, Dr. John Baez [video] [https://www.youtube.com/watch?v=xvflQcHT5C4](https://www.youtube.com/watch?v=xvflQcHT5C4)

Eric Weinstein explains Gauge Symmetry [video] [https://www.youtube.com/watch?v=2xiEEtoa-_4](https://www.youtube.com/watch?v=2xiEEtoa-_4)</comment>


We're trying out a splash page. - <AUTHOR> http://www.phome.us

<comment><AUTHOR> I run a homepage manager with my friend and we look at 2 very concrete statistics: signups and clicks (on the homepages). We wanted to see if we could increase our adoption rate, so we revamped our splash page.

We pushed it live just earlier today, so I don't have much data to share with you quite yet, but I'm curious to hear what the rest of you think about splash pages. Particularly ones that have a style that's different from the rest of the site. Have you seen any changes in your number of signups? Did you attract a different sort of user that wouldn't normally sign up?

</comment><comment><USER2> Did anyone else feel slightly nauseous from the wavy boxes around the normally aligned text? Or is it just me? :)

</comment><comment><USER3> I spent about 15-20 seconds looking at the page, and had no idea what this service does. You need to make it more obvious, even for not-so-smart users like me.

But I like the design.

<comment><USER4> One more vote for the confused user... I had to read the "Get to the sites you always visit, and see when they are updated" several times to even guess what your site does.

Are you talking about a bookmark repository (ok, "homepage") that somehow tells you when there is new stuff on your bookmark?

If that is the case, shouldn't you put a sample image on this screen that shows how the homepage looks like, including the one that tells you a site has been updated?

Ok, but your questions was about a splash screen :-) ... It looks good, but don;t call it a splashscreen. The word brings up awful memories of sites that forced you to wait a minute or two over dial-up just to display some image that told you nothing except to click to get to where you really wanted to go. Your screen has a lot more than that, it is actually useful.

As far as homepages that look very different than the rest of the site, this is a good thing. Lots of entertainment-related sites use them, and they are overall a good thing. The homepage engages the visitor, makes a good impression, and the rest of the site is actually the useful part. Yours is pretty good, it's just the wording I had an issue with.

<comment><USER5> Interesting. We thought it was very self-explanatory, but maybe we have just been too immersed in it. It's a homepage (in the sense of your browser's starting page) which holds links to the sites you always visit.

It auto discovers the RSS feed and periodically checks them, but we never refer to it as "RSS feeds" on the site. We tried to abstract that process as much as possible, so it becomes like any other toggle button.

That's exactly what we were going for, to hook them and pull them to step two (which will hopefully pull them to step three, and so on). Now that we have the format, we plan on continuing to tweak the copy until we find something that works.

</comment></comment></comment><comment><USER6> "and I totes love it."

Huh? Totes? What? I guess I'm just not cool enough for this site.

<comment><USER4> Yeah, that got a chuckle out of me too... But a quote is a quote :) Better to leave it exactly as said.

</comment></comment><comment><USER7> Your tagline on top doesn't make sense to me, I don't get what the product does and it just confused me a bit more, apart from that confusion the design looks fabulous

Also love the Totes quote .. what the?</comment>


Ask HN: Mi Band Xiaomi hack? - <AUTHOR> Hi, I received the Mi Band Xiaomi for my birthday. I am looking for unofficial resources and utility, and how to integrate it in a custom project. I found very few materials on github. <comment><USER2> [http://allmydroids.blogspot.de/2014/12/xiaomi-mi-band-ble- pr...](http://allmydroids.blogspot.de/2014/12/xiaomi-mi-band-ble-protocol- reverse.html)

This is a nice post about their protocol, although it seems that they are trying to prevent reverse engineering by obfuscating it in newer releases. There are also links to some useful libraries. Remember that MiBand can be connected to just one device at a time.

<comment><AUTHOR> Thanks, this website is a pretty old, and I hope the protocol doesn't change after the firmware upgrade. The 1st hack, I'd like to do, is to use miband for notification mobile. It will be nice have a library or sdk for this purpose. For android : [https://github.com/lwis/miband- notifier](https://github.com/lwis/miband-notifier)

<comment><USER2> Yes, I know... Developers are constantly asking for an API of some sort, but seems that Xiaomi ignores that. Too bad, since the MiBand is a nice little device. Are you trying to use it on Android? There is also an iOs library (but seems very limited) and a Python one (has a lot of functions - [http://oscaracena.bitbucket.org/mibanda/api/](http://oscaracena.bitbucket.org/mibanda/api/))

<comment><AUTHOR> Yes, I am an Android developer, but it is not the point. The point is to increase functionality, and maybe build a sort of library to handle the main functionality ( it should be really nice customize the notification). The python library looks like very nice :-) good job</comment></comment></comment></comment>


Programming Patterns I Like - <AUTHOR> https://www.johnstewart.dev/five-programming-patterns-i-like <comment><USER2> Nested ternaries are horrible. They add an additional burden to think about operator precedence, which is actually a hard thing especially if you switch between languages regularly. They are harder to extend for those reasons and often it is just stupid to handle condition prerequisites outside of the nesting of an if statement.

Conditional logic is the third hardest thing just after variable naming and cache invalidation. There is no excuse to make it harder to understand.

<comment><USER3> Ironically, it could have been written far more concisely and clearly by using IIFE, if-then statements and reordering the logic:

      const result = (() => {
        if (!conditionA) return 'Not A';
        if (conditionB) return 'A & B';
        return 'A';
      })();

Yes, I know, I "need" to use curlies. But there's really no reason why someone shouldn't be able to quickly make sense of this. The ternary, on the other hand, is unnecessarily cryptic.

<comment><USER4> Can't help but call out Rust here for it's (imo excellent) syntax.

if condition {do_x()} else {do_y()}

Basically there's no need for line breaks between if/else, but also they decided not to add a ternary conditional operator.

<comment><USER3>
      if (condition) { do_x() } else { do_y() }

That's the JavaScript version of what you wrote, and it's nearly identical. JavaScript doesn't require line breaks.

<comment><USER5> The significant difference is that in Rust, like in Lisp, `if` is an expression, so if-else essentially is the ternary operator.

        const x = cond1 ? a
                : cond2 ? b
                : c

becomes in Rust

        let x = if cond1 { a }
                else if cond2 { b }
                else { c }

</comment></comment></comment></comment></comment><comment><USER6> I know that is a matter of taste, but nested ternaries are not straightforward to understand as the author try to convey. The example shows two nested levels, and I need to simulate the program flow for a while in my head to really understand it. Definitely not desirable for my everyday programming sessions. However, simple and short ternaries are welcomed.

<comment><USER7> When formatted like this:

           result = (cond_A ? 1 :
                     cond_B ? 2 :
                     cond_C ? 3 :
                     5)

they look quite a bit nicer than the if/else equivalent IMO.

<comment><USER8> This is actually nice because in some languages a case statement is a statement and not an expression -- so you can't assign the value easily. +1, would use this in production code :-)

<comment><USER9> And when conditions are not direct don't forget to add Lisp level of parentheses. I bet one time you will forget and everything will explode.

</comment></comment></comment></comment><comment><USER10> > This pattern is nothing really special and I should have realized it sooner > but I found myself filtering a collection of items to get all items that > matched a certain condition, then doing that again for a different > condition. That meant looping over an array twice but I could have just done > it once.

Write a generic function for this instead? Lodash has one like this called "partition" for example.

I try and avoid explicit for loops as much as possible as they tend to make code harder to follow and state manipulation is a big source of bugs. Most operations on collections can be decomposed into some easy to follow combination of map, reduce and filter instead (this is a filter variation).

Nice article!

<comment><USER11> The lodash one might be inspired by the Python itertools "partition" recipe, [https://docs.python.org/3/library/itertools.html#itertools-r...](https://docs.python.org/3/library/itertools.html#itertools- recipes)

TFA's inlined reduce version is much less readable than calling a function which wraps this behavior up.

<comment><USER10> It's common in functional programming libraries too, usually with the same name. See e.g. OCaml, Haskell and Standard ML.

</comment></comment></comment><comment><USER12> I'm very surprised that early returns are still commonly used and advocate in 2019. In my opinion, they are obviously terrible. I'll try to convince you.

First the practical, in my experience, a big function with many early returns has a bug or has a convoluted logic, 100% of the time. I've literally made a living and a career by untangling big functions with early returns. I've really saved many situations and code just by doing that. The reason this happens is that early returns are gotos and gotos are harder to follow.

Also, you can't move easily (think copy/paste) code than has early returns, which means that the code is defacto harder to refactor. So in practice, code with early returns stays in place and grows.

Early returns are artefacts of the assembly jump instruction. They shouldn't even be in a high-level programming language because it makes no sense to have jumps in such a language. They make the programmer lives in the assembly language world (succession of instructions that update a state) instead of the wonderful world of high-level programming (expressions).

If you interested by what I'm saying, you should try removing all returns, continues and breaks from your code, you'll see what wonderful things happens. It's literally magic. Things becomes so much more expressive without them. Which is the point, high level programming is about gaining more expressiveness over assembly code.

Early returns is one of the big pillars of bad inexpressive entangled convoluted programming. And what is people reason for using early returns? It makes less indentations...

You may wonder why early returns doesn't sound that much like a big deal after all. And you are right, there is no big deal. No big deal in terms of what the market reward. Now if you care about the _art_ of programming, this is a huge deal imo.

 _edit: thank you for the fair discussion. I would like to insist that obviously, if your code is more expressive, you will take better decisions and at the end, what I 'm saying is that you will end up with a totally different program. Early return or not is not about cosmetic. It's about writing better program._

<comment><USER13> But break/continue statements are also like goto, and to be consistent they would need to be eliminated as well.

<comment><USER14> The more I read about for loops, non local exits.. the less I want to go back to imperative programming.

</comment></comment></comment><comment><USER15> This object / function switching is horrible. Obfuscates code reading a lot. Why lambdas and not named functions. Same for nested ternaries. This is the kind of code which no one will like afterwards to maintain.

Early exits are fine when they are used for invalid input/use cases. But not for regular algorithmic outputs. This would hide cyclomatic complexity. Unfortunately, not understood by the author once you understand the reduce example. I am not experienced enough with reduce to make a statement about the array pattern... But it looks good especially when the language has array deconstruction.

<comment><USER16> Re Object/functions, I think his example is a bit flawed too, but not for the reason you give. A lambda vs named function doesn't really change his pattern at all.

The big problem for me is that it's offloading the logic for picking to the caller, so that if they forget to default null to ```contentType["default"]``` everywhere there will be a bug. putting the choice+ default fallback at the callee side reduces this boilerplate.

<comment><USER15> The reason I complain about the lambdas is the lack of readability what the function does (the name), the lack of a speaking stack trace and finally in most languages this pattern also allocates memory.

</comment></comment></comment><comment><USER17> > _2\. Switch to object literal_

I've generally called a much more general form of this "data driven programming". (The data here being the mapping.)

See: [https://en.wikipedia.org/wiki/Data- driven_programming#Anothe...](https://en.wikipedia.org/wiki/Data- driven_programming#Another_interpretation) and the referenced [https://homepage.cs.uri.edu/~thenry/resources/unix_art/ch09s...](https://homepage.cs.uri.edu/~thenry/resources/unix_art/ch09s01.html)

> _the important part is moving program logic away from hardwired control > structures and into data_

<comment><USER18> Of course the logical conclusion of any data driven programming technique is to build a DSL and a parser. I always think that if my solution is starting to look like a compiler I'm doing something _right_ since I'm modeling the domain and allowing end users to solve their own problems. After all, what is a compiler/interpreter of a Turing complete language if not (provably) the most flexible data-driven program?

</comment></comment><comment><USER19> You really should just use a for loop over reduce. It's much easier to understand, shorter, and is more performant:

        const truthy = [], falsy = [];
        for (const i of values) {
          if (i) truthy.push(i);
          else falsy.push(i);
        }

<comment><USER20>
        const truthy = [], falsy = [];
        for (const i of values) {
          (i ? truthy : falsy).push(i);
        }

If for some reason you did want to use reduce (and I see no reason to), it would be

        const [truthy, falsey] = exampleValues.reduce((arrays, i) => {
          arrays[+!i].push(i);
          return arrays;
        }, [[], []]);

</comment></comment><comment><USER21> 1\. Yes, love avoiding nested if-statements.

2\. Yes, similar to my love my avoiding nesting, I too like avoiding indentation. Switch -> Case -> Statement+Break vs Object -> Key/Value.

3\. I think this example dips a bit into the arcane. It's not that I can't read it, but you have a reduce starting with two arrays and some conditional logic. I don't often run into it, but I might try to think of where this can apply further.

4\. Yes. Even though I love short concise code, I want the variables and function names to be clear to their meaning. When I read acceptable abstract code I expect the pieces to read like a set of instructions. Ideally the nicely named functions do what they say they do, and no more.

5\. Hard pass. That ternary looks like a blob of characters and I have to think very hard about the logic going on. Not a... if b then a & b else a... I don't like picking on specific examples inside these kinds of posts, but on first pass:

      if(!conditionA) return "Not A";
      if(!conditionB) return "A";
      return "A & B";

Probably give it a nice snappy function name so there isn't a bunch of conditional logic in the middle of a function, when I just want to know the state of two booleans, (with a caveat).

<comment><USER22> I think the problem with #5 is the formatting and use case. Ternaries are really useful for certain things and can make code much easier to read but they are also super easy to misuse. The big thing I find is that ternaries allow for greater code density and better alignment of similar elements.

The style I find works best is as follows. Note that alignment of the ? and : characters (and depending on the code style, the parentheses) is vital for the legibility of this style.

      x = (condA) ? (trueA) : (falseA)
          (condB) ? (trueB) : (falseB)
          (condC) ? (trueC) : (falseC)
          (condD) ? (trueD) : (falseD)
          (condE) ? (trueE) : (falseE)
                            : (final case);

Mind you this has it's uses mostly in low level stuff but I find it a hell of a lot easier to read than a giant if else chain.

<comment><USER23> If I'm reading it right, those false cases shouldn't exist; it should be:

      x = (condA) ? (trueA) :
          (condB) ? (trueB) :
          (condC) ? (trueC) :
          (condD) ? (trueD) :
          (condE) ? (trueE) : (final case);

and the equivalent if/else chain should be:

      if   (condA) {x = trueA }
      elif (condB) {x = trueB }
      elif (condC) {x = trueC }
      elif (condD) {x = trueD }
      elif (condE) {x = trueE }
      else         {x = (final case) }

In which case it doesn't really get you much readability-wise, since the formatting consistency appears in either case; the main benefit really is that ternary is an expression rather than a statement

It's definitely superior, since it's still less noise all around, but almost worthlessly so. And then the same pattern gets covered by switches too...

<comment><USER22> Yep I'm dumb. That's what I get for writing that snippet last night with a few drinks in me.

As for comparison against switches, I find that switches are very limited in a lot of languages (looking at you C/C++). The problem with the if else chain as well is that most code formatters seem to blow it up into the fully expanded form which kills readability.

</comment></comment></comment></comment><comment><USER24> I used to write php and JavaScript at the same time. Turns out nested ternaries get evaluated differently in both languages, leading to some subtle bugs sometimes. I will never write those without parentheses again.

<comment><USER25> iirc php is the only (popular) language with messed up ternary-if associativity, it works as you'd expect pretty much everywhere else

<comment><USER26> I believe you're correct; I'm not aware of any other language with a left- associative ternary.

This will be deprecated as of PHP 7.4[0], and will cause a compile error in PHP 8.0.

However, instead of switching straight to right-associativity, PHP will require explicit parentheses to disambiguate nested ternaries.

[0] [https://wiki.php.net/rfc/ternary_associativity](https://wiki.php.net/rfc/ternary_associativity)

</comment></comment></comment><comment><USER27>
      contentTypes[contentType] || contentTypes['default'];

Don't do this. Untrusted user input could be anything, such as "hasOwnProperty" or "toString", for example:

      contentTypes['hasOwnProperty'] // [Function: hasOwnProperty]
      contentTypes['toString'] // [Function: toString]

<comment> your-nanny I always thought the urge to replace switches with objects was fashionably bad advice.

I get that the object literal approach feels more functional, and that forgotten break statements will cause havoc tho.

Seems like a safeswitch construct is in order, that does not allow dropthrough. something like:

      safeswitch(s) {
        case 'alpha':
          calc(alpha(x), 2);
        case 'beta':
          calc(beta(x), beta(x*x));
      } else {
        // default case here
        calc(x);
      }

alternatively, switch could be modified so that passthrough is _not_ the default, and so, instead of a break statement one would use a passthrough statement to enable that behavior (opt in instead of opt out)

</comment></comment><comment><USER28> "I started deferring to ternaries and nested ternaries and I found I was able to quickly understand at a glance what was happening."

That sort of reads like "I was able to read my own code". That's a good start, but can other people also "quickly understand at a glance"?

</comment><comment><USER29> As a future educator interested in how people think about code, I like these submissions! Whenever things like functional style or language syntax pop up on HN, they tend to create a big stink in comment threads, as people defend their (obviously different) tastes, perhaps by providing contrived code examples, or focusing on why Alice's code is "unreadable" to Bob, rather than understanding "that's just what works for Alice." Honest, unprovoked opinions like in this blog post (like "Hey, this works for me!") are a breath of fresh air.

<comment><USER30> The brain rewires - literally.

So whatever you are used to - you are used to it because your brain wired itself to recognize those patterns. So obviously, when you look at something you are not used to, you are not wired for, it takes a lot longer to process because a lot more of the brain needs to get involved. However, with some time the brain rewires and what was alien now seems completely natural.

Of course, this is within larger limits, you cannot adapt to everything and not to everything at the same speed.

Anyway, my point is, for any such comment people make they should make this test: Do I feel how I feel because of the above, or do I have _actual hard knowledge_ that there is a deeper effect? Meaning, is my comment simply a report of my current wiring state (so, mostly useless to others), or do I have to share actual insights?

Then there's what I wrote in another comment here, about disagreements on waaayyyy to general topics, where people might not actually disagree nearly as much if there was a specific context, but since the topic is so broad everybody comes with their own imagined scenario, depending on their own past experiences, which may very well be best served with very different approaches, but since the discussion remains abstract everybody keeps defending their opinion. Which may actually _all_ be right - for the concrete scenarios they all have in their heads.

For example, there are several commenters here arguing against nested ternaries. I did the same for the longest time. But TypeScript's conditional types require - and officially advertise - exactly this pattern. The way they write it it looks perfectly clear, and I found myself agreeing with there actual concrete code (i.e. types; I posted the link in another comment here).

</comment></comment><comment><USER13> Note: this is mostly about style at the syntax level, not about design patterns at the architectural level.

</comment><comment><USER31> I agree with the 1st pattern.

The 2nd one, there's a caveat about space/GC here.

The 3rd one depends a lot on the situation.

4th one is too obvious for it to be called a pattern, but I agree with it.

5th one is, meh, not really easy to read. I prefer his "bad" example. It could be less verbose, e.g,

if (!conditionA) result = "Not A"

else if (conditionB) result = "A & B"

else result = A

<comment><USER32> Regarding nested ternaries, while not recommended, short circuit evaluations may be even more readable:

return ( (cA && cB && "A & B") || (cA && "A") || (cB && "B") || "neither" );

<comment><USER33> Quick, it's another case of Javsacript Stockholm Syndrome!

<comment><USER32> :-)

However, this would also work in Perl, etc, (anything featuring short-circuit evaluation and type coercion for evaluating conditions.)

</comment></comment></comment></comment><comment><USER34> Re the switch example, another possible solution is the command pattern, where you encapsulate the action in an object.

e.g. (in C# because my JavaScript isn't good):

      interface IContentType {
       void CreateType();
      }

      class ContentPost : IContentType {
       public void CreateType() {
        return console.log("creating a post...");
       }
      }

      class ContentVideo : IContentType {
       public void CreateType() {
        return console.log("creating a video...");
       }
      }

      void CreateContentType(IContentType contentType) {
       // Instead of a switch, you can now do:
       contentType.CreateType();
      }

Mainly useful if you want to do more than one thing depending on content type, of course. It's overkill if you'd only need a single switch anyway.

</comment><comment><USER35> I disagree with the "object literal" because it hides the traces when which is taken. Sometimes it's better to write more self explaining code instead saving a vew lines.

<comment><USER36> It's also dangerous in JavaScript where properties of the Object prototype can mistakenly be dereferenced instead of the default/fallthrough case.

</comment></comment><comment><USER37> I feel Proxies could be a cleaner way to handle default cases in using object literals to replace switches:

        const cases = new Proxy({...cases}, {
          get: (obj, val) => obj[val] || () => {...default case}
        });

It does not add any lines to the definition, and saves you from writing `|| cases[default]` all the time and bugs from forgetting to write it. Additionally, you can also use 'default' as a case.

<comment><USER38> Proxy is slow and unnecessary. Passing around a wrapped object that behaves in this way would be exceptionally surprising. Just move this behavior into a function if you find yourself having to repeat something many times.

</comment></comment><comment><USER39> The 'One loop two arrays' example looks like premature optimisation to me. Going through the list twice is much easier to understand:

      let exampleValues = [2, 15, 8, 23, 1, 32];
      let truthFn = (x) => x > 10;
      let truthyValues = exampleValues.filter(truthFn);
      let falsyValues = exampleValues.filter((x) => !truthFn(x));

</comment><comment><USER40> When I found out about the 1st pattern I liked it, but at another workplace I was advised to avoid it since it creates multiple exit points for the function, leading to confusion. I'm not quite convinced of that and tend to agree with the author of this article, but are there any other arguments against it?

<comment><USER41> There's a very old programming style rule about only ever having one entry and one exit to a function. This rule dates back to the days of assembly programming, where any 'function' could just jump directly into the middle of some other function, or jump out before the end. This made understanding and maintaining code super-difficult, and this rule made a lot of sense.

Eventually, "structured programming" languages like C and Pascal were invented, where you couldn't just leap from one arbitrary part of the program to another. In these languages, the compiler enforced that each function had a single entry point, solving part of the problem. However, for C in particular the rule was still kind of useful - all the resources allocated during the function needed to be cleaned up by the end, so it was still good practice to have a single exit point that always did whatever cleanup was required.

These days, most languages have a garbage collector that will automatically clean up for you. Languages that don't have a garbage collector, like C++ and Rust, generate all the deallocation logic at compile time (the RAII idiom).

If you're using a language designed after the early 1980s, the "single entry and single exit point" rule is either wholly irrelevant, or does more harm than good.

</comment></comment><comment><USER42> Replacing switch, which is compile time construct (converts to an if-else statement or a lookup table or a binary search) with an object which is a run time construct (hash table) is pretty inefficient at least in compiled languages.

</comment><comment><USER43> Early returns are good because they also save a lot of indentation.

</comment><comment><USER44> re: switch to object literal.

Run a perf test comparing execution speed on the two strategies. I've had to defend switch like three times this year; there's a reason it exists, it's super easy for compilers to optimize :\

</comment><comment><USER45> Thanks for sharing this. I didn't know about 'reduce()'. Only thing I'd add is to use TypeScript.

</comment><comment><USER46> Should have applied item 4 to item 3. I don't really know what's going on there.

</comment><comment><USER47> I disagree strongly with the "no foo variables" rule. If you put meaning into a variable name that you use twice, then you are repeating yourself, which is very bad. Thus, variable names should NEVER be meaningful (except maybe when they are used only once). It is better to name your variable "x" with a clear comment of its meaning upon its declaration.

Moreover, mixed-case symbols suck big time.

<comment><USER48> Are you familiar with the concept of 'coding your documentation?' Code often changes without the comments being updated so making the code as informative as possible has lasting benefits.

It is much easier to use descriptive variables than keep the comments up to date.

Additionally, descriptive variables allow anyone to read and more quickly understand the code.

<comment><USER47> > Are you familiar with the concept of 'coding your documentation?' Code often > changes without the comments being updated so making the code as informative > as possible has lasting benefits

Yes, and I agree 100% with it.

It is much better to write self-documenting code than comments. I just contend that descriptive variable names are not the way to self-documenting code. Of course, I'm talking about local variables whose scope should never go beyond a single screen of code. Globally accessible identifiers (e.g. functions) should of course have very long and descriptive names.

> Additionally, descriptive variables allow anyone to read and more quickly > understand the code.

This does not ring true to me, but maybe it depends a lot on the context. At least in numeric mathematics, you always want to name your numbers, vectors and matrices using single letters (as they appear in the corresponding paper). Using "cute" descriptive names hinders a lot the readability of formulas.

<comment><USER48> Ah, I think the context of your programming and mine are quite different. I don't do any mathematical formulations beyond basic manipulations.

I can see where someone writing complex mathematical formulas in C would definitely benefit from single character variable names</comment></comment></comment></comment>


Ask HN: What are your favorite tools for getting work done? - <AUTHOR> I have this repo on Github, though it's more of an all inclusive list. https://github.com/cjbarber/ToolsOfTheTrade
What I'm really curious about is -- what tools do you love so much that you recommend them to others any chance you get?
For me:
- Quip. Start using it. It will eliminate any use for Google Docs and Evernote. It's a much faster version of Google Docs. Make sure you download the desktop and mobile apps though, otherwise it's not as good.
What tool is so good that you know others will love it once they start using it? <comment><USER2> clickable link: [https://github.com/cjbarber/ToolsOfTheTrade](https://github.com/cjbarber/ToolsOfTheTrade)

<comment><USER3> Thanks for pointing this out, useful resource!

</comment></comment><comment><USER4> Bose QC20i noise cancelling earbuds.

Easily my favorite purchase of 2015 so far. It's incredible how much noise they suck out of the room - I typically use Sennheisers for music, but Bose really nailed the noise cancelling technology.

If you're in a noisy open office and listen to music, give them a shot!

<comment><AUTHOR> Awesome! Thanks for sharing :)

</comment></comment><comment><USER5> For News monitorin/Reading: [https://www.feedsapi.org](https://www.feedsapi.org)

Sales: Yesware , Toutapp

Payment processing: Paypal & Stripe

<comment><AUTHOR> Why do you like them? Why are they awesome?

</comment></comment><comment><AUTHOR> I realize I didn't make it clear in the OP -- specifically tools for working. That could still include things like Quora if you get good info from it.

</comment><comment><USER6> I like Quip and I wish they had a Presentation tool also. Which tool do you use for Presentations?

</comment><comment><USER7> meta-note: here are all the TotT lists on github -

[https://google.com/search?q=site%3Agithub.com+toolsofthetrad...](https://google.com/search?q=site%3Agithub.com+toolsofthetrade)

</comment><comment><USER8> index cards, blu-tack, pens, free wallspace.

</comment><comment><USER9> My keyboard.</comment>