We are learning higher-order functions in our class and our professor mentioned that they can be useful for web programming. I'm unsure as to what cases in which that would be true and was wondering if anyone had any experiences with higher-order functions in some common web programming tasks, and in what situations they would be useful.
I read through our book, but web programming wasn't mentioned, I suppose it was just something the professor mentioned off topic, but it sparked my interest a bit.
Thanks!
I'm not exactly sure which cases your professor might have been talking about, but higher order functions are used heavily in JavaScript. A simple example of a higher order function (a function taking a function as a parameter and/or returning a function as a result) would be the jQuery ready() function:
$(document).ready(function(){
alert('The DOM is ready for manipulation!');
});
A simple example, yes...but it demonstrates how useful higher order functions can be.
Play, (Scala) Lift (Scala) , SeaSide (Smalltalk) and Webmachine (Erlang)
are three web frameworks the rely heavily on functional ideoms such as higher-order-functions.
Clojure makes extensive use of higher order functions for web development in the excellent Ring framework. See this excellent video which explains some of the concepts.
The basic idea is:
A web application is really just a function that maps a request to a response
You can therefore compose the entire web application using higher order functions
Related
On RxJS - Goals I read that their goal is better debuggability:
Goals
Provide more debuggable call stacks than preceding versions of RxJS
I have just started to use redux-observable which is quite easier for me to understand comparing it to redux-saga as I am already used to the reactive style with lodash and ramda (ok, fp style maybe ;). I was surprised that it's not possible to debug it yet. Is it true? If so, then I gotta switch to redux-sagas maybe or stick with redux-thunk.
Edit based on Jay Phelps's answer
By debugging I meant: "How to set a breakpoint on e.g. observable.map(...) in a browser?" With lodash I can set a breakpoint in the browser and it stops right there on the _.map(...). How to do it with redux-observable (or rxjs)? I don't want to depend on drawing of marble diagrams and console.log().
It certainly is possible to debug RxJS code. I think it's probably safe to say hardly anyone would use it if that wasn't the case--Angular2 is heavily built on it too.
The most common ways people use are the same ways they debug other JavaScript, breakpoints (e.g. debugger) and console.log()'s
There are more advanced techniques some users use like drawing dependency graphs or marble diagrams. André Staltz wrote about this recently, so that might be a helpful resource.
Ultimately, any kind of async programming is going to be harder to debug. This is not unique to redux-observable/RxJS; a quick search will reveal plenty of debugging concerns for redux-saga too.
It turns out that redux-thunk is the best solution for a vast majority of applications built because a majority of them do not have complex side effect concerns that justify something like redux-observable or redux-saga. Though if you are already proficient in RxJS, there's nothing wrong with using redux-observable.
redux-saga as a project has existed longer than redux-observable so that's certainly one major selling point. You'll find more documentation, examples, and likely are have a better community to get support from.
The counter being that the operators and APIs you learn in redux-saga aren't nearly as transferable as learning RxJS, which is used all over the place. redux-observable is super super super simple internally, it's really just giving you a natural way for you to use RxJS. So if you know RxJS (or want to), it's an extremely natural fit.
My advice at the moment for most people is that if you have to ask which one you should use, you probably should choose redux-saga.
(disclaimer: I am one of the maintainers of redux-observable and RxJS v5)
import Rx, { Observable } from 'rxjs'
const arrStream$ = Observable.of(1,2,3)
.do(x=>console.log('Before',x)) // 1, 2, 3
.map(x=>x*2)
.do(x=>console.log('After',x)) // 2, 4, 6
.subscribe(value=>doThingsWith(value))
// real console output
// Before 1
// After 2
// doThingsWith(2)
// Before 2
// After 4
// doThingsWith(4)
// Before 3
// After 6
// doThingsWith(6)
.do(debugValue=> console.log(debugValue))
It's possible to write parallel code in Elm? Elm is pure functional, so no locking is needed. Of course, I can use Javascript FFI, spawn workers here and do it on my own. But, I want more user friendly "way" of doing this.
Short answer
No, not currently. But the next release (0.15) release will have new ways to handle effects inside Elm so you will need to use ports + JavaScript code less. So there may well be a way to spawn workers inside Elm in the next version.
More background
If you're feeling adventurous, try reading the published paper on Elm (or the longer original thesis), which shows that the original flavour of FRP that Elm uses is well suited for fine-grained concurrency. There is also an async construct which can potentially make part of the program run separately in a more coarse-grained manner. That might be support with OS-level threads (like JS Webworkers) and parallelism.
There have been earlier experiments with Webworkers. There is certainly an interest in concurrency within the community, but JavaScript doesn't offer (m)any great options for concurrency.
For reading tips on the paper, here's post of mine from the elm-discuss mailing list:
If you want to know more about signals and opt-in async, I suggest you try Evan's PLDI paper on Elm. Read from the introduction (1) up to building GUIs (4). You can skip the type system (3.2) and functional evaluation (3.3.1), that may save you some time. Most in and after building GUIs (4) is probably stuff you know already. Figure 8 is probably the best overview of what the async keyword does (note that the async keyword is not implemented in the current Elm compiler).
thanks in advance.
Somewhere else I asked the same question but about scalability. Please let's not confuse both terms. I'd really like to understand what particular parameters I should look at when assessing if a framework performs acceptably.
I mean parameters such not over-querying the database for simple tasks just because the ORM above is not very well written, etc... Please let's try to answer this question without diving into a particular technology.
Lastly, let's assume that the underlying hardware is any that allow you to perform well, that is to say, there is no hardware bottleneck. I don't want a software that uses a cannon to kill mosquitos :).
Thanks again.
I mean parameters such not over-querying the database for simple tasks
just because the ORM above is not very well written, etc... Please
let's try to answer this question without diving into a particular
technology.
Succesfull ORM technologies are not under-performant. But if your web application is extremely simple (you don't define the scope of your question) then introducing a robust ORM that would be an overkill. Do a DAO pattern yourself instead.
Finally you can always do test measurements yourself to evaluate if the performance suits you
From their website http://www.playframework.org/documentation/1.0/faq
"
The biggest CPU consumer in the Play stack at this time is the template engine based on Groovy. But as Play applications are easily scalable, it is not really a problem if you need to serve a very high traffic: you can balance the load between several servers. And we hope for a performance gain at this level with the new JDK7 and its better support of dynamic languages.
"
So there are no better choices? What about JSP?
JSP is not feasible as every JSP compiles to a Servlet and the servlet API provides things like the server side session which are not compatible with the RESTful paradigm. We don't want to go back to the dark ages of badly scalable server side sessions, back buttoning problems in the browser, reposts etc.
Japid templates are interesting, but they are not backed by a great community and perhaps didn't even exist at the time play was created (I don't know for sure though). I tried Japid as a replacement for the Groovy templates in my own application and found out in a JMeter test that the benefit would be only marginal, 10% to max. 25% improvement.
I guess in the end it all depends on your scalability requirements and the structure of your pages. I picked the 90% use case of my application and did the test. To me, the little improvement did not justify for the additional costs of the extra dependency (I like to keep dependencies to a minimum for maintainability).
Groovy templates are not bad or slow in general. Use typed variables wherever possible (instead of "def"), even in closures! Keep values of accessed properties in local variables. Do reasonable results paging. Then keep your fingers crossed that GSP might be able to run on groovy++ in the future and you're done ;)
To me, the question would not be why they used groovy in the views. That is, because I rather do miss it so much in the controller layer. Groovy would make coding the controller behaviour a lot easier IMHO.
First off, JSP was not a valid option for Play since it chose not to go down the Java EE route (which JSP is part of). Instead, Play chose to use Groovy as an intuitive, simple but powerful templating engine.
However, one of Play's greatest features is that it is a pluggable system, meaning that many parts of the core system can simply be replaced. This includes the template engine, and there are a couple that are already available.
The most popular is Japid. It claims to be 2-20x faster than the standard templating engine, and has been around for a while. For more info, see here http://www.playframework.org/modules/japid.
A second option is Cambridge, although this has only been out for a little while, but is reasonably active in the message boards (see https://groups.google.com/forum/?hl=en#!searchin/play-framework/cambridge/play-framework/IxSei-9BGq8/X-3pF5tWAKAJ).
I tend to stick to Groovy, as I like the way it works, and have not found it to be too bad in terms of performance, but every application is individual, so your own performance tests should lead you down your own particular path.
Yes there is Japid. Which is much, much faster.
http://www.playframework.org/modules/japid
I totally agree with the choice of ease over speed the Play Framework designers made here. My guess is that if the templating starts getting in the way in terms of performance, you can (and should!) measure the slow bits, and refactor them into fast tags where possible. With that, you're likely to save 80% of CPU by moving 20% into fast tags, leaving you with flexibility and adequate speed.
Having said that, I'm looking forward to an experiment I'm planning to see how well the new Scala templates (loosely "borrowed" from Razor.NET - awesome clean syntax) work with Java controllers/models. The Scala backend isn't there yet in terms of comparative ease, but the templating language certainly rocks.
I may be late to the party in 2016. Play 2 is out, and the JDK (not to mention the hardware) drastically improved. I am not using Play or Spring Boot, since my platform doesn't need them - just pure runtime text/HTML generation from templates.
First, when talking about Groovy templates, there is more than one. I use the original Groovy SimpleTemplateEngine for anything from emails to rich Web pages, whether most people nowadays favor the "advanced" MarkupTemplateEngine with its non-HTML builder syntax. I did not go that route because of the IDE (e.g. UntelliJ) support for JSPish HTML files with JavaScript - catching unclosed tags, braces, etc. Besides, how would you include JavaScript into the curly brace based "builder" style template?
Whichever you chose, both SimpleTemplateEngine and MarkupTemplateEngine statically compile their templates, even though the Groovy doc only mentions it for the latter. Why wouldn't it generates a class for the former? I didn't compare them against each other, but I'd expect SimpleTemplateEngine to be faster, since it is... well, simpler - doesn't translate any syntax into String concatenations with ifs and loops in between.
And it is indeed very fast. I was concerned about invoking it in a loop. Doesn't make any difference. There is no overhead, as the template is compiled once.
I use multiple small templates responsible for generating individual form control markup (HTML + JS) to generate a composite form, included in a higher-level container, included in another container, and so on, until the entire page is formed. Decomposing your view like that makes it, as you already guessed, modular, encapsulated, and "object-oriented" - composed of many individual MVC components building upon each other. Sort of like good old custom JSP tags, only evaluated at runtime and compatible with technologies like Spring Boot, if you cannot resist trendy resume-boosting stuff like that.
A test form with a 100 fields (all complex "smart" controls with encapsulated state management and behavior) renders in 150ms the first time, and then 10-14ms thereafter. In an IDE debugger on my memory-starved 4y.o. notebook. I also verified it is thread-safe, since Groovy never mentioned it explicitly. Why wouldn't it be, if it is compiled into a stateless Groovy class like any other? Call createTemplate() once, store the Template somewhere, and use it (call Template.make()) in your servlet or another concurrent context. Obviously I'll never have a 100-field form in a real application. Anyone who does, needs to reconsider his/her UX.
The performance is quite adequate. I'd even accept one second to render a 100-field page. Think of it, you don't need ultimate nanotrading or nuclear missile tracking performance in a Web app. If you do, pick Jamon: http://www.jamon.org/Overview.html, which generates a Java class, you'd normally write to concatenate Strings. I didn't test it, as I don't like extra compilation steps (automatically executed by Maven, but still). Compiled Groovy bytecode is good enough for me - compared to the compiled, yes, strongly-typed Java. The difference would be marginal unless you are doing something complex, which you shouldn't inside a template (see below). Playing with typed Groovy variables vs. def as suggested in this thread, only saved me a couple of milliseconds on that 100-template run.
Templates should not have much procedural logic (internal variables, ifs and loops) anyway - that's the controller's, not view's responsibility. That said, ifs and loops are a must for a template engine. Why would one use Handlebars/Mustache, if he/she can simply call String.replace()?
The rest of the template engines is also irrelevant. No String concatenation (e.g. Velocity, or Freemarker) or interpreted JS-based technology (e.g. Jade) would ever beat the most direct Jamon's approach performance-wise. And being a Java programmer, you want to use your favorite language/syntax: either directly (Jamon) or 90% close to Java, Groovy is (being a scripting-centric concise interpreted Java). I wouldn't comment on Scala - the matter of preference. Other than its allegedly "concise" syntax (less and less relevant with Java 8+) comes at a price. And only matters for complex loops. You do not want to write your entire app inside one template, like I already said. A couple of loops and up to ten if statements max.
And, like everyone mentioned, the intuitive syntax, and ease of use is the key. They drastically reduce the number of bugs. A good (additional) server costs a $1000, while developer salaries - to fix all of the bugs stemming form the complexity of marginal performance optimization, are 100 times higher.
My question has two parts:
Does anyone have any tips or references to some documentation on the web about how to write GUI code that is easy to read, write, and maintain?
Example.
I find that the more extensive my GUI forms become, I end up with a long list of fairly short event handler methods. If I try to add any private helper methods, they just get lost in the shuffle, and I constantly have to scroll around the page to follow a single line of thought.
How can I easily manage settings across the application?
Example.
If the user selects a new item in a drop-down list, I might need to enable some components on the GUI, update an app config file, and store the new value in a local variable for later. I usually opt to not create event handlers for all the settings (see above), and end up with methods like "LoadGUISettings" and "SaveGUISettings", but then I end up calling these methods all over my code, and it runs through a lot of code just to update very few, if any, actual changes.
Thanks!
Some guidelines for the first question, from an OO perspective:
Break up large classes into smaller ones. Does that panel have a bunch of fairly modular subpanels? Make a smaller class for each subpanel, then have another, higher-level class put them all together.
Reduce duplication. Do you have two trees that share functionality? Make a superclass! Are all of your event handlers doing something similar? Create a method that they all call!
Second question. I see two ways of doing this:
Listeners. If many components should respond to a change that occured in one component, have that component fire an event.
Global variables. If many components are reading and writing the same data, make it global (however you do that in your chosen language). For extra usefulness, combine the two approaches and let components listen for changes in the global data object.
If you're using WPF, you might want to read the Composite Application Guideance for WPF.
It discusses many of these topics (as well as many others). The main goal of that guideance is to make large scale applications in a flexible, maintainable manner.
You should definitely look at Jeremy Miller's guide to rich client design. It is incomplete, but I believe he is writing a book on the subject.
Another blog you should check out is Rich Newman's. He is writing about Composite Application Block which is a MS best practice guide on how to structure rich clients.
You can also read this book which is only a very light read but gives you some good ideas.