DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Popular Topics

article thumbnail
It's Official! Fat Arrows in JavaScript!
It’s official! We’re getting a new function syntax! The TC39 group (the panel charged with delivering ES 6) has reached a consensus on an abbreviated syntax for JavaScript function expressions. It's popularly known as the fat arrow syntax, and is based on a similar construct found in CoffeeScript. Make no mistake, I’m delighted that we will finally have an alternative to the unnecessary clunkiness and verbosity of the present grammar, but I can’t shake a nagging feeling that this proposal (in its current form) is flawed to the extent that it might actually make new developers more confused than they already were. I’ll run through the key features of this new construct, then explain my concerns and how they might be mitigated. There are Finally Fat Arrows in Java Java continues to add new features and make itself more useful to the public in due course. That said, there are many who have complained that the service never allowed them to put in the fat arrows that they wanted to. It was a glaring hole in the program, and it has now been clamped down on. People are finally able to get the fat arrow designs that they have been looking for without having to use another program to make it happen. Make sure you take a look at the full scope of what Java has to offer you as you explore the promise that it will be something even grander than anything else out on the marketplace at this time. You will want to take advantage of these new arrow designs if you can, and you will want to check up on all of the latest offerings from Java whenever possible. BS Alert Before starting out I should let you know that I’m going to make a lot of assertions about how fat arrows work. I’m reasonably confident that most of them are consistent with the latest proposal, but since research material is scant (I’m relying on the ES Wiki and the ES discuss list) and the examples are not testable (the traceur compiler does not yet support fat arrows) there are going to be some mistakes, for which I apologize upfront. I welcome corrections and will update the content as I get them. Thanks! How does it Work? The Syntax The fat arrow grammar has the following characteristics: 1. The arrow (=>) takes the place of the function keyword 2. Parameters are specified before the arrow, parentheses are required when there are zero, two or more parameters. 3. Block syntax (i.e. enclosing the function body in curly braces) is optional when the body comprises a single expression, otherwise it is required. 4. The return keyword is implied when the function body comprises a single expression. In all other cases returns must be used explicitly. Here are some simple examples. I’ve paired each fat arrow use case with the corresponding long-form syntax, although as we’ll see later the paired functions do not necessarily represent identical behavior. I’m defining variables with the var keyword for the sake of familiarity, but by the time ES6 is implemented you’re more likely to use let which allows variables to be defined with block scoping: //empty function var fat1 = () => {}; var long1 = function() {}; //return the square var fat2 = x => x * x; var long2 = function(x) {return x * x}; //add two numbers var fat3 = (a, b) => a + b; var long3 = function(a, b) {return a + b}; //return square root if x is a number, otherwise return x var fat4 = x => (typeof x == "number") ? Math.sqrt(x) : x; var long4 = function(x) { return (typeof x == "number") ? Math.sqrt(x) : x; }; Fat arrows bring a terse elegance to functional JavaScript… //return a new array containing the squares of the original... [1, 2, 3, 4, 5].map(x => x * x); //[1, 4, 9, 16, 25] //capitalize... ['caption', 'select', 'cite', 'article'].map(word => word.toUpperCase()); //['CAPTION', 'SELECT', 'CITE', 'ARTICLE'] //rewrite all instances of Fahrenheit as Celsius... function f2c(x) { var test = /(\d+(\.\d*)?)F\b/g; return x.replace(test, (str, val) => (val-32)*5/9 + "C"); } f2c("Store between 50F and 77F"); //"Store between 10C and 25C" (The last example is a rewrite of this traditional implementation). No Extras For You, Fat Arrow Not only do fat arrows use lightweight syntax – they also generate lightweight functions… No Constructors Functions created using fat arrow syntax have no prototype property, which means they can’t be used as constructors. If you try to use a fat arrow function as a constructor it throws a TypeError. No Arguments The argument’s object is not available within the execution context of a fat arrow function. This is not a huge loss; by the time ES 6 is in full swing, we can expect arguments to have been deprecated in favor of the rest (...) syntax. No Names There are Function Expressions, and then there are Named Function Expressions. Fat arrow functions have no place for a name, so they will always just be plain anonymous Function Expressions. The Value of This Functions defined with the fat arrow syntax have their context lexically bound; i.e. this value is set to the value of the enclosing scope (the outer function where present, otherwise the global object). //with long-form inner function var myObj = { longOuter: function() { console.log(this); //this is myObj var longInner = function() { console.log(this); //this is global object }; longInner(); } } myObj.longOuter(); //with fat arrow inner function var myObj = { longOuter: function() { console.log(this); //this is myObj var fatInner = () => console.log(this); //this is myObj fatInner(); } } myObj.longOuter(); It's a hard binding, which means if a fat arrow is used to define a method in an object literal it will continue to be bound to that object even when invoked from a borrowing object: var myObj = { myMethod: function() {return () => this;}, toString: () => "myObj" } var yourThievingObject = { hoard: myObj.myMethod, toString: () => "yourThievingObject" }; yourThievingObject.hoard(); //"myObj" Similarly the this value of a fat arrow function cannot be modified by means of call or apply: //traditional long inner function var myObj = { longOuter: function() { console.log(this); //this is myObj var longInner = function() { console.log(this); //this is now myOtherObj } longInner.call(myOtherObj); } } myOtherObj = {}; myObj.longOuter(); //new fat inner function var myObj = { longOuter: function() { console.log(this); //this is myObj var fatInner = () => console.log(this); //this is still myObj fatInner.call(myOtherObj); } } myOtherObj = {}; myObj.longOuter(); So What’s the Problem? If you trawl the JavaScript section of Stack Overflow, you’ll find dozens of questions from puzzled developers trying to get their heads around JavaScript’s somewhat byzantine process of this assignment. So…remember how there are five ways to define the value of this in a function?… Syntax of function call Value of this 1. Method call: myObject.foo(); myObject 2. Baseless function call: foo(); global object (e.g. window) (undefined in strict mode) 3. Using call: foo.call(context, myArg); context 4. Using apply: foo.apply(context, [myArgs]); context 5. Constructor with new: var newFoo = new Foo(); the new instance (e.g. newFoo) …well now there’s a sixth… Syntax of function call Value of this 6. Fat Arrow: (x => x*x)(); this of lexical parent (A seventh rule was also proposed – naming the first argument of a fat arrow as ‘this’ would have bound the context to the base reference of a method call – but thankfully that option has been deferred). I appreciate the rationale behind lexical this binding. It’s intuitive, and if JavaScript was starting over, this would not be a bad way to do it. But at this point I’ve fallen in love with dynamic this values; they make functions gloriously flexible and are a great compliment to functional patterns, wherein functions form the bedrock of data, and other objects are mere fungibles. Moreover, if new developers are already discouraged by JavaScript’s perceived arbitrary assignment of context, yet another rule might be enough to finish them off for good. Bear in mind that fat arrow is sugar, and a very tasty sugar at that; it will be eagerly devoured by many developers long before the consequences of the sixth law of this has time to sink in. There’s another, related issue with the current proposal. Legacy functions (third party or otherwise) generally assume that their function arguments have dynamic this values. This enables them to invoke function arguments in any given context, which, amongst other things, is a useful way to add mixins. It’s true that Function.prototype.bind already offers a form of hard binding, but it does so explicitly; on the other hand, fat arrow’s hard binding is a side effect and it’s not at all obvious that it would break code like this: function mixin(obj, fn) { fn.call(obj); } //long form function mixin is dynamically bound var withCircleUtilsLong = function() { this.area = function() {return this.radius * this.radius * Math.PI}; this.diameter = function() {return this.radius + this.radius}; } //fat arrow function mixin is lexically bound (to global object in this case) var withCircleUtilsFat = () => { this.area = function() {return this.radius * this.radius * Math.PI}; this.diameter = function() {return this.radius + this.radius}; } var CircularThing = function(r) {this.radius = r}; //utils get added to CircularThing.prototype mixin(CircularThing.prototype, withCircleUtilsLong); (new CircularThing(1)).area(); //3.14 //utils get added to global object mixin(CircularThing.prototype, withCircleUtilsFat); (new CircularThing(1)).area(); //area is undefined How to Fix It OK, enough whining; time to make some proposals. Here are three ideas to remove, or at least mitigate, any negative effects of the new fat arrow context behavior. 1) (This one’s easy). Have fat arrow functions define this the same way as any regular Function Expression does – i.e. according to the five rules in the table above. It’s worth noting that CoffeeScript defined fat arrow as an alternative to their thin arrow (->) syntax. Thin arrow in CoffeeScript behaves, by and large, the same way as regular JavaScript Function Expressions. In contrast, ES6′s fat arrow is attempting to do at least two things at once – be the sole abbreviator of the syntax and redefine context assignment. To do one, or the other, would be less confusing. 2) (You probably saw this one coming too). Introduce thin arrow syntax at the same time. That way developers are drawn to the safer, less radical sugar which simply abbreviates their Function Expressions without throwing in secret surprises that mess with their contexts. Fat arrow expressions become the special case, not the default. This mail suggested the difference between fat and thin arrow would confuse folks, but by removing thin arrow we remove the stepping stone between dynamically bound long form functions and hardbound short form functions and the necessary conceptual leap becomes more radical. 3) (This one was proposed by @fb55 on the es discuss list). Only employ lexical scoping as a fallback when no other this binding is suggested. In other words, this would take the value of the base reference in a method call, or the context passed with a call or apply, but would defer to lexical scoping when invoked as a standalone function. (Standalone functions might just be the only part of JavaScript this assignment that actually needs fixing anyway). Wrap Up Is the primary goal of arrow functions brevity? or a hard-lexical binding? If it’s the former (and even if it isn't, a lot of developers will perceive that it is) then we should be careful not to overload it with new or surprising behavior. Oh and follow @fat.
August 13, 2022
by Angus Croll
· 17,341 Views · 1 Like
article thumbnail
7 Best MQTT Client Tools Worth Trying
Find a suitable client tool for MQTT testing. Listed by desktop, browser, and command line categories, these tools are available for free (most, open source).
August 12, 2022
by Li Guowei
· 10,215 Views · 1 Like
article thumbnail
Extending Iridium With Custom Step Definitions
Iridium makes it easy for developers to build in their own custom step definitions, removing the need to write custom code gluing Cucumber and WebDriver together.
Updated August 12, 2022
by Matthew Casperson
· 3,269 Views · 1 Like
article thumbnail
Creating Application using Spring Roo and Deploying on Google App Engine
Spring Roo is an rapid application development tool that helps you in rapidly building spring-based enterprise applications in the java programming language. Google app engine is a cloud computing technology that lets you run your application on Google's infrastructure. Using Spring Roo, you can develop applications that can be deployed on the Google app engine. In this tutorial, we will develop a simple application that can run on the Google app engine. Roo configures and manages your application using the Roo shell. Roo shell can be launched as a stand-alone, command-line tool, or as a view pane in the Springsource tool suite ide. Create it Fast and Effectively Most who create applications want to make them fast, and they want to make them effectively. What this means is that if they can figure out a way to create something that will both work for their users and also provide them with the speed of transaction that they need, then it is entirely possible that this will be precisely what they need to do in order to get the best results. Most are looking to Google search as a great way to get their apps out into the world, and it seems like this is as good of a place as any to start. Pushing out apps that can help the general population get the help they need with various projects means working with the most popular search engines in the world to make it happen. Thus, you should look to develop apps that work on Google in order to get the kind of results that you require. Prerequisite Before we can start using the Roo shell, we need to download and install all prerequisites. Download and install SpringSource Tool Suite 2.3.3. m2. Spring Roo 1.1.0.m2 comes bundled with STS. While installing STS, the installer asks for the location where STS should be installed. in that directory, it will create a folder with the name "roo-%release_number%" which will contain roo stuff. add %spring_roo%/roo-1.1.0.m2/bin in your path so that when you can fire roo commands from the command line. Start STS and go to the dashboard (help->dashboard) Click on the extensions tab Install the "google plugin for eclipse" and the "datanucleus plugin". Restart STS when prompted. After installing all the above we can start building the application. Conferenceregistration.roo Application Conference registration is a simple application where speakers can register themselves and create a session they want to talk about. So, we will be having two entities: speaker and presentation. Follow the instructions to create the application: Open your operating system command-line shell Create a directory named conference-registration Go to the conference-registration directory in your command-line shell Fire Roo command. You will see a roo shell as shown below. Hint command gives you the next actions you can take to manage your application. Type the hint command and press enter. Roo will tell you that first you need to create a project and for creating a project you should type 'project' and then hit tab. Hint command is very useful as you don't have to cram all the commands; it will always give you the next logical steps that you can take at that point. Roo hint command told us that we have to create the project so type the project command as shown below project --toplevelpackage com.shekhar.conference.registration --java 6 This command created a new maven project with the top-level package name as com. Shekhar.conference.registration and created directories for storing source code and other resource files. In this command, we also specified that we are using Java version 6. Once you have created the project, type in the hint command again, Roo will tell you that now you have to set up the persistence. Type the following command persistence setup --provider datanucleus --database google_app_engine --applicationid roo-gae This command set up all the things required for persistence. It creates persistence.xml and adds all the dependencies required for persistence in pom.xml. We have chosen the provider as DataNucleus and the database as google_app_engine because we are developing our application for google app engine and it uses its own data store. Applicationid is also required when we deploy our application to the Google app engine. Now our persistence setup is completed. 8. Type the hint command again, Roo will tell you that you have to create entities now. so, we need to create our entities' speaker and presentation. To create a speaker entity, we will type the following commands entity --class ~.domain.speaker --testautomatically field string --fieldname fullname --notnull field string --fieldname email --notnull --regexp ^([0-9a-za-z]([-.\w]*[0-9a-za-z])*@([0-9a-za-z][-\w]*[0-9a-za-z]\.)+[a-za-z]{2,9})$ field string --fieldname city field date --fieldname birthdate --type java.util.date --notnull field string --fieldname bio The above six lines created an entity named session with different fields. In this, we have used notnull constraint, email regex validation, date field. Spring Roo on the app engine does not support enum and references yet which means that you can't define one-one or one-to-many relationships between entities yet. These capabilities are supported on spring MVC applications but spring MVC applications can't be deployed on app engines as of now. Spring Roo Jira has these issues. They will be fixed in future releases(hope so :) ). 9. Next create the second entity of our application presentation. To create a presentation entity type the following commands on Roo shell entity --class ~.domain.presentation --testautomatically field string --fieldname title --notnull field string --fieldname description --notnull field string --fieldname speaker --notnull The above four lines created a jpa entity called presentation, located in the domain sub-package, and added three fields -- title,description and speaker. As you can see, the speaker is added as a string (just enter the full name). Spring Roo on google app engine still does not support references. 10. Now that we have created our entities, we have to create the face of our application i.e. user interface. currently, only GWT-created UI runs on the app engine. so, we will create GWT user interface. To do that type gwt setup this command will add the GWT controller as well as all the UI required stuff. This command may take a couple of minutes if you don't have those dependencies in your maven repository. 11. Next you can configure the log4j to debug level using the following command logging setup --level debug 12. Quit the Roo shell 13. You can easily run your application locally if you have maven installed on your system, simply type "mvn gwt:run" at your command line shell while you are in the same directory in which you created the project. This will launch the GWT development mode and you can test your application. Please note that applications do not run in the Google chrome browser when you run from your development environment. So, better run it in firefox. 14. To deploy your application to the Google app engine just type mvn gwt:compile gae:deploy it will ask you for app engine credentials (email id and password).
August 12, 2022
by Shekhar Gulati
· 52,310 Views · 1 Like
article thumbnail
CouchDB vs. MariaDB: Which Is Better?
We take a comparative look at two of the most popular databases on the market today, CouchDB and MariaDB, and what each brings to the table for your team.
Updated August 12, 2022
by Subin Sabu
· 14,236 Views · 6 Likes
article thumbnail
CoffeeScript: a TDD example
CoffeeScript is a language building an abstraction over JavaScript (as the similar name suggests.) It is an abstraction over the syntax of JavaScript, not over its concepts: the language is still based on functions as objects which may bind to other objects, and prototypical inheritance. CoffeeScript favors the best practices of JavaScript by transforming abstractions you would have written anyway, or borrowed from a framework, into language concepts for maximum conciseness. It has a compilation step - as every language must compile to a lower-level one, like C or Java. Since cowboy coding is not my preferred way to work, I prepared a Test-Driven Development example by using jsTestDriver. In this article, you get two things: a CoffeeScript introduction, and the tools for unit testing it (and consequently, how to TDD with CoffeeScript). Building on Top of JavaScript There is something to be said for those who go out of their way to try to improve the infrastructure of existing programs. Many have taken a stab at it by creating tools that are a compliment to JavaScript, and it appears to have worked quite well in this case. The reason? Because JavaScript is in need of some improvements. One of the programs that people have come up with is CoffeeScript. It is literally a bit of computer code that overlays the existing JavaScript codes to make it read even more fluidly. The benefit that one gets from this is that they can start to use JavaScript in a more efficient way with fewer bumps in the road. As it stands right now, JavaScript has numerous challenging issues that we must recognize. However, that can all be amended by using JavaScript as it was intended and just working towards perfecting it. CoffeeScript is certainly not the end all be all of the programs for improving JavaScript, but it is a great step in the right direction. People should at least try out the CoffeeScript code to see if it may be useful to them in terms of improving the quality of codes that they receive from JavaScript. If so, then it will have been worth the trouble. The infrastructure The basic structure consists of two folders: src/ and lib/; remember the compilation step. We'll put .coffee files into src/ and compile them to .js equivalents in a symmetrical tree in lib/. We add also a jsTestDriver.conf file to tell the unit testing framework all the files to load, which are only the "binary" .js scripts: server: http://localhost:4224 load: - lib/*.js Compiling This is the first version of the test I've managed to write, fizzbuzztest.coffee. It is a tautology that should always pass: mytest = () -> assertEquals(1, 1) tests = { "test1is1": mytest } TestCase("tests for fizzbuzz kata", tests) You see here that functions are still first-class objects, but only anonymous functions are supported. CoffeeScript is a Python/Ruby-like language without semicolons, and there are some affinities and common backgrounds with the latter language. I still use the old syntax for calling functions for now, although parentheses can be omitted in many cases. CoffeeScript is conservative, and even accepts semicolons if you want to write them. I compiled this script with coffee -o lib/ -c src/. fizzbuzztest.js is the result: (function(){ var mytest, tests; mytest = function() { return assertEquals(1, 1); }; tests = { "test1is1": mytest }; TestCase("tests for fizzbuzz kata", tests); })(); The global namespace is not touched by default, and var keywords are automatically introduced to preserve it. When I later needed the global namespace, I wrote: this.fizzbuzz = /* ... function definition ... */ This in this case is the window object or the other global object where you execute the code. Running To run the test, we must initialize the test driver (only once): jsTestDriver java -jar JsTestDriver-1.3.2.jar --port 4224 jsTestDriver will now listen at localhost:4224. Load this URL in your browser and capture it by clicking on the link. Tests will be executed inside the browser when requested: for more details see the related article. Every time you want to run the tests, execute them from the command line: java -jar JsTestDriver-1.3.2.jar --tests all This is the complete history of my kata. Here is the final version of the code (spoiler alert!), with support for addition of other factors than 3 or 5. The code is probably uglier than average, but it compiles: tests = { "test ordinary numbers are unchanged": -> assertEquals(1, fizzbuzz(1)) assertEquals(2, fizzbuzz(2)) assertEquals(4, fizzbuzz(4)) assertEquals(142, fizzbuzz(142)) "test multiples of 3 become fizz": -> assertEquals("Fizz", fizzbuzz(3)) assertEquals("Fizz", fizzbuzz(6)) assertEquals("Fizz", fizzbuzz(9)) "test multiples of 5 become buzz": -> assertEquals("Buzz", fizzbuzz(5)) assertEquals("Buzz", fizzbuzz(10)) "test multiples of 3 and 5 become fizzbuzz": -> assertEquals("FizzBuzz", fizzbuzz(15)) assertEquals("FizzBuzz", fizzbuzz(45)) } TestCase("tests for fizzbuzz kata", tests) newRule = (word, divisor) -> (number) -> return word if number % divisor == 0 "" newFizzBuzz = (rules) -> (number) -> result = "" concatenation = (rule) -> result = result + rule(number) concatenation rule for rule in rules return result if result number fizzRule = newRule("Fizz", 3) buzzRule = newRule("Buzz", 5) this.fizzbuzz = newFizzBuzz([fizzRule, buzzRule]) Comments On The Experience CoffeeScript offers a shorter syntax, which presents a bit of a learning curve but not a steep one. I went through the whole example in 1 hour (I already knew how to use jsTestDriver, however.) Syntax shapes how you write code by making some things easier: I found myself using higher-order functions which create other ones more often, since creating a function now is just a matter of putting -> before some lines of code. Variable naming is also simpler as you just have to think of the name, not about var or polluting the scope. More time to dedicate to design, and less to language issues. Some one-liners like the instruction if the expression is handy but not essential, and are there due to Ruby's inspiration. There's, even more, to discover in CoffeeScript, such as the options for the binding of functions which helps not to lose the reference to this. However, the question is if all this convenience has more value than the time spent to learn a new language and add infrastructure to make it work - the compiler, the build hooks, and the parallel tree to ignore in your version control system.
August 12, 2022
by Giorgio Sironi
· 15,655 Views · 1 Like
article thumbnail
Clojure: Destructuring
In The Joy of Clojure (TJoC) destructuring is described as a mini-language within Clojure. It's not essential to learn this mini-language; however, as the authors of TJoC point out, destructuring facilitates concise, elegant code. Making Code More Understandable One of the scariest things for those who are just now learning how to do some coding is the fact that they have to try to figure out what a seemingly impossible set of rules and structures means for the work that they are trying to do. It is not easy at all, and many people struggle with it in big ways. Fortunately, there are some people who are going about the process of destructuring code so that it may be broken into smaller and more manageable chunks. If this is to happen, then one can easily see how they can potentially get a lot more value from the process of coding, and even how they can contribute to it for themselves in the future. We need to be as encouraging of the next generation of coders as we possibly can because there is no question that they will ultimately have an outsized impact on how the future of coding is decided. If they are best set up to understand coding and to make sense of its many intricacies, then they will be able to handle it without problems. However, we need to support and encourage them along the way, and that all begins by making coding easier to understand in general. What is destructuring? Clojure supports abstract structural binding, often called destructuring, in let binding lists, fn parameter lists, and any macro that expands into a let or fn. -- http://clojure.org/special_forms The simplest example of destructuring is assigning the values of a vector. user=> (def point [5 7]) #'user/point user=> (let [[x y] point] (println "x:" x "y:" y)) x: 5 y: 7 note: I'm using let for my examples of destructuring; however, in practice, I tend to use destructuring in function parameter lists at least as often, if not more often. I'll admit that I can't remember ever using destructuring like the first example, but it's a good starting point. A more realistic example is splitting a vector into a head and a tail. When defining a function with an arglist** you use an ampersand. The same is true in destructuring. user=> (def indexes [1 2 3]) #'user/indexes user=> (let [[x & more] indexes] (println "x:" x "more:" more)) x: 1 more: (2 3) It's also worth noting that you can bind the entire vector to a local using the :as directive. user=> (def indexes [1 2 3]) #'user/indexes user=> (let [[x & more :as full-list] indexes] (println "x:" x "more:" more "full list:" full-list)) x: 1 more: (2 3) full list: [1 2 3] Vector examples are the easiest; however, in practice I find myself using destructuring with maps far more often. Simple destructuring on a map is as easy as choosing a local name and providing the key. user=> (def point {:x 5 :y 7}) #'user/point user=> (let [{the-x :x the-y :y} point] (println "x:" the-x "y:" the-y)) x: 5 y: 7 As the example shows, the values of :x and :y are bound to locals with the names the-x and the-y. In practice we would never prepend "the-" to our local names; however, using different names provides a bit of clarity for our first example. In production code you would be much more likely to want locals with the same name as the key. This works perfectly well, as the next example shows. user=> (def point {:x 5 :y 7}) #'user/point user=> (let [{x :x y :y} point] (println "x:" x "y:" y)) x: 5 y: 7 While this works perfectly well, creating locals with the same name as the keys become tedious and annoying (especially when your keys are longer than one letter). Clojure anticipates this frustration and provides :keys directive that allows you to specify keys that you would like as locals with the same name. user=> (def point {:x 5 :y 7}) #'user/point user=> (let [{:keys [x y]} point] (println "x:" x "y:" y)) x: 5 y: 7 There are a few directives that work while destructuring maps. The above example shows the use of :keys. In practice I end up using :keys the most; however, I've also used the :as directive while working with maps. The following example illustrates the use of an :as directive to bind a local with the entire map. user=> (def point {:x 5 :y 7}) #'user/point user=> (let [{:keys [x y] :as the-point} point] (println "x:" x "y:" y "point:" the-point)) x: 5 y: 7 point: {:x 5, :y 7} We've now seen the :as directive used for both vectors and maps. In both cases, the locale is always assigned to the entire expression that is being destructured. For completeness I'll document the :or directive; however, I must admit that I've never used it in practice. The :or directive is used to assign default values when the map being destructured doesn't contain a specified key. user=> (def point {:y 7}) #'user/point user=> (let [{:keys [x y] :or {x 0 y 0} point] (println "x:" x "y:" y)) x: 0 y: 7 Lastly, it's also worth noting that you can destructure nested maps, vectors and a combination of both. The following example destructures a nested map user=> (def book {:name "SICP" :details {:pages 657 :isbn-10 "0262011530"}) #'user/book user=> (let [{name :name {pages :pages isbn-10 :isbn-10} :details} book] (println "name:" name "pages:" pages "isbn-10:" isbn-10)) name: SICP pages: 657 isbn-10: 0262011530 As you would expect, you can also use directives while destructuring nested maps. user=> (def book {:name "SICP" :details {:pages 657 :isbn-10 "0262011530"}) #'user/book user=> user=> (let [{name :name {:keys [pages isbn-10]} :details} book] (println "name:" name "pages:" pages "isbn-10:" isbn-10)) name: SICP pages: 657 isbn-10: 0262011530 Destructuring nested vectors is also very straight-forward, as the following example illustrates user=> (def numbers [[1 2][3 4]]) #'user/numbers user=> (let [[[a b][c d]] numbers] (println "a:" a "b:" b "c:" c "d:" d)) a: 1 b: 2 c: 3 d: 4 Since binding forms can be nested within one another arbitrarily, you can pull apart just about anything -- http://clojure.org/special_forms The following example destructures a map and a vector at the same time. user=> (def golfer {:name "Jim" :scores [3 5 4 5]}) #'user/golfer user=> (let [{name :name [hole1 hole2] :scores} golfer] (println "name:" name "hole1:" hole1 "hole2:" hole2)) name: Jim hole1: 3 hole2: 5 The same example can be rewritten using a function definition to show the simplicity of using destructuring in parameter lists. user=> (defn print-status [{name :name [hole1 hole2] :scores}] (println "name:" name "hole1:" hole1 "hole2:" hole2)) #'user/print-status user=> (print-status {:name "Jim" :scores [3 5 4 5]}) name: Jim hole1: 3 hole2: 5 There are other (less used) directives and deeper explanations available on http://clojure.org/special_forms and in The Joy of Clojure. I recommend both. **(defn do-something [x y & more] ... )
August 12, 2022
by Jay Fields
· 15,011 Views · 1 Like
article thumbnail
The Challenges of a JavaFX Reboot
In Jonathan Giles's post An FX Experience Retrospective, he starts by looking at the history of JavaFX and focuses on "what has happened in the world of JavaFX" in 2011. I was highly skeptical of JavaFX prior to JavaOne 2010 (see here and here for examples), but started to think more positively about it after the JavaOne 2010 and JavaOne 2011 announcements related to JavaFX. One thing that has been a little tricky about learning JavaFX since JavaOne 2011's big announcements have been knowing for certain whether a particular resource on JavaFX applies to JavaFX 1.x or JavaFX 2.x. Reading the An FX Experience Retrospective post provided a different perspective on the risks and challenges Oracle and the JavaFX team has faced in making this major overhaul. A JavaFX Reboot is Going to be a Challenge It is absolutely the case that a JavaFx Reboot will be an extreme challenge in that most people haven’t given the idea of rebooting this system much thought at all. They assume that the JavaFx system will work just as well for them today as it has in the past, but they may be making a big mistake in making such a sweeping judgment. There are many who feel that JavaFx is in need of an update/upgrade, but it is not clear how that is going to be possible. So many of the elements of JavaFX were built with a specific purpose in mind, and it is far from easy to change course on that idea at this stage of the game. Thus, it seems likely that JavaFx will largely continue to exist as it has for all of these years and not receive the upgrade that it needs at this time. However, there are at least some people who are working around the edges to see what they can do about putting the JavaFx train back on the tracks that were designed for it. Giles writes in his post, "Another vivid recollection I have from JavaOne 2010 is the various reactions that people had of this news. It varied from those in shock at losing their favorite language, to those who said it was long overdue and was the right way to proceed with JavaFX." I was in the latter group, welcoming this change and I would have liked to see it happen even sooner. The ability to use JavaFX with standard Java language and APIs was a huge benefit in my opinion and finally gave credence to the pro-JavaFX argument to Java developers that "JavaFX is Java." The JavaOne 2011 announcements of making JavaFX open source and making it part of standard Java SE were likely less controversial for Java developers (who wouldn't want these characteristics?) and are also important to me in my renewed interest in JavaFX. For developers just learning JavaFX, it can be a bit tricky to know if an online resource is for JavaFX 1.x or 2.x without delving into the article. The changes in JavaFX from 1.x to 2.x are significant enough that I generally don't want to risk confusion by reading JavaFX 1.x resources (though some have found value in reading JavaFX 1.x resources in preparation for using JavaFX 2.0). However, there are some clues that can help make it quicker and easier to identify which version of JavaFX is applicable. It is most obvious that an article is about JavaFX 2.0 when it explicitly states so. I try to do this with my blog posts on JavaFX 2.0, though I'm sure I occasionally forget to do so. When an article or blog post does not state the version of JavaFX specifically, another good clue is the date of the resource. In general, it is usually safe to assume that anything written about JavaFX before late 2010 is about JavaFX 1.x and it is similarly safe to assume that most things written about JavaFX in 2011 or later are about JavaFX 2.x. Another clue to watch for is discussion in a resource that includes JavaFX Script or FXML references. The former (JavaFX Script) was exclusive to JavaFX 1.x and the latter (FXML) is exclusive to JavaFX 2.x. Some really good documentation on JavaFX 2.x has been made available recently. The JavaFX 2.0 documentation states the following about JavaFX 2.0 versus JavaFX 1.3: JavaFX 2.0 is the latest major update release for JavaFX. Many of the new features introduced in JavaFX 2.0 are incompatible with JavaFX 1.3. If you are developing a new application in JavaFX, it is recommended that you start with JavaFX 2.0. The JavaFX 2.0 documentation contains many newly written or updated articles and posts on JavaFX 2.0. This set of documentation includes What is JavaFX?, Getting Started with JavaFX, Working with the JavaFX Scene Graph, Introduction to FXML, Getting Started with FXML, and Using JavaFX Charts. Books on JavaFX provide another perspective on the challenges associated with the major shift in JavaFX's vision. Most JavaFX books that are currently available were written for JavaFX 1.x. berry120 (who has also blogged on JavaFX 2) recently asked, Any decent books on JavaFX 2? As far as I can tell, the only JavaFX 2.x book currently available is Carl Dea's JavaFX 2.0: Introduction by Example (I hope to write a review of this short, recipe-oriented book in the near future). This book has a publication date (2011) and JavaFX 2.0 in its title, making it clear that it's on JavaFX 2.0. With books, which typically have a longer time between writing and publishing, even early 2011 publication dates might still mean a book on JavaFX 1.x. Another good clue with books is the price of used books on the Amazon Marketplace. Books on old and/or deprecated language versions tend to be very cheap. Other books on JavaFX 2.0 are likely to come. Pro JavaFXTM 2 Platform A Definitive Guide to Script, Desktop and Mobile RIA with JavaTM Technology has an advertised publication date of 12 February 2012. Carefully wading through online resources and selecting books to purchase is tricky for developers because of the major shift in JavaFX's long-term vision. Giles's post provides some insight into the even greater effort required within Oracle and the JavaFX team to make this major shift. As painful as the shift is, I believe this shift in vision coming at the cost of short-term pain provides JavaFX a fighting chance for a prosperous long-term future.
August 12, 2022
by Dustin Marx
· 10,024 Views · 4 Likes
article thumbnail
Rust’s Ownership and Borrowing Enforce Memory Safety
By using an ownership model, Rust takes a novel approach to ensure memory safety at compile time.
August 11, 2022
by Senthil Nayagan
· 5,258 Views · 2 Likes
article thumbnail
Conceptual Architecture: Conversational AI/NLP-Based Platform
Conceptual Architecture for Conversational Artificial Intelligence (AI) / Natural Language Processing (NLP) based Platform for Customer Support and Agent Services.
August 11, 2022
by Chandra Manohar
· 10,275 Views · 3 Likes
article thumbnail
10 Best Infrastructure-as-Code Tools for Automating Deployments in 2022
With the rapidly changing technology landscape, the traditional approaches to infrastructure are hampering businesses to adapt, innovate, and thrive optimally. Now, Infrastructure as Code (IaC) tools have emerged as the key to navigating this challenge.
August 10, 2022
by Vishnu Vasudevan
· 7,437 Views · 2 Likes
article thumbnail
What Is the Future of Humans With Artificial Intelligence (AI)?
The use of AI can facilitate humankind in reaching its potential. It will contribute to a sustainable future for humans if used within ethical limits.
August 10, 2022
by Emily Daniel
· 5,671 Views · 1 Like
article thumbnail
Problems With Kafka Streams: The Saga Continues
Problems with the old version of Kafka haven't been solved completely. Some shortcomings have been fixed while some problems have been introduced. The cycle continues.
Updated August 10, 2022
by Aleksandar Pejakovic
· 17,606 Views · 11 Likes
article thumbnail
Delivering the Future of Uber-Like Apps With AI and ML
Uber uses AI and ML for fraud detection, risk assessment, safety processes, marketing, matching drivers and riders, and just about everywhere else it's possible to apply.
Updated August 10, 2022
by Anahit Ghazaryan
· 7,956 Views · 3 Likes
article thumbnail
Introduction: Querydsl vs. JPA Criteria
This article presents an introduction to the Querydsl series with the goal to highlight the difference from JPA Criteria.
Updated August 9, 2022
by Arnošt Havelka DZone Core CORE
· 19,392 Views · 8 Likes
article thumbnail
Snake-Based REST API (Python, Mamba, Hydra, and Fast API)
Using Python, Fast API, Hydra, and Mamba to build dockerized applications.
August 9, 2022
by Bartłomiej Żyliński DZone Core CORE
· 8,486 Views · 4 Likes
article thumbnail
How to Write RFCs for Open Source Projects
The importance of RFCs has been emphasized by many people. These documents can help supplement information, improve ideas, and build better designs.
August 9, 2022
by bingxi Wu
· 5,254 Views · 1 Like
article thumbnail
How to Build Spark Lineage for Data Lakes
Better understand the intricacies of Spark and how to build a lineage graph for data lakes.
August 8, 2022
by Lior Gavish
· 4,969 Views · 1 Like
article thumbnail
Auth0 (Okta) vs. Cognito
This article compares two authentication service providers: Auth0 and Amazon Cognito. Both of them are cloud-based identity management services.
August 8, 2022
by Anastasiia Komendantova
· 4,377 Views · 3 Likes
article thumbnail
Build a Java Microservice With AuraDB Free
For today’s adventure, we want to build a Java microservice that connects to, and interacts with, graph data in a Neo4j AuraDB Free database.
Updated August 8, 2022
by Jennifer Reif DZone Core CORE
· 9,832 Views · 5 Likes
  • Previous
  • ...
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×