News for hackers. Stuff that matters.
Re:Code boilerplate: Is it always bad? by tigershark on Saturday June 10, 2017 @01:23AM (#14526269)
It's always bad. The second line makes you understand with a glance what it does because it is declarative and explains what is doing instead of how. The go code is awful (personal opinion, although I hope it is widely accepted), much more verbose and it opens you up to a whole series of errors that are just impossible in the python version. Boilerplate code by definition is just duplication and it is always bad because opens you up to bugs in a specific part of the boilerplate while you can't have any bug at all in any boilerplate if you don't have any of it. Honestly I can't really see how anyone can prefer code that is more verbose and bug-prone to code that is more concise, clear and with less bugs.
Re:Code boilerplate: Is it always bad? by bostik on Saturday June 10, 2017 @02:57AM (#14526430)
> It's always bad.

Generalisation is always[tm] a bad idea. Taken to illogical extremes, at the other end of the spectrum we have the monstrocities of old Perl. After all, with Perl it was often said that you could fit most solutions to a oneliner.

In fact, I would go as far as to claim that using Python for n-tuple iterators inside branched comprehensions are getting awfully close to the worst aspects of what Perl scripts were commonly criticised for.

Re:Code boilerplate: Is it always bad? by inopinatus on Saturday June 10, 2017 @04:20AM (#14526592)
Perl golf is certainly an extreme example, but more commonplace is the convention-over-configuration in Ruby on Rails. Mostly this is useful in avoiding boilerplate and increasing "programmer happiness", but (in my opinion) the C-over-C is slightly overcooked. I believe a small amount of boilerplate declaration goes a long way towards assisting with debugging and production correctness. Two examples from Rails to illustrate:

1. RESTful routes leading to implied controller actions that render a view without any controller declaration at all. I've seen more than one codebase with routes that could be invoked by users despite being never linked in production and having no test coverage. It's basically undocumented code due to a total absence of declaration, and a case of needing to know the implied framework behaviour to understand a program.

2. I have an issue with ActiveRecord's schema behaviour. By avoiding attribute declaration in models and just defining ORM methods by asking the database for column names, it only takes one poorly handled migration or a DBA oops to lead to some very strange production behaviour. Situation is only partially offset via the (new) attributes API and/or a schema cache dump during CI but one can never fully do away with the hazard. Philosophically speaking, sometimes Rails thinks it is dictating the database schema, sometimes Rails accepts what the database tells it, and out-of-the-box rails has no model boilerplate that bridges the gap to guarantee a specific DB schema.

In both cases I add my own safeguards for production environments, but that's a matter of programmer discipline rather than mandatory declaration.

Re:Code boilerplate: Is it always bad? by tigershark on Saturday June 10, 2017 @03:05PM (#14528682)
Convention most of the time doesn't reduce boilerplate at all while it increases exponentially the headaches for anyone reading the code. A typical example is using the awful Prism way to display a view in a WPF application. For some reason completely alien to me the people at Microsoft practices, or whatever it was called at the time, explicitly suggested to use the IOC container directly (or with a kind of service locator) to create a view that automatically will try to load a view model with the same name if it existed, without throwing any error if it wasn't found. This is the worst possible suggestion ever. It is much easier and much more readable to just get your view model as a parameter in your main viewmodel, the IoC container will create it for you, you assign it to a public property and the view defined in a template is automatically shown in a content presenter. This is extremely easy, much easier to do than to explain, there is no whatsoever connection to the container, if the viewmodel is not found you receive a runtime error, the view model has no relation at all with the view, it can be called whatever you like and the view has an explicit connection with the viewmodel. So in this case the removal of convention based loading not only makes everything explicit, but also removes all the boilerplate needed to get a view from the container. I don't particularly like ROR exactly for the same reason for which I don't like this convention driven way just explained. And as you can see removing conventions and using different techniques can actually reduce the boilerplate if done properly.
Re:Code boilerplate: Is it always bad? by crdoconnor on Saturday June 10, 2017 @10:43AM (#14527498)
Perl's terseness is about ripping meaning away from the code's symbolic representation to save a few characters. That's a related issue to boilerplate, but it's not the same thing at all.

Boilerplate is usually maximized in projects which try to give users a huge amount of flexibility that they don't need or want.

This is partly why minimizing boilerplate is so hard - one thing that continually surprises me is what users want flexibility over and what they don't. I've lost count of the number of times I've given users flexibility to do something they don't give a shit about and not given them the flexibility to do something they really wanted.

Re:Code boilerplate: Is it always bad? by tormeh on Saturday June 10, 2017 @11:18AM (#14527642)
>ripping meaning away from the code's symbolic representation to save a few characters

That's a great way to put it. I'll steal this one.

Re:Code boilerplate: Is it always bad? by grasleya on Saturday June 10, 2017 @03:32AM (#14526499)
You can code golf in any language and it will probably result in less comprehensible code. If there's one thing I think I agree with the original author on, it's that terseness is not an end unto itself. But I think the overall point that terseness can sometimes be bad so therefore we shouldn't work at a higher level of abstraction is really at odds with everything we've learned about programming in the last century.
Re:Code boilerplate: Is it always bad? by btschaegg on Saturday June 10, 2017 @12:18PM (#14527860)
On a related note: The single thing I absolutely love in Visual Studio is how it handles C#'s #region statements. While they traditionally seem to be used mostly to group class members (which doesn't really benefit the reader much, IMHO), one can use them to hide the fact that C# still has the tendency to be a bit verbous by reducing complicated methods to pseudo code.

I tend to use this pattern quite a lot:

  #region Find the first Foo with Bar
    var foo =
      foos.Where(f => f.Bar)
          .Distinct()
          .OrderBy(f => f.Baz)
          .FirstOrDefault();
  #endregion

I still miss a similar feature in Emacs and Vim. There are similar folding markers one could use (say {{{ }}}), but they don't seem to work together with syntax-based folding.
Re:Code boilerplate: Is it always bad? by taeric on Saturday June 10, 2017 @03:49PM (#14528875)
This would be easy to code up in Emacs. If interested, I'll try and get an implementation out. (Currently on my phone...)
Re:Code boilerplate: Is it always bad? by btschaegg on Saturday June 10, 2017 @06:44PM (#14529625)
If you know how to do this, I would indeed be interested.

I already pondered if it wouldn't be possible to merge multiple "folding strategies" if one would build some kind of interface with which multiple routines could basically communicate folds in a buffer.

Say you have one routine scanning the syntax of the according language, one looking for folding markers and one for manual (Vim-style) folds. I guess it technically should be trivial to use all of them provided they are nested and don't intersect in weird ways (the latter could be resolved with some simple priorities).

Re:Code boilerplate: Is it always bad? by taeric on Monday June 12, 2017 @12:04AM (#14535154)
I wound up not getting the computer out. Looking at it right now to see if it would be as easy as I was thinking.

Simply put, knowing how advanced org-mode can get with folds, this is likely trivial to do. (If you haven't played with it, I'd recommend taking a look. I don't have perfect examples, but http://taeric.github.io/DancingLinks.org is an example. Open that in emacs with org-mode and you will see that all of the source blocks can be folded together. For me, the source blocks are correctly colored, as well.)

Quickly searching, I found https://www.emacswiki.org/emacs/FoldingMode, which seems to be a large start to this. There were also some other ideas that seem to get close.

The basic idea I had was to just make a few functions that would:

    - Fold from current location to next #endregion
    - List all region/endregion's in the current buffer
    - Fold all region/endregion's in the current buffer
The second of those felt trivial, since it is basically M-x occur #region\|#endregion. On top of that, I just need to learn how to actually make overlays and then the rest feels like it would fall into place easily enough.

Edit: It occurs to me that I didn't show how to actually hide text, which I think is your question. Fastest way I can see is this (run this in your scratch buffer to see it in action):

    (let ((o (make-overlay 5 120)))
        (overlay-put o 'display "---hidden---"))
To easily delete this particular overlay, if you make it, use:

    (let ((o (overlays-at 5)))
        (mapcar 'delete-overlay o))
So, the basic task that will need to be completed is finding the point position for the start and end of make-overlay.
Re:Code boilerplate: Is it always bad? by BJanecke on Saturday June 10, 2017 @04:11PM (#14528974)
I think that's really cool, although

// Find the first foo with bar foos.map(f => f.bar).uniq().orderBy(f => f.baz)[0]

does the same basic thing, the ability to collapse and display intent is incredibly rad for lack of a better word

Re:Code boilerplate: Is it always bad? by userbinator on Saturday June 10, 2017 @10:51AM (#14527534)
Honestly I can't really see how anyone can prefer code that is more verbose and bug-prone to code that is more concise, clear and with less bugs.

I agree with you, but seeing the number of proponents of Enterprise Java there are, it's clear that there are a significant number of programmers who prefer verbosity and extra abstractions --- although IMHO not necessarily because it's actually better.

In fact a trend I'm seeing with a lot of programming languages is more verbosity and unnecessary abstraction, leading me to wonder whether programmers actually know the languages they're using or are barely scraping by with the very minimal basics (and in the case of some languages, a bit of OOP cargo-cult dogmatism.)

Although I'm not really familiar with Python, and the order of the clauses its conditional expression syntax is unusual and a little surprising, I think that second line probably took longer to write than it did for me to read.

Re:Code boilerplate: Is it always bad? by coldtea on Saturday June 10, 2017 @11:36AM (#14527702)
>I agree with you, but seeing the number of proponents of Enterprise Java there are, it's clear that there are a significant number of programmers who prefer verbosity and extra abstractions --- although IMHO not necessarily because it's actually better.

Even Enterprise Java wasn't verbose for the sake of it (I say "wasn't" because modern enterprise Java can be more like modern functional style than Go).

It was more verbose because it added tons of options and flexibility while keeping with the OO style, so everything was pluggable and configurable and factorable. But that's something else than Go style verbosity.

Re:Code boilerplate: Is it always bad? by mushishi on Saturday June 10, 2017 @12:56PM (#14528045)
I don't know people who like verbosity per se. But I can symphatize with people who think that if removal of verbosity introduces other burdens that possibly affect the understandability or refactorability of the code, it is not clear-cut if it's worth it.

Say, with Scala implicit parameters, you get to remove code from call-site. Does it make the code better? Depends on the case, in my opinion. So I don't get the point to say some people categorically want verbosity. They may prefer explicitness and unsurprising code which may require verbosity. Or perhaps the removal of verbosity requires code that allocates more memory -- in that regard Kotlin seems to be a good citizen. It has ways to make code concise without making the byte code entirely different.

Re:Code boilerplate: Is it always bad? by xapata on Saturday June 10, 2017 @11:46AM (#14527740)
> probably took longer to write than to read

That's the point. Reading is far more important.

Re:Code boilerplate: Is it always bad? by watwut on Saturday June 10, 2017 @04:12PM (#14528981)
> unnecessary abstraction, leading me to wonder whether programmers actually know the languages they're using or are barely scraping by with the very minimal basics

It is more that they have good abstract thinking, so abstraction is not an issue for them. Abstractions are issue only for some people.

> I think that second line probably took longer to write than it did for me to read.

If it takes more time to read then write, then it is not done yet needs to be refactored. Good code is as obvious to read as possible.

Re:Code boilerplate: Is it always bad? by banku_brougham on Saturday June 10, 2017 @06:47AM (#14526891)
Your comments clearly ring true, for the example code snippets shown. But i think you have missed the point of the article, which is the benefit of the Go version when iteratively changing the structure.

The author could have brought the examples forward, instead of just providing links to urllib3 and the Set type.

Re:Code boilerplate: Is it always bad? by coldtea on Saturday June 10, 2017 @11:37AM (#14527712)
>Your comments clearly ring true, for the example code snippets shown. But i think you have missed the point of the article, which is the benefit of the Go version when iteratively changing the structure.

You can iteratively change a smaller, terser code, must faster. There's a reason prototypes are often written in languages like Python.

Re:Code boilerplate: Is it always bad? by mushishi on Saturday June 10, 2017 @12:49PM (#14528016)
Logical duplication tends to be bad. But code duplication -- that is not logical duplication (business rules, etc) -- might not be.
Re:Code boilerplate: Is it always bad? by taneq on Saturday June 10, 2017 @03:32AM (#14526498)
I feel that this sort of 'cleverness' in packing a large amount of logic onto a small amount of code is treated quite differently between Python and C-type languages.

In C++, would you write the same structure using a single line for-loop and ternary operators?

Re:Code boilerplate: Is it always bad? by bartread on Saturday June 10, 2017 @04:11AM (#14526569)
I tend to avoid both 'cleverness' and writing ultra-terse code for a couple of reasons.

The first is that somebody else will eventually have to work with it, decipher what the heck I was trying to achieve, and generally get tripped up and slowed down by it.

The second is that eventually I may have to work with it again, and sit there scratching my head and wondering what I'd been smoking when I wrote instead of focussing on the changes I need to make.

The point is to code for maximum clarity to humans whilst still achieving the desired functional and non-functional outcomes on the machine. You will use varying terseness as part of doing this because terseness isn't the point: it's just one of many means to your end.

Re:Code boilerplate: Is it always bad? by tigershark on Saturday June 10, 2017 @05:08PM (#14529202)
I completely agree. Writing a loop with several useless variables in scope, increment operators, exploding computational complexity is for sure more difficult for a human to understand compared to declaring what your code ought to do in a concise and well understood way. The maximum clarity for humans is always the goal and bug-prone, verbose code is for sure not the way to go.
Re:Code boilerplate: Is it always bad? by alexeiz on Sunday June 11, 2017 @10:00PM (#14534825)
Yes, I'd write that code in C++ in a single like if I could. At the moment it's not quite possible, but in C++17 and with ranges library the expressiveness of C++ will get quite close to the expressiveness of Python.

It's not "cleverness", but rather the ability to express the intent as succinctly and clearly as possible. Higher level languages allow you to do that, lower level languages don't. Obviously, Go is not a very high level language because it forces you to write explicit loops instead of using comprehensions or functional algorithms. Loop is a primitive concept. All other factors being equal (i.e. performance) you should always prefer comprehensions or algorithms over explicit loops.

Re:Code boilerplate: Is it always bad? by userbinator on Saturday June 10, 2017 @11:03AM (#14527584)
If I were asked to do a similar thing in C it would probably look something like this --- I've renamed some of the variables to match a hypothetical situation and show that naming can have a significant effect on understanding what the code could be doing:

    for(i=0,total=0;i<resultlen;i++) {
        int price = results[i].price;
        total += results[i].selected && (price&1) ? price : 0;
    }
In C++, someone would probably do the same using the standard library functional programming templates etc., approaching the conciseness of the Python (and coincidentally, likely generating even more code than the simple loop above.)
Re:Code boilerplate: Is it always bad? by themodelplumber on Saturday June 10, 2017 @01:58AM (#14526332)
This argument can be abstracted to subjective thinking vs. objective. In subjective thinking, every situation is unique and even the best objectively-validated boilerplate can increase risk by lowering flexibility, control, and responsibility for & deep knowledge of the situation.

Objective thinkers tend to go looking for existing, established boilerplate or frameworks because of the immediate leverage that is provided. They may think of too much subjective thought or originality as ridiculous NIH or wheel-reinvention. Their struggle is in the weighty task of grokking and maintaining third-party resources.

Scott Adams has kind of unwittingly uncovered this dichotomy with his own inventive, subjective thinking. He considers more objective thinkers as "word thinkers" or some name like that, because they go looking up the established names of things rather than understanding the things themselves.

Also Chris Langan similarly trashed Jeopardy contestants in a news interview, because they aren't subjective thinkers like he is; their minds are just filled with objective facts about various things. Well, true for him; his bias dictated the way he developed his own unique universal model--he prefers and has a gift for subjective thought.

Really though, we need both kinds of approaches.

Re:Code boilerplate: Is it always bad? by unabst on Saturday June 10, 2017 @03:13AM (#14526470)
Except, subjective thinking is what leads to objective facts. If not for thinkers, there would be nothing to share.

And words are amazing. All these complex and nuanced concepts we're talking about can be expressed and shared almost instantly because of the words we share. If we had to invent words as we communicated, or worse yet, had no words, there would be no discourse because the sun would go down before we got anywhere.

It is true that words are set in their definitions and intuitions, much in the way that scientific models are and common sense is. These can be considered objective facts.

But challenging these facts and inventing new words is just an important part of the process. Some have more success with it than others, but not looking up what is already known is just wasting your time. Same with not using words that already mean what you mean.

Subjective thought leads to objective facts with fact checking. Objective facts are then better shared, and better learned, because learning is far easier than arriving at them yourself. Learning just takes communication, which is proportional to the complexity of the information. Inventing or discovering new facts requires the entire lengthy and laborious process which is will inevitably include experiments and fact checking and evidence validation if we are to be scientific. If the problem can be solved with pure thought, chances are it was a philosophical one, although philosophy too highly relies on existing language.

Re:Code boilerplate: Is it always bad? by icebraining on Saturday June 10, 2017 @02:58AM (#14526434)
While I don't disagree with the distinction, I don't agree that it applies here.

The thing with code is that you can take those existing patterns and make them a first-class concept in your program. You're still in "objectively thinking" - still reusing existing code - just in a more compact and safe way.