Exceptions for control flow considered perfectly acceptable - <AUTHOR> http://www.drmaciver.com/2009/03/exceptions-for-control-flow-considered-perfectly-acceptable-thanks-very-much/ <comment><USER3>
        > Argument by meaningless blither. What distinguishes
        > "exceptional conditions" from "control flow"? I have
        > reached the end of a million element list. This
        > happens one time in a million! That sounds pretty
        > exceptional to me!

Unless you were expecting the list to have infinite length, then this would be a misuse of exceptions. The true logical fallacy here is the author of this post's argument from personal incredulity. The fact that he hasn't yet learned how to distinguish between exceptional conditions and control flow doesn't mean that it's an impossible or meaningless distinction.

<comment><USER4> h2s: Can you explain to us what exactly _is_ the difference between the implementation of flow control during exception throwing and all the other kinds of flow control (including, but not limited to, stack popping).

<comment><USER5> IIRC no standard flow-control construct can do non-local returns (and that's where the Evil lies).

<comment><USER4> How about call/cc and setjmp/longjmp ?

<comment><USER6> And those control flow methods are also widely considered to be tricky and cause a maintenance burden.

<comment><USER7> Just making an observation here. The reason they are tricky and cause a maintenance burden is because they create non-obvious dependencies. You'd have to read a lot of seemingly unrelated code to spot them. Without the explicit knowledge of these dependencies, your changes will have unexpected consequences. (Hence, in a system that tracks all dependencies perfectly, this might not be a problem. This is an experiment I'm trying to run right now.)

<comment><USER5> Exceptions have been called "glorified goto" for a reason. In fine, the OP says that GOTOs are perfectly acceptable.

</comment></comment></comment></comment></comment></comment></comment><comment><USER8> I agree with you. There are way too many cases of people making generalized arguments "you shouldn't do XYZ in programming because it's slow/confusing/etc" that really just have no place being uttered unless they can show mathematical proof it is too much to bother with in _every_ situation. Back in the 80s and early 90s it was "no compiled language should ever be used for critical software", and then in the late 90s and early aughts it was "no VM'd language". Now what? It's all there is! You'd be nuts to NOT use a VM'd language. And the only reason we know any better is because people ignored the received wisdom and just did their own thing.

Keep doing your own thing.

<comment><USER4> I generally agree but I'd replace "unless they can show mathematical proof" with "unless they can show a code profile".

Happy days!

<comment><USER8> I get your point, and that's pretty much what I meant. You need to have very specific reasons. I would argue a code profile would only prove a specific case, instead of a general case. But the point remains, "best practices" aren't theorems. They are used by more programmers as CYA than as good software development strategies.

</comment></comment></comment><comment><USER9> _Writing exception safe code is hard

No it's not. Be sure to clean up anything that could need cleaning up in a finally block._

This is like saying... _be sure to never copy more bytes than the buffer capacity_. Easier said than done.

Writing exception safe code is very hard. Do not take my world for it. Read Alessandro Warth's paper (with Alan Kay as a co-author) [1]. Do not skip section 3...

Let me quote section 3.1:

 _In languages that support exception-handling mechanisms (e.g., the try/catch statement), a piece of code is said to be exception-safe if it guarantees not to leave the program in an inconsistent state when an exception is thrown. Writing exception-safe code is a tall order, as we illustrate with the following example:_

      try {
      for (var idx = 0; idx < xs.length; idx++)
          xs[idx].update();
      } catch (e) {
          // ...
      }

_Our intent is to update every element of xs, an array. The problem is that if one of the calls to update throws an exception, some (but not all) of xs' elements will have been updated. So in the catch block, the program should restore xs to its previous consistent state, in which none of its elements was updated. One way to do this might be to make a copy of every element of the array before entering the loop, and in the catch block, restore the successfully-updated elements to their previous state. In general, however, this is not sufficient since update may also have modified global variables and other objects on the heap. Writing truly exceptionsafe code is difficult and error-prone._

Now, I have seen a lot of code, and very very very few times I've seen someone restoring the state of a collection after an exception blows.

[1] <http://www.vpri.org/pdf/tr2011001_final_worlds.pdf>

<comment><USER10> How would you write this without exception handling, how would that make it any easier? Perhaps do not put the entire loop in the try catch, but just the single iteration.

<comment><USER9> Oh no. I'm not saying it would be easier without exceptions. I'm just saying that the current status of our programming tools makes writing safe code very hard, and exceptions are one more thing you have to think about. I use them a lot...

The authors of the paper propose their "worlds" API as a way to make writing safe code easier. They're still using exceptions, but they would require no cleanup...

The code becomes:

      try {
          in thisWorld.sprout() {
              for (var idx = 0; idx < xs.length; idx++)
                xs[idx].update();

              thisWorld.commit();
          }
      } catch (e) {
          // no clean-up required!
      }

So it's commit for data structures for data structures. If an exception is thrown and the commit line is not executed, no changes will be visible.

</comment></comment></comment><comment><USER11> I think this argument is generally taken out of context; my biggest concern would indeed be that using exceptions for control flow is non-idiomatic _currently_ for most mainstream languages (and yes, Python disagrees).

This means that going against the grain will cost you time (and not you necessarily, but your company / colleagues, etc), and that time better come with some great benefits for it to be worthwhile.

So really, the argument can be looked at from many angles, depending on what value system you are using / what you would like to optimise for. I like to optimise for least surprises / development time.

<comment><USER12> The main problem with the idea of abusing exceptions as a control flow structure is the fact that they were designed to subvert and obscure the flow of control of any program that uses them. If people start to mindlessly pull clever stunts such as relying on exceptions to implement their algorithms then their code becomes unreadable, unmaintainable and unauditable. Not only their code, but any code which happens to include it. Its only purpose is to create an unmanageable pile of spaghetti code which is needlessly hard to trace. And what good comes out of it?

<comment><USER11> Well, I tend to agree; but keeping an open mind, this might just be our subjective rationalisation because we don't understand a newer / better approach.

My point is just that even if the exception-raising approach was better, it'd take a lot of time before it would become truly idiomatic and allow us to reap its benefits, on a software engineering level. I know many would disagree with me on this, however; I like to think I'm a realist.

</comment></comment></comment><comment><USER13> I've used exceptions for flow control in validation before. Worked well.

Basically, you have nested validation code, and the second you hit something which invalidates your data you throw an InvalidDataException(X), catch it at the top of the validation, and then report back to the user that their input is broken because of X.

The alternative was that every method would need to pass back whether it had found a validation error, and every place that called one would need to check that returned value. Huge numbers of lines of code, for no real gain.

(Obviously, this doesn't work if you want to return _all_ the things that are wrong with the data.)

</comment><comment><USER14> I think it all depends on context. I use checked exceptions for handling edge cases in Java, which turns something like this:

        public Session startByInterviewId(Long interviewId, String email, String name) {
            Session session;
            Interview interview = interviewService.getPublicById(interviewId);
            if (interview != null)  {
                Account user = userService.createUser(name, email, interview.getLocale());
                if (user != null) {
                    session = startByInterview(interview, user);
                }
            }
            return session;
        }

into this:

        public Session startByInterviewId(Long interviewId, String email, String name)
                throws Interview.NotActive, Interview.NotPublic, Interview.DoesNotExist, Account.EmailExists {
            Interview interview = interviewService.getPublicById(interviewId);
            Account user = userService.createUser(name, email, interview.getLocale());
            return startByInterview(interview, user);
        }

in which case I'm very much in favor of using exceptions as control flow mechanisms.

Instead of just getting nulls to indicate failure I now even know exactly what caused my error.

I would never even think of writing code like this in JavaScript or Clojure though and I'd guess is that in Scala/Haskell a custom Option would be much better.

<comment><USER15> Interesting, I first looked at the second code segment and _really_ didn't like it. However, I think thats just the whole Java checked exception thing (which I think everyone now regards as a mistake) - if you removed the throws and everything after it on that line it actually looks quite sensible and much better than simply returning null to mean "it didn't work for some reason I'm not going to tell you about".

<comment><USER14> Exactly. It's essentially as close as you can (legibly) get to an Option/Maybe monad in Java.

</comment></comment></comment><comment><USER10> Discussions about performance are statements of fact and can be measured. A jsperf shows that code executing in a try catch for chrome on a mac can be up to 3% slower for me[1]. Let's just get the numbers and show them and if they're valid they're valid, if not let's just dispel the rumors. Arguments about code architecture or best practices for intangible reasons are bikesheds. Just do what you like and be consistent and that's good enough. So if you can't demonstrate slowness, can't demonstrate a real problem as in the code wont work, then there is no real argument. In JavaScript avoid exceptions as control flow though, because they really are slower.

<http://jsperf.com/try-catch-error-perf/3>

<comment><USER16> Oh, wow. On an iPad mini, the exception code is over two orders of magnitude slower in MobileSafari 6.

</comment></comment><comment><USER17> I'm reminded of Kent Pitman's essay "Condition Handling in the Lisp Language Family" ([http://www.nhplace.com/kent/Papers/Condition- Handling-2001.h...](http://www.nhplace.com/kent/Papers/Condition- Handling-2001.html)):

 _To properly understand condition handling, it is critical to understand that it is primarily about protocol, rather than mere computational ability. The establishment of protocols is a sort of before-the-fact hedge against the "prisoner's dilemma"; that is, it creates an obvious way for two people who are not directly communicating to structure independently developed code so that it works in a manner that remains coherent when such code is later combined._

</comment><comment><USER18> "Debuggers will break on exceptions... Decent debuggers allow you to specify which exceptions you break on and which you don't."

This drives me mad in Visual Studio, if you specify a set of exceptions to break on, then later decide you need to catch all exceptions, there's no easy way to go back to the first set.

I'm surprised this question and partial answer on Stack Overflow haven't got more votes:

[http://stackoverflow.com/questions/5452480/how-to-save- and-m...](http://stackoverflow.com/questions/5452480/how-to-save-and-manage- debug-exceptions-preferences-in-vs2010)

</comment><comment><USER19> I was going to do a post rebuking the points made, but rather unsurprisingly it seems plenty of others already have done so, in a manner much less arrogant than OP's.

<http://www.javaspecialists.eu/archive/Issue187.html> and [http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?pa...](http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2) are two well written sources of many that Google turned up on the subject.

<comment><USER20> I would encourage you to do that post. Because the two documents you linked to are very unconvincing when placed beside David MacIver's essay.

The first link (<http://www.javaspecialists.eu/archive/Issue187.html>) says the code was hard to understand, that this is the 'wrong' way to use exceptions, that reusing a normal exception type instead of an exception intended for control-flow might mask other exceptions, and that debuggers will pause. These are MacIver's points #4, #2, #6, and #5 and he debunked each one.

The second link ([http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?pa...](http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2)) says "This not only makes the code difficult to read, but also makes it slower." That is MacIver's points #4 and #1 and he debunked them.

Do you feel that any of MacIver's points are incorrect? Do you know of any arguments that he did not already address?

<comment><USER6> He didn't do any debunking. He merely asserted the opposite; and not very convincingly.

He claims exceptions are fast enough. But though he proposes that exceptions are generally usable, he only backs this up for java, and AFAIK the statement is in general false. In other words, in most contexts, using exceptions for control flow is expensive.

He claims that "decent debuggers" won't pause - but which decent debuggers is he talking about? Because that's not at all the norm. Furthermore, as soon as you attach a debugger, it's likely _all_ exceptions are much, much slower. Having code that runs orders of magnitudes slower in debug mode is a problem in and of itself because it means that some issues can't be properly debugged. Furthermore, many debuggers are designed to work with convential code - <USER2> other words, if they let you filter exceptions, it's not in a practical way intended to be ideally usable as control flow.

He claims that it's not hard to understand, but provides no support. If you're going to deviate from convention, you should have a reason; some argument. Merely the fact that it _is_ conventional is a plus since that simplifies communication and maintenance. And frankly, having read his article, I don't see the advantage - he's doing it differently, but what's the point? What's he winning?

He claims that the arguments against exceptions aren't well documented, but that's simply because he's searching rather narrowly. All the way back to dijkstra's article on goto such control flow existed, it just wasn't called the same. And exceptions are essentially non-local goto's.

Finally, he's doing an end run around the type system. This is about as problematic as a null reference; i.e. it's going to cause constant pain. You've documented your program by type annotation which is good for humans, good for API discoverability (autocomplete) and allows some static checking. By doing this you're adding a hole that isn't properly annotated. In some languages, e.g. java with checked exceptions, this is less of a problem (but then it's also quite wordy). And again, it isn't true in general - maybe for java.

In a purely functional language with checked exceptions, I can see his argument holding water - Say, some Haskell variant. At that point, the distinction between this approach and discriminated unions is very small - indeed, if you use some nice monadic syntax sugar you could probably exchange the one for the other.

But really, why not just use discriminated unions in the first place?

<comment><USER20> > He claims exceptions are fast enough.

This is going to vary across languages. In cPython for instance (since I happen to know it), exceptions are at least as fast as looping through an iterator, since exiting from a loop is done via exceptions. He included a link to an article showing that exceptions are quite fast on the JVM. I am sure there are other languages where the implementation of exceptions is slow -- in these languages this is a valid objection to using exceptions for flow control. And I don't care how fast the code runs under a debugger. Perhaps you do, but really, I don't; we must have very different use cases.

> He claims that it's not hard to understand, but provides no support. [...] I > don't see the advantage - he's doing it differently, but what's the point? > What's he winning?

It ISN'T hard to understand if used in a consistent way... I don't need any further evidence of that than my own observations. But you are absolutely correct that the argument needs evidence of exceptions being clearer. Perhaps it would help to provide an example of a triple-nested loop with numerous boolean condition variables contrasted with the same loop using exceptions for exit. I don't think exceptions for flow control are more clear in all circumstances, or even in most circumstances, but I believe that they are in some circumstances, especially in cases where substantial work needs to be done in order to determine whether one should proceed: doing the work twice is inefficient, and splitting the function into part-A (everything before the decision point) and part-B (everything after it) can be much less readable than using an exception if part-A sets up variables and data structures used in part-B.

> All the way back to dijkstra's article on goto such control flow existed, it > just wasn't called the same. And exceptions are essentially non-local > goto's.

No, I think they are fundamentally different. The problem with GOTO, and with programming before structured programming was invented, was a problem with arbitrary ENTRY points; arbitrary EXIT points do not cause this problem. My more detailed thoughts on this can be found at [http://mcherm.com/permalinks/1/in-defense-of-the-much- malign...](http://mcherm.com/permalinks/1/in-defense-of-the-much-maligned- goto)

> Finally, he's doing an end run around the type system.

This seems to be a completely new argument and one which wasn't addressed. I am very interested, but somewhat confused. How does the use of exceptions undermine the type system? Is it because the type of the function, instead of being "Returns an Int" becomes "Returns an Int or raises an exception"? If that happens for all functions, how is it confusing? Can you give me an example of how things could go wrong?

> In a purely functional language with checked exceptions [...] if you use > some nice monadic syntax sugar [...] the distinction between this approach > and discriminated unions is very small. [...] why not just use discriminated > unions in the first place?

I agree, as long as the language syntax supports doing it easily that is the better approach.

</comment></comment></comment></comment><comment><USER21> The author notably tries to refute arguments against the use of exceptions for control flow, but doesn't present any reasons (at least not in this article) as to why this usage might be a _good_ idea.

There's no compelling reason to introduce odd, non-idiomatic code patterns when they don't confer a significant benefit. Some people here argue that the "intent" of exceptions in a language design is not relevant compared to what _can_ be done with them. In general, I disagree with this. Language designers' intent informs the expectations of readers of code, and your readers' expectations are important. Code is a form of writing for communications, both with the computer and with maintainers; it's not artistic writing, where you might deliberately violate expectations or norms in order to delight or surprise your audience.

That said, using exceptions as a method of transferring control to a non- local, dynamically-bound location is a powerful technique for which few languages offer an explicit alternative. It's also difficult for readers to analyze, so it should be used sparingly. For instance, I can think of reasons that one might use this technique within a container or algorithm library, but I can't think of a good reason for a container library to force this control flow idiom on callers by throwing exceptions to signal common situations.

(As usual, Common Lisp is unusual here. It has a throw/catch feature which is explicitly a flow control mechanism, and not just an error-handling mechanism. The standard documentation is interesting in that the Notes section suggests exactly _when_ one would want to use this mechanism: [http://www.lispworks.com/documentation/HyperSpec/Body/s_thro...](http://www.lispworks.com/documentation/HyperSpec/Body/s_throw.htm))

<comment><USER22> Given that the article was a response to criticism of a previous proposal of mine on grounds that it used exceptions for control flow, and given that I linked to that discussion (on the page for the proposal in question) in the opening paragraphs of this one I probably felt that the reasons for using exceptions for control had been adequately covered at that point.

But I was probably not trying to suggest you should regularly do this (certainly I wouldn't suggest that now), only that if you find you have a good reason to do it you shouldn't be afraid of it.

<comment><USER21> Sorry I didn't follow the link. Given the link's text, "I have been invited", I didn't expect it to lead to background information, but rather just to, well, an invitation. My bad.

</comment></comment></comment><comment><USER23> I couldn't agree more and have long been arguing that we should use exceptions when they are a useful tool for the job because their semantics do what we need at the time. Sometimes that means exiting early because you can't do what you've been asked to for some reason. Other times it means exiting early because you've already done everything you were asked to and there is no point in continuing further.

The main thing I would add to the original article is that the author is being a little kind to the critics on some of those points. For example, not only do exceptions not inherently need to be slow, they can actually be _faster_ than the "classical" equivalent via return codes and the like. This is essentially because any jump-table-based exception mechanism means the non-exceptional control path can omit all the test logic that would serve only to exit the current block early. That could both reduce the size of the non-exceptional code and reduce the number of potential branches, each of which can be helpful for optimization. Although it's rather less significant in performance terms because it only tends to happen once, when an exception does occur you also don't have to run through all the individual levels of unwinding the stack with a jump table approach, as you can jump straight to levels that actually need to do something on their way to handling the exception and skip over anything that was just going to return immediately anyway.

As another minor data point, I haven't found exceptions in C++ to be slow. Most/all of the major compilers seemed to have moved to a table-driven approach last time I used a broad set of them. The nasty overhead in C++ is more likely to be in the size of the generated executables; I've seen a compilation with exceptions disabled shave nearly 1/3 off the executable size.

Of course exceptions have somewhat different meanings and can have very different implementation overheads in different languages, so I'm not arguing that all advice to use them sparingly is bad. As always, it's important to separate the dogma from the rational arguments.

</comment><comment><USER24> Back in my early years as a software developer I once though that I could make some really eligent code by using exceptions for control flow. I used it to do a form of what I now know is pattern matching. It really cleaned up the code and made it super easy to extend and read, but it was a _terriable_ idea. It was slow and since nothing was checked by the compiler I found myself often at my root catch block trying to figure out how my nested catches didn't work.

Exceptions are not suitable for control flow. Yes they work and can sometimes give nice features, but typically they are just showing that you have poorly designed code and should be doing something differently.

'/s/Exceptions/GOTO/g' and you have essentially the same argument

<comment><USER20> > '/s/Exceptions/GOTO/g' and you have essentially the same argument

Absolutely untrue. Eliminating GOTO was a major step forward in programming language design, one better known as "Structured Programming". The advantage was that it eliminated random entry points so that bits of code ("subroutines", "methods", or "functions") could be reasoned about independent of the entire program by starting from the "top" and working forward. Arbitrary exit points (like exceptions, break, and return) still permit this reasoning; allowing GOTO to target arbitrary statements makes it impossible to reason this way.

For a better explanation, see this essay I wrote on the subject: [http://mcherm.com/permalinks/1/in-defense-of-the-much- malign...](http://mcherm.com/permalinks/1/in-defense-of-the-much-maligned- goto)

<comment><USER24> So exceptions do add structure as to where you can go _to_ but they serve the same purpose in where you can come _from_ Its a little easier to trace since you are scope bound, but its still harder then being able to trust the control flow of your code. Additionally because you can't trust control flow of your code ( since any time the sub routine can essentially longjump to some place higher in your stack) you are now required to context wrap all your code in try blocks essentially implementing bookkeeping that the compiler will do for free if you just design your code in a sane manner.

This is why java implemented typed exception throwing because it the only way to have some semblance of safety when programming with exceptions. I am even more disheartened to see that the author uses my beloved scala and in still trying to do this kind of nonsense, when we have plenty of good tools at our disposal to negate the use of exceptions for control flow.

<comment><USER20> I'm not completely sure I am understanding you.

I think that RAISING exceptions is just a non-local exit point, like a break or return which does not make it difficult to reason about one piece of code in isolation from others.

I think that CATCHING exceptions is a clearly marked 'entry' point: one can only arrive in an exception handler from an exception raised within the corresponding try statement, and the place that you arrive is clearly marked.

The one bit that is more confusing is throwing right through without an exception handler: in other words, code you call might raise an exception which your code does NOT catch, and thus exit your function prematurely: you might thus allocate some resources and fail to deallocate them safely.

Are we saying the same thing here?

<comment><USER24> Somewhat. You are correct to say were know that the exception was raised in the try block so we have an idea about where it came from, but unless each try block is one statement long you don't know where the exception came from . That's the disconnect. When in a try/catch block you know where your going ( the catch ), but you don't know where you came from. That is almost as problematic as GOTOs in that planning for all program states is once again a headache ( did I open that socket , is that memory free'd ,... )

<comment><USER20> I see what you are saying. I think I avoid this problem by having a policy of not modifying fields arbitrarily within a try statement.

Let me try to give some examples. I write things like this:

      Person p = getThePerson(id);
      try {
          storePersonToDatabase(p);
      } catch(DatabaseException err) {
          generateAlert('Could not save person');
      }
      doMoreProcessing(p);

In this case I know that p was initialized because it happened outside of the try statement. But I try never to do things like this:

      Person p = getPrimaryAccountHolder();
      try {
          storePersonToDatabase(p);
          p = getSecondaryAccountHolder();
          storePersonToDatabase(p);
      } catch(DatabaseException err) {
          generateAlert('Could not save person');
      }
      doMoreProcessing(p);

If I did that, then there would be no way to know whether p was the primary account holder or the secondary after the try statement when I call doMoreProcessing(). On the other hand, it's perfectly OK for me to do this:

      Person p = getPrimaryAccountHolder();
      try {
          storePersonToDatabase(p);
          Person p2 = getSecondaryAccountHolder();
          storePersonToDatabase(p2);
      } catch(DatabaseException err) {
          generateAlert('Could not save person');
      }
      doMoreProcessing(p);

...because with this pattern I don't know, after the try-catch, whether the variable p2 has been initialized or not, but I also don't care because it is out of scope and can't be used.

If I didn't follow this practice, then I think the problem you describe would be an issue for me: not knowing which of several possible locations was the source of the exception would mean I didn't know how the variables had been set. Interesting... I learned something today.

<comment><USER24> I think we are on the same page now. What your describing works well If you do it _everywhere_ and also _require_ exceptions to be handled, much like Java does (mostly) in c++ its a total crap shoot since destructors don't run if you pop their stack.

</comment></comment></comment></comment></comment></comment></comment><comment><USER25> Exceptions break normal encapsulation mechanisms but as long as you code is exception safe, nobody cares, it's just that exceptions are the new goto, and nobody likes goto.

However they are only few good reasons to use goto, and exceptions for control flow should be treated the same.

Therefore the point we should make against exceptions for control flow is not exceptions are for exceptional circunstances but; as a rule of thumb exceptions are for errors. And indeed they help a lot in not obscuring normal program logic, we allready have other tools for control flow.

Nobody likes goto (and my bad english)

bye

</comment><comment><USER26> It entirely depends on the language as to the level of acceptability of using exceptions for control flow. In Java, it's _moderately_ routine to get a random exception or two that you recover from and go along your way merrily. Python similarly is A-OK much of the time.

In Objective C, exceptions are "he's dead Jim" territory.

Some of the differences of use are caused by the implementation of exceptions in those environments and the expectations programmers of libraries in those environments to what happens when exceptions occur.

<comment><USER27> Many years ago, there was a language called TOM. TOM was a descendant of Objective C, but with garbage collection, blocks, some other stuff ... and a Common Lisp style condition system (before Objective C had exceptions or blocks or GC or ...).

<http://gerbil.org/tom/>

Sadly dead once the author got his PhD though.

<comment><USER26> > garbage collection, blocks

Blocks exist in Objective C. GC did, but was replaced for Automatic Reference Counting (ARC).

ARC is good enough in mobile and probably better for Desktop.

<comment><USER27> Let me quote a couple of relevant parts of my comment:

> Many years ago

> (before Objective C had exceptions or blocks or GC or ...)

TOM had the things that I mentioned back in 1998, 1999, maybe earlier.

Objective C has come a long way since then.

</comment></comment></comment></comment><comment><USER28> Yeah, sometimes, using exception as control flow is the only simple and clear way. I do use it occasionally.

ex. Lets assume that a problem can be attacked as algorithm1 (A1), and algorithm2 (A2). A1 is fast but cannot handle some corner cases while A2 is slow and can handle all cases. we also assume that there is no easy way to tell whether A1 is good or not without invoking A1.

So the function can be implemented as:

void A()

{

      try {
        A1();
      }
      catch (e) {
        A2();
      }

}

void A1()

{

      .....
      if(corner case) raise();
      .....

}

Is there a simple way to avoid using eceptions here?

<comment><USER29> Yup. Have some sort of error code that is passed back by A1() or A2().

      bool A1();
      bool A2();

      void A(){
          bool result = A1();
          if (!result){
              A2();
          }
      }

Instead of your "if(corner case) raise();", you would then have a "if(corner case) return false;".

However, it becomes more difficult if you want a return value. Suppose that your A() function was as follows.

      double A(){
          double result;
          try{
              result = A1();
          catch (e) {
              result = A2();
          }
          return result;
      }

Then, you are already using the return value to indicate something other than success or failure of the operation. You could have A1 and A2 return some special value that wouldn't return normally. For example, if it is some distance, negative values could represent invalid responses.

      double dist(){
          double output = dist1();
          if (output==-1)
              output = dist2();
          return output;
      }

However, sometimes any value could be a valid value. Then you need to pass things by pointer or reference in order to have two outputs, one for the value and one for the success/failure.

      bool A1(double* output);
      bool A2(double* output);

      double A(){
          double output;
          bool success = A1(&output);
          if (!success)
              A2(&output);
          return output;
      }

It is in this last case when exceptions start being much cleaner, since they provide a clean way to indicate that the operation has failed.

</comment></comment><comment><USER30> The reason why using exceptions for control flow is bad is because it violates the Samurai Principle. Now why do I refer to a cheesy made up principle instead of explaining what I mean? Why do people use "exceptions are for exceptional situations" and similar empty expressions?

Because programming is just as much about _communicating intent_ as it is about writing efficient code! Following guidelines and maxims is extremely useful because if both the writer and the reader understands the protocl, then communication is smoother.

The "Exceptions are for exceptional circumstances" protocol means that the reader of the code doesn't have to wonder "Is this a control flow situation? Is this exception supposed to be handled? Where does the code resume?"

Following the Samurai Principle (<http://c2.com/cgi/wiki?SamuraiPrinciple>) similarily eases the cognitive load of the person reading the code. It allows you to treat each callable piece of code as an isolated unit whose value is equal to what it returns. For non-critical code, you can completely forget about exception handling because you dont need to bother. However, if an exception is thrown you can be equally assured that something unexpected happened. It was to hard for the "samurai function" to handle. Simple and extremely convenient.

One example of not following the Samurai Principle or "exceptions for exceptional situations" happened at my last job. We were an mobile payment processor and trying to issue a charge to a customer when their balance was to low would result in a BalanceToLowException. Except that wasn't anything out of the ordinary, customers would often not have enough funds! The situation would be handled by retrying the transaction some other day. The API for charging customers would better have been designed returning a two tuple (chargeStatus,errorMsg) so that the following code could continue in the same location whether the charge succeeded or not. Throwing exceptions for ordinary events lead to spaghetti code.

You can see similar misdesigns in some database ORM:s in which some queries throw silly NoRecordsFoundException which user code is forced to handle. Or Python's classic

        try: return int(somestr)
        except ValueError: return None

Often the string you're passing to int() is user input so you _expect_ it to often be non-numeric.

</comment><comment><USER31> Oleg Kiselyov uses exceptions for control flow in his Delimcc library for Ocaml, and if that doesn't establish that doing so is perfectly acceptable, I don't know what could.</comment>


Microsoft adds free root certificate authority to Windows - <AUTHOR> http://www.istartedsomething.com/20091010/microsoft-free-root-certificate-authority-windows/ <comment><USER2> These stories make me cringe. The security of SSL is as good as the verification practices of the laziest CA. We need fewer of them, not more, and any CA that can give certificates away for free is guaranteed to have atrocious practices.

It appears that this company authenticates you by verifying that you can receive email at the domain that you want the certificate for. In addition to completely defeating the purpose of SSL by sending secrets in the clear over SMTP, ability to receive email at a certain address is no proof of ownership of that domain. Unfortunately, though, StartCom didn't invent this stupidity. I already discovered a few months ago that I can get Thawte to issue me an SSL certificate for hushmail.com.

<comment><USER3> Look at it the other way: The CAs who are charging hundreds of dollars have atrocious practices, so StartCom is actually an improvement.

</comment></comment><comment><USER4> Could we just throw current CA's out and get some sensible, working organization instead. Basically anyone can get certificate for any domain nowdays, CA's care only about money. That kinda defeats the whole purpose of having CA's in the first place. Okay, maybe applying for *.google.com certificate could be noticed in the current system, but thats about it.

Why couldn't eg domain registrars grant certificates for the domains they have sold? Wouldn't that kinda simplify and be a lot more secure than the current mess.

<comment><USER5> I wasn't aware it was that easy. I thought, at the simplest, they verify the whois information of the domain and you must be an admin contact for the domain. What would you suggest they do beyond that or besides that?

How can I get *.ycombinator.com for example?

</comment></comment><comment><USER3> Are they pushing this patch out? The article gives the impression that XP/Vista users would have to patch manually, which isn't going to happen.

<comment><USER6> On XP, through Windows Update. On Vista, automatically the first time you visit a StartCom-signed site.

</comment></comment><comment><USER7> Does this mean we don't have to pay for ssl certs anymore? If ie, firefox, and safari support this company's free certs - what's the problem?

<comment><USER8> did you read the article?

 _Granted Firefox and Safari has supported many of the certificate authorities issuing free certificates for some time, Microsoft has not, until now._

<comment><USER9> Did you notice the "anymore"?</comment></comment></comment>


4chan's nemesis: thenicestplaceontheinter.net - <AUTHOR> http://thenicestplaceontheinter.net/

<comment><USER2> I'm good enough, I'm smart enough and by gosh! people like me!

</comment><comment><USER3> silly fluff, but in a good way...</comment>


Ask HN: TechCrunch for enterprise startups? - <AUTHOR>

Anybody know of a good resource to read up on enterprise/b2b startups? All the tech blogs I've seen seem to focus on consumer internet companies. <comment><USER2> GigaOM seems to cover enterprise/b2b startups more than other tech blogs. You've probably run across it already, but if not then it's worth a look.</comment>


The Acquisition King: Reckitt Benckiser - <AUTHOR> https://aalokbhatawadekar.in/2020/07/08/reckitt-benckiser/ <comment><AUTHOR> Reckitt Benckinser or RB as we know it today owes a great amount of its growth to the outstanding acquisitions that it had done in the past. The author has listed many such acquisitions and the resulting product line that has helped RB enhance its portfolio of products.</comment>


IOS Notifications: No More, No Less - <AUTHOR> http://www.macstories.net/stories/ios-notifications-no-more-no-less

<comment><USER2> By jailbreaking iOS, one can significantly improve the notification experience by installing LockInfo and enabling its InfoShade option. Obviously this is far from a perfect or complete solution, but it's a step forward in the right direction.

</comment><comment><USER3> A UI should follow the same rules of etiquette as human conversation - if it would be rude for a human to interrupt you constantly when you were trying to do something, it's just as bad for your UI to do it.

A good notification system needs to be context-aware, to realize that there's a difference between a device sitting idle on a desk or in your pocket, and a person playing a game, writing an email, or watching a video.

Even within apps, there should be context. I may be fine with an unobtrusive notification appearing when I'm reading an email, for example - but if I've got the keyboard up and I'm typing, don't place a button right where I was about to press a key, or shift the location of UI elements while I'm interacting with them.

The trouble with the iOS (and Mac & Windows, for that matter) approach to notifications is that they try to be "user friendly" when they should be "user subservient."

</comment><comment><USER4> TFA suggests that a single icon/menu for all apps that have generated any notifications, in other words: all notifications appear in the same list.

This sounds like a bad idea to me:

First, you can't see at a glance whether you've just received a text message (something you might want to respond to immediately) or an email (which you don't immediately care about).

We would need a user to be able to control which apps can generate notifications. Otherwise every shovelware developer is going to want to put their crappy icon in that menu. And then we have the iOS equivalent of a Facebook news feed full of virtual farming updates!

Second, not all notifications are equal. On WebOS, a media player notification (new song is playing) is separate from the notification about how many texts are unread. A hundred texts can come in, and they won't bury the notification about the music playing.

I hope they start with the WebOS notification system and start improving.</comment>


Educate HN: AJAX doubt - <AUTHOR>

I really like the idea of making a rich web application using static pages + AJAX.
I don't understand how would I solve this though. In something like Django one would just render the variable in the template.
The problem: browser visits twitter.com/john - or twitter.com/user/john to makes things simpler.
We should then serve a static page - say user_profile.html, which displays the static part of the user profile page and loads Javascript that will load the dynamic, user-specific part using AJAX.
Now, how would one pass the username "john", from the URL to the javascript, so we can then make the AJAX calls like get_user_tweets("john") ? <comment> mike-cardwell You would parse document.location to obtain information from the address bar. Eg:

document.location.pathname would contain "/user/john" if the url was <http://twitter.com/user/john>

This isn't really a javascript help forum.

<comment> mike-cardwell Also, good web design practice, (and law in some countries) dictates you should make a site which doesn't rely on javascript, and only uses it to enrich the experience.

<comment><USER2> _good web design practice_

Who's good design practice? The world moves on, web apps are build with JavaScript, people now respect JavaScript as a decent language that has it's quarks and the DOM has been tamed by the toolkits. The best in the industry are flocking to JavaScript based web application and abandoning the contorted server side frameworks in droves. Why? because the programming model is simple, the separation of concerns and disciplines are clean and the ability to prototype rapidly on the front end is not bound by the rigor that the back end requires.

<comment> mike-cardwell Industry wide, commonly considered and accepted, best practice.

Make sure everything works without javascript, and then add as many bells and whistles as you like with javascript afterwards.

<comment><USER2> Most people make a business case for any feature that they implement or technology that they use. Just because something is a recommended practice does not mean it is a best practice.

When one looks at the numbers of older non-supporting browsers and people who intentionally turn Javascript off. It does not make a compelling case to adopt an older more costly development model that cannot support the superior feature set of the new development model. Just as COBAL was once a recommended practice it no longer is, the world moved on.

As for the 5% or less that still cannot execute Javascript for whatever reason, study after study has highlighted that you spend an exponentially larger volume of money to chase this market than you do on the 95% solution. Money that for all intents and purposes would be better spent trying to increase conversion in the 95% market or adding new revenue stream to provide to the 95% market.

So when we talk about best practices we should be mindful of the technical egos, as well as lack of any business grounding of some of the people that make up "Best Practices" that believe their way is the only way and always offset it with marketing 101.

JSP has best practices, ASP has best practices and PHP has best practices some conflict with each other and none are weighed against what you are personally trying to achieve. At one point in time in the industry unified programming environments where the DB, the code and the execution platform where rolled up into one technology where "Best Practice". The list of no longer in vouge best practices stretches from hear to Siam.

Whenever best practice is seen it should serve as a red herrin that someone may not be listening to opposing view points. People in the technical industry following other people blindly is why we get so much group think and brain dead design patterns from people who believe in the Highlander model of development. JavaScript is standards compliant and that is all that should matter, the rest is just working the numbers.

<comment> mike-cardwell If you make a website that requires javascript to work. If you don't provide a non-javascript alternative. You have made a website which isn't accessible, and when you grow large enough, you will probably be sued.

<comment><USER2> Come on now, [http://www.dojotoolkit.org/reference- guide/dijit-a11y-statem...](http://www.dojotoolkit.org/reference- guide/dijit-a11y-statement.html) . I am doing a project that is using Javascript for a huge public tech company, who gets sued all the time for accessibility for the specific reason that JavaScript can be used to increase accessibility.

<comment> mike-cardwell I fail to see how that's relevant. There's quite a marked difference between:

1.) Creating a website which uses JavaScript to increase accessibility

And:

2.) Creating a website which requires JavaScript in order to function

I only have a problem with number 2.</comment></comment></comment></comment></comment></comment></comment></comment>


MOVE an injury not RICE (2017) - <AUTHOR> https://thischangedmypractice.com/move-an-injury-not-rice/ <comment><USER2> That "inflammation exonerated" section is excellent. I think OTC NSAIDs are abused every bit as much as opiates, though not as harmful obviously. The point should be to manage your pain, not eliminate it. If I am still injured, I should know it so I don't over do it before my body has healed. Let your body do it's thing to fix the root cause - don't just bandaid it. I've known people to preemptively pop 800mg ibuprofen before a workout, to numb the pain they know is coming. Terrible idea, IMHO.

<comment> inspector-g > If I am still injured, I should know it so I don't over do it before my body > has healed

To address this specific point (not the rest of your comment, which I largely agree with): this is in line with the "old" bio-medical model of pain, and not up to date with the modern bio-psycho-social model of pain. In many cases, the biological insult to tissues will fully heal far in advance of pain subsidence, or conversely will heal long after pain subsidence. The point being that a pain experience is not an accurate indicator of the state of one's tissues.

For a primer on this more modern model of pain experiences, please give this excellent video a watch: [https://www.youtube.com/watch?v=lCF1_Fs00nM](https://www.youtube.com/watch?v=lCF1_Fs00nM)

<comment><USER3> So sometimes it overshoots and sometimes it undershoots, but is there a better heuristic readily usable by non medical professionals? (Sorry if this is addressed in the video; I have only read the summary)

<comment> inspector-g Well, the field surrounding pain/injury is large and nuanced, so not only is that a difficult question to answer but it's also _sort of_ the wrong question. And, firstly, I strongly recommend watching the linked video (if you have time). But I'll try my best here anyway.

Let's start with injury - what constitutes an injury? As in, how should the word "injury" be defined? This is a more complex issue than one might initially assume; not all pain is associated with an insult to tissue, not all insults lead to mechanical damage, insults that _do_ lead to damage do not necessarily lead to pain, etc. So, mostly, injury tends to be defined as anything that leads to a reduction in function/performance in an organism. The ramifications of this definition are important, because things like a compound fracture, delayed-onset muscle soreness, and pain with no (known) underlying cause all meet the definition's criteria.

That last bit is the most important (and why I strongly recommend watching the video), because pain is _not_ an input to the brain, rather it is an output of some function in the brain that takes a large number of inputs _other than pain_. This is basically the crux of the whole bio-psycho-social model, and why I said the original question is sort of the wrong question regarding injury. So here's the revelatory part, as it relates to the original question: aside from large and obvious traumas like a compound fracture, one cannot conclude that, because they are experiencing pain, physical damage to tissue has taken place. So looking for a heuristic to determine the state of some tissue after experiencing an event that led to pain is not really the right approach from the beginning, as one cannot be confident (and should not assume) that the tissue's state is awry at all.

<comment><USER4> I'm afraid I must strongly disagree with your comment, or at least your conclusion.

The existence of pain itself is predicated on its accurate coupling to injury, since the purpose of pain is inhibitory: this hurts, so stop doing it, [because tissue is injured], and it must not continue to be injured.

There are of course some counterexamples where this line of thinking fails: pain localized to previously amputated limbs comes to mind.

But overall I can think of very few instances where this is true. The _magnitude_ of pain may or may not be proportional; the _location_ may or may not be correct (as in referred pain); but in the vast majority of cases that can I bring to mind, pain very much does indicate tissue damage.

(And the biopsychosocial model of pain doesn't change that! The brain, after all, is tissue.)

<comment> inspector-g > pain itself is predicated on its accurate coupling to injury, since the > purpose of pain is inhibitory

> pain very much does indicate tissue damage

These statements are not supported by modern research. The bio-psycho-social model indicates that pain is a threat _detection_ and deterrent mechanism, NOT a "status report" _from_ the painful tissue to the brain. In other words, the brain is concerned that something might lead to physical trauma, yet none need to have taken place for pain to be generated.

There are certainly biological inputs to the "pain generator" function of the brain (like sensing a foreign object touching one's skin), but psychological factors/contexts and social factors/contexts can be equally strong inputs (and ultimately generate a significant pain experience without any, or with very little, biological input).

Think of the magnitude of pain response to a given situation as an indicator sitting somewhere on a spectrum between "benign" and "dangerous". The more psychologically threatened one feels, the more the pain response will be shifted toward the "dangerous" end (i.e. higher magnitude). The more socially threatened one feels, the more the pain response will be shifted toward the "dangerous" end.

Here is a somewhat contrived but favorite example of mine. One night, you wake up to go to the bathroom. In the dark, you unexpectedly step on your child's lego brick left on the floor, and it hurts immensely - it feels like the pegs are actually spikes! This is mainly because of how it has surprised you; the context is that it's dark, you expected the trip to the bathroom to be just a few simple steps, and (for sake of argument) have never stepped on a lego before. Your brain feels rather threatened by this surprising situation and generates a large pain response. Now, a night or two later, it happens again, and though it hurts it definitely isn't as bad. Another night or two later, it happens a third time, and barely hurts at all (you're basically to the point of expecting it now). I think we can agree that no tissue damage has really been done, and if pain was simply a state-of-tissue indicator then the magnitude of pain should have been the same each and every night. Additionally, if tissue damage need be present for pain to be present, why did it hurt at all?

Lastly, I'll note that lack of apparent examples != lack of evidence.

</comment></comment></comment></comment></comment></comment><comment><USER5> For those just reading the headlines and comments: before you try this at home, please note that the paper indicates that this EXCLUDES certain types of injuries, such as fractures.

</comment><comment><USER6> What athletes and coaches have known for decades, basically.

RICE is for serious things that render you incapacitated.

If you can remain active with the injury then you do so, and monitor it: if it gets better with activity, then keep with it. If it worsens, back off. Very simple.

<comment><USER7> The physically active people I know (of whom I am not one!) seem to follow this pattern compulsively anyway. They always hurt themselves being physically active and they hate not being physically active so they get back out there again.

</comment></comment><comment><USER8> This seems intentionally misleading. RICE is acute care immediately following an injury, to prevent further damage and relieve pain. MOVE (a terribly strained acronym) is for rehab/physical therapy. What is newsworthy here?

</comment><comment><USER9> On a slightly related note: I've never been able to get into the "start your day with a cold shower" thing, and find myself skeptical of its health benefits. I find that I need a very warm shower to massage my muscles, while a cold shower leaves them cramped and sore, reducing my ability to heal from exercise and engage in extensive physical activities through the week.

<comment><USER10> I do both. I take a normal hot shower for everything up until I'm completely soaped up; then I switch to a cold shower and rinse myself off.

<comment><USER11> Same, if only to ease the transition out of the shower

</comment></comment></comment><comment><USER12> Very timely article, as I'm currently sitting in the doctors office waiting room to be seen for a sprained ankle.

> The resulting vasoconstriction from cooling, not only reduces tissue > oxygenation with necrosis if extreme, but inhibits the inflammatory response > needed to initiate healing.

Wondering if this means applying heat would speed up healing due to increased blood flow.

<comment><USER13> There's a balance. Excessive inflammation pushes joints and ligaments out of position. However, it's the way the body brings fluids to heal the injury.

Manage it, don't let it go wild, and don't try to drug/compress/ice it into oblivion and make it last longer.

Currently have my moderately sprained ankle elevated. This is the worst sprain I've had in 20 years, so taking it really easy.

</comment></comment><comment><USER14> This is covered at length in a book titled "Good to Go." It was such a good read and addressed so many things that I'd taken as a given about recover. Highly recommend the approach and the style of the author.

[https://www.goodreads.com/book/show/40180017](https://www.goodreads.com/book/show/40180017)

</comment><comment><USER15> I would have been okay with RICE. After breaking 1.5 arms (well, it felt like it, just an elbow fracture), I wish I had known about RICE. Six hours later, in A+E I get a bit of fabric and some string with the 'you've broken it mate!' serenade from the X Ray department.

Two weeks after that I watch something about sports injuries and realise how much better things would have been had I just bought some ice after my bicycle crash and got myself a cab home instead of riding the ten miles or so, up and down over a big hill.

This was with the NHS and if I was running that department I would have a big bag of ice, right there on reception with a 'help yourself' sign. People wouldn't have to wait for four hours before being seen to, not that RICE was even on offer.

RICE would have been nice, maybe with an upgrade to this MOVE thing.

<comment><USER16> Sounds like you'd benefit from taking a first aid course. You can see if the Red Cross offer one near you, or your local mountain rescue or lifeguard station if you live near one of those. As well as RICE you can learn some more useful skills: treat injuries and burns, administer CPR, etc.

That said, for suspected broken bones an X-ray really is recommended. Depending on the nature of the fracture, you might need a cast instead of a sling and even the most experienced doctor can't tell you which until they've seen the X-ray results.</comment></comment>


President Obama Comments on Ahmed's Clock - <AUTHOR> https://twitter.com/POTUS/status/644193755814342656 <comment><USER2> Watching the replies to that thread make me despair.

Be happier: never read the comments, avoid mainstream media.

</comment><comment><USER3> I was wondering if he would make a comment about this. Part of me hoped he would fly down to Texas and personally "pardon" Ahmed. That would've been the ultimate slap in the face to the Irving police and the school.

</comment><comment><USER4> I don't care for Obama, but I agree with him on this.

Assuming that all the pertinent facts surrounding Ahmed's case have been made public (and I have no reason at the moment to suspect they haven't), then the kid was wronged and a white-hot spotlight of shame needs to be focused on the school district and "educators" in question.

Bringing him to the White House is a good first step.

<comment><USER5> To the white house. Without the clock of course.

</comment></comment><comment><USER6> Hillary Clinton has come out in support of Ahmed too.

[https://twitter.com/HillaryClinton/status/644167278196600832](https://twitter.com/HillaryClinton/status/644167278196600832)

> Assumptions and fear don't keep us safe—they hold us back. Ahmed, stay > curious and keep building.

</comment><comment><USER7> I love this but reading the responses is extremely sad and a worrying indication about the future of this country.</comment>


Make photomosaics, GIFs, and murals from pictures in Python with ML/OpenCV - <AUTHOR> https://github.com/worldveil/photomosaic <comment><USER2> I'm not an expert in the topic, but my understanding is RGB is a poor color space for computing color difference. This could be why your mosaics end up so washed out. [1] suggests using a CIELAB color space [2].

Edit: Looking at the code more closely it looks like you were using Lab at one point but commented it out[3], so I'm guessing you're already aware of this.

1: [https://stackoverflow.com/a/9019461/185171](https://stackoverflow.com/a/9019461/185171)

2: [https://en.wikipedia.org/wiki/CIELAB_color_space#CIELAB](https://en.wikipedia.org/wiki/CIELAB_color_space#CIELAB)

3: [https://github.com/worldveil/photomosaic/blob/bb720efda11383...](https://github.com/worldveil/photomosaic/blob/bb720efda11383fbb037a05bec41eea942ddb189/emosaic/image.py#L63)

<comment><AUTHOR> It didn't make a ton of difference empirically when I tried it.

But you're correct, generally that's the space you want to be in.

<comment><USER3> It is quite noticeable when you are using a limited selection of tiles or image has desaturated colors.

I've done some similar work[1], but issue with L*ab color is it's terrifically slow to calculate diff, at least in JS.

[1] [https://imgur.com/a/g3EzcSV](https://imgur.com/a/g3EzcSV)

<comment><AUTHOR> Totally. Everything improves with more images since that's your palette for painting, so to speak. The ones I posted were with less than 100 images so you can definitely do better.

L*b was very slow, yes. It's all done offline but I tend to like quicker feedback...

</comment></comment></comment></comment><comment><USER4> Is the example image ([https://github.com/worldveil/photomosaic/blob/master/media/r...](https://github.com/worldveil/photomosaic/blob/master/media/readme/header.jpg)) with or without opacity cheat?

<comment><AUTHOR> Both! You can experiment with —-best-k and —randomness <1.0 and sort of get things in the middle.

Basically what this will do is assign each tile less than 100% of the time randomly and then for each that isn't, you choose among the top best K matches on L2 distance with equal probability. Gives it a little bit of both.

<comment><USER4> I'm talking about `--opacity` - because to me the mosaic images used in the sky can't be that blue originally.

<comment><AUTHOR> Right. The opacity setting is superimposed after the tile assignment. Thus you can have both.

I've found that opacity if 0.7 is often a nice compromise.

</comment></comment></comment></comment><comment><USER5> Way better implementation of the face alignment than what I did for our peru trip. Good going ;-)

</comment><comment><USER6> The gif with facial recognition is actually really really cool. Awesome work

</comment><comment><USER7> Ok, but where is the ML part?

We've been creating these mosaics for decades...

<comment><USER8> It's using the KMeans[1] library from sklearn.cluster. But this isn't really ML, is it? My ML knowledge is limited. Regardless, it's a cool project. OP might want to update the title to remove ML.

[1] [https://github.com/worldveil/photomosaic/blob/master/emosaic...](https://github.com/worldveil/photomosaic/blob/master/emosaic/image.py)

<comment><USER8> "[Kmeans] algorithm has a loose relationship to the k-nearest neighbor classifier, a popular machine learning technique for classification that is often confused with k-means due to the name." Maybe an ML expert could elaborate? I've been curious on my own projects when to actually mention when they use true ML or not.

[https://en.wikipedia.org/wiki/K-means_clustering](https://en.wikipedia.org/wiki/K-means_clustering)

<comment><AUTHOR> Right. See my comment above.

As to why it was in the project: If you treat each pixel as an example vector in 3 dimensions and cluster, you get the "dominant" colors for the image. It's a primitive way to compress images as well. In this case I just was using it to generat fun cards that would use a minimal number of dominant colors. It's still in the code if you'd like to use it but a bit hidden.

</comment></comment></comment></comment><comment><USER9> like others here, i really like the aligned face montage gif and it seems like it would be a great product for people to package up their selfies over a timeline

</comment><comment><USER10> This is fantastic, great project!</comment>


Nate Silver on this year's superbowl teams - <AUTHOR> http://fivethirtyeight.com/features/the-patriots-and-seahawks-are-the-best-this-could-be-the-worst-super-bowl-ever/

<comment><USER2> Are poeple just upvoting because 'Nate Silver'? I didn't find anything truly great in the article, usually I am much more impressed. The tutorial on hexagonal grids [1] a few days back had better data viz than this Nate Silver post.

[1] - [https://news.ycombinator.com/item?id=5809724](https://news.ycombinator.com/item?id=5809724)</comment>


Ask HN: How do I impress my wealthy and powerful new boss? - <AUTHOR> I am new to the workforce, but landed a job where I will be working very closely with a billionaire on the Forbes 400. How do I make the best of this, and stand out? <comment><USER2> I assume something that is rare for a person like that would be to be told the whole, ugly truth about things.

That kind of person would have unlimited talent willing to work with them, but finding someone who gives them accurate information would be invaluable.

That is not to say you become some kind of undercover snitch. Just that accurate information can be immensely valuable to someone like that.

For an example, watch how Marco Polo (Netflix original show) shares information about what is happening in the Mongol Kingdom with the Khan.

Instead of exaggerating, he tries to be specific and accurate. And the Khan makes him an adviser in the court despite his original standing, so he can continue to get his reports.

</comment><comment><USER3> Curious what "making the best" of it would be.

<comment><AUTHOR> Just taking advantage of the opportunity to meet someone of this stature to advance my career and get ahead.

<comment><USER3> In what direction should the career advance?

Ahead of what?

<comment><AUTHOR> I would like to be promoted up to leadership positions within the company.</comment></comment></comment></comment>


Richard's guide to software development - <AUTHOR> http://www.sandraandwoo.com/2012/11/19/0430-software-engineering-now-with-cats/

<comment><USER2> This is quite a description.

But to be honest, I still have not found the best way to keep code flexible so that it never turns into the mutant of what the Statement of Work intended it to be.

Most of the time the clients don't have any idea of what they truly want, but as seasoned software developers it should be our job to keep the bad ideas clients propose out of the requirements.</comment>


The Industries Plagued by the Most Uncertainty - <AUTHOR> http://blogs.hbr.org/2014/09/the-industries-plagued-by-the-most-uncertainty/?utm_source=Socialflow&utm_medium=Tweet&utm_campaign=Socialflow

<comment><USER2> Sad that they fail to mention the lower left corner of their chart is anchored by 'prostitution' and the upper right corner by 'flying cars' :-)

Most of the venture folks I've talked with over the years talk about "stacking risk" rather than uncertainty but its the same thing. Trying to figure out if you can eliminate the risk of something before the big investment pays huge dividends. A lot of the 'create a signup page' kinds of ideas are built around this.

<comment><USER3> Flying cars are bottom right: everyone wants one, no one knows how to build it.

</comment></comment><comment><USER4> I am interested to know what the correlation is between uncertainty and returns. Are companies that succeed in highly uncertain spaces more profitable than those which succeed in well known markets? If you include companies that fail in uncertain spaces, is the average return still greater than those in more certain markets?

I would think yes, otherwise we would all be sticking with mining precious metals.

<comment><USER5> Do you know about Modern Portfolio Theory and Capital Asset Pricing Model?

Granted, they don't refer to "uncertainty" exactly, but rather about quantifiable risk in the form of volatility. Also, the key word is "returns" (not exactly profits, but roughly the ratio of total profits over the initial investment). Basically, while investors have different levels of risk tolerance, a rational investor requires higher expected returns for higher expected risks.

While a lot of researchers have been questioning the validity of MPT and CAPM (because these e.g. rely on a lot of questionable assumptions), empirically the answer to your question seems to be "yes". Small cap stocks historically have higher returns than large cap stocks, and tech stocks have higher returns than utilities.

</comment></comment><comment><USER6> _"... fortunately, experiments with customers trump opinions at Google. Following the advice of then CEO Eric Schmidt to "get 100 happy users inside Google," Bucheit prototyped solutions that eventually proved demand and won the day. ..."_

source of the 'a handful of users who really love you' idea pg sprinkles in his essays?</comment>


Facebook confirms 419m phone numbers exposed in latest privacy lapse - <AUTHOR> https://www.theguardian.com/technology/2019/sep/04/facebook-users-phone-numbers-privacy-lapse <comment> java-man "lapse"</comment>


Ask HN: Which is your favorite online code teaching company? - <AUTHOR>

In the last months there have been at least three[1] new start ups launching their products.<p>What are your favorites? What do you think about learning to code online?<p>[1] http://www.codeschool.com/ [2] http://www.codecademy.com/ [3] http://teamtreehouse.com/ <comment><AUTHOR> clickable links

<http://www.codeschool.com/>

<http://www.codecademy.com/>

<http://teamtreehouse.com/></comment>


Facebook scans system libs from Android app and uploads them - <AUTHOR> https://mobile.twitter.com/wongmjane/status/1167463054709334017 <comment><USER2> Extensive discussion, currently on front page: [https://news.ycombinator.com/item?id=20839689](https://news.ycombinator.com/item?id=20839689)</comment>


Barnes & Noble puts itself up for sale - <AUTHOR> http://www.marketwatch.com/story/barnes-noble-to-evaluate-strategic-alternatives-2010-08-03

<comment><USER2> To me, it is pretty fascinating to see how Barnes & Noble has fared versus Borders (now only 1/10 of BN's market cap).

Borders made a number of miscalculations that have really cost them dearly. They passed up on running their own online store -- outsourcing it to Amazon, but worse they bet big on selling media merchandise at their stores (DVDs, CDs, Games). I am sure originally the media decision worked, but as CDs died out (and DVD sales are dropping off), they were screwed.

Barnes & Noble on the other hand went with their own online store and bet bigger on having their own publishing arm (plus a college textbooks biz). Obviously in the longer run this has worked out but they are still facing extinction. I imagine that bookstores will still continue to exist going forward, but they will be far fewer in numbers akin to record stores. My guess is that Ron Burkle was going to make a play for the whole company so Riggio had to quickly react with his own potential offer (note the language he used in the press release).

Some people will try to play up the store real estate value aspect of these companies but I think that is not a good angle. Borders / B&N have -huge- stores on a sqft basis. That presents a big problem for potential businesses looking to purchase a location. I think the stores are most appropriate for maybe furniture stores but those are still recovering from tough times during the crisis. I don't expect them to start investing any time soon.

<comment><USER3> What's worse is that their stores are in more well-to-do (i.e., well, or at least better, read) suburbs and exurbs, so you can't do a "package sale" to any company who's doing well in this environment (Dollar Tree or Big Lots, for example) to take up space there, as the property owner and neighboring stores in the strip would balk at the idea of their anchor store going downmarket. So, they'll have to pawn each property off piecemeal, which is much more laborious.

</comment></comment><comment><USER4> > Leonard Riggio, the company's founder and largest stockholder, has informed > the Board that, in light of its decision to explore strategic alternatives, > he intends to consider the possibility of participating in an investor group > to acquire the company

For those curious how Riggio, born in 1941, could be a founder of a company formed in 1873, it appears that Riggio's bookstore company bought Barnes and Noble in 1971, and adopted its name.

</comment><comment><USER5> Wow, I figured it would take someone huge to buy them, but it turns out their market cap is only $755M. Amazon's is $54B

<comment><USER6> I wonder if Amazon would have any use for them?

<comment><USER7> Amazon has typically refused to acquire any company that would expose it to nationwide (or even Californian) sales tax.

<comment><USER8> Agreed, but to my confusion Amazon has been very aggressive in competing with B&N. Every price drop of the Kindle in the last 9 months has seemingly been in response to a price drop of the Nook (B&N's e-reader). Given that B&N is like a gnat on Amazon's elephant, I haven't been able to figure out what is going on.

So it wouldn't surprise me if Amazon somehow got involved here, perhaps in a way that would avoid the sales tax issue.

</comment></comment></comment></comment><comment><USER9> It's as if B&N suddenly realized, "We're mostly selling just bits and bytes, but at a heavy markup and with tons of warm bodies and brick and mortar. The Internet is going to eat our lunch. Holy shit!"

Except the rest of us realized this years ago.

That said, there are still things about a physical bookstore that the Internet doesn't "do better/cheaper". One is the pleasure of perusing the bookshelves. Second is the social factor of seeing other folks there and striking up conversations. Third is the Starbucks-like factor: every B&N I've been to seems to have a mini-coffee shop inside of it, complete with tables and snacks and power outlets. Very smart move, because we still can't download tables or coffee over the Internet, let alone for free.

<comment><USER10> It's true, I can flirt in person at B&N, and Amazon.com provides no such functionality! I go there for the experience of getting out of my house and walking around in the presence of actual people (I work from home). The coffee shop isn't really as inviting as Starbucks or Caribou, though, in my locality, though it is nice enough. They just stopped charging for wifi a few months ago.

<comment><USER9> Same here, and I also often work from home or coffee shops.

I live in suburban Colorado and there are 3 places nearby I can go to almost assuredly see good looking women on a daily basis, even weekdays, even the middle of the day: Target, B&N and Starbucks. (Target is the most reliable, for whatever reason.) Walmart tends to have the worst looking women, so even if I could get groceries there a few cents cheaper per item, it's just not worth the impact on my overall quality of life.

One advantage to B&N over Starbucks is that at Starbucks I feel obligated to buy something as micro-rent for the table space, even if I'm not hungry/thirty. At B&N I have the excuse of browsing for books and magazines, so every trip can be free, guilt-free. Starbucks has awesome bathrooms though, and lower chance of screamers, er, I mean, kids.

</comment></comment></comment><comment><USER11> 755.71M market cap - 510.40M debt - would be an interesting way to instantly get a lot of retail locations (700+ stores and 600+ campus stores).

I guess I should expect the Apple and Microsoft sites to contemplate each companies purchase. Probably some HP action in there too (so they can be more like Apple).

<comment><USER12> You seem to be assuming they own all of their retail stores. Is this true?

<comment><USER2> On their balance sheet, under assets, they record about $812M worth of value for their net property, plant, and equipment. With 720 store locations that comes out to about $1M in value per store. That's probably understated by a lot because of the excess depreciation charge they take.

<comment><USER12> I would humbly submit that PP&E likely is dominated by warehousing facilities and books at a place like B&N. It may include some real estate, but I wouldn't bet on it representing the value of 720 store locations, even with aggressive depreciation schedules.

I would bet their PP&E likely has a large emphasis on esoteric distribution equipment, as well as some stores. I am just wildly speculating though: the business of selling books is too crappy (low cashflow yeilds) to get me interested enough to crack open a 10-k.

</comment></comment></comment></comment><comment><USER13> One of the main reasons I'd go to a brick-and-mortar store is to be able to pick up a book that day rather than get it shipped.

Borders has nice kiosks you can use to look up where a book is, but at Barnes and Noble you have to talk to someone at the information desk and watch over their shoulder to make sure they're spelling the name of the book right, etc. Inconvenient.

Also, usually at brick-and-mortar stores, if they don't have something they'll say "but we can order it for you", which has never made sense to me. If I wanted to order it, I'd do so more cheaply online.

Bookstores also need to focus on the browsing experience and the immediate gratification aspect if they want to compete with Amazon.

<comment><USER14> > Also, usually at brick-and-mortar stores, if they don't have something > they'll say "but we can order it for you", which has never made sense to me. > If I wanted to order it, I'd do so more cheaply online.

I did this when I was younger. The point was, I _did not have a credit card_. By ordering in the store, I could pay cash or use gift certificates.

(Ask a parent? Buy a prepaid debit card? Oh, you funny funny people.)

</comment></comment><comment><USER15> The edited title is very misleading, not only because it's a publicly traded company (and thus always for sale) but also because all they're really saying is "yeah we know we're plummeting, but don't sell your shares."

</comment><comment><USER16> In this town in the UK, all the 2nd-hand bookshops are shutting down one by one due to Amazon's 'used book' sales. It's hard to sell a book for £3.50 when you can buy it from Amazon for 1 penny plus £2.75 postage.</comment>


Ask HN: Should we apply to YC, if we are a competitor of a YC Alum?  - <AUTHOR>

Our idea is to disrupt a space, where the leader is a YC alum. Should we still apply to YC? Has anything similar happened before? <comment><USER2> Yes a number of times. Rapportive, Etacts and Xobni were all YC and competitors. YC has also funded a number of competing developer recruitment startups.

</comment><comment><USER3> YC funded a startup (Double Robotics) that competed with a YC partner's co (Anybots). Just apply.</comment>


Java 14 Features with Examples - <AUTHOR> https://solidstudio.io/blog/java-14-new-features.html <comment><USER2> Everytime I read a article about a java update it feels like its getting bigger and bigger in mundane ways.</comment>