Category Archives: javascript

Layering in new behavior with React

I’ve talked in the past how I like the approach React leads me to when it comes to building apps. How does such grandiose talk play out when it’s time to add a new, unexpected feature? Let’s check it out. I’ve been building an installation app for Spinnaker, and one of our top notch developer advocates gave it a spin.

Results? Not good. Too many presumptions were built into the UI meaning he had no clue where to go. Message to me? Fix the flow so it’s obvious what must be done and what’s optional.

So I started coding in a feature to flag certain fields REQUIRED and not allow the user to reach the installation screen without filling them out. Sounds easy enough in concept. But how do you do that?

With React, what we’re describing is an enhancement to the state model. Essentially, keep filling out fields, but earmark certain fields as required, and adjust the layout of things to show that, while barring other aspects of the interface in the event those same fields aren’t populated.

So I started with a little bit of code to gather a list of these so-called required fields, and it looked like this:

If you have done any React programming, assigning something via this.state[…] = foo should set off bells in your head. You always, always, ALWAYS used this.setState(…). So what’s up?

Rules are rules until they aren’t. This is a situation that defies the concept. I don’t WANT to set the state such that it triggers a ripple through the DOM. Instead, this code happens right after the initial state model is initialized. And I’m setting it using values populated in the previous line, because you can’t initialize required, pointing at this.state.api in the same call the initializes this.state.api itself!

With this list of required fields setup, we can start marking up the fields on the UI to alert the user. I have a handful of React components that encapsulate different HTML inputs. One of them is dedicate to plain old text inputs. Using the newly minted required list, I can adjust the rendering like this:

Notice the little clause where it checks this.props.settings.requires.includes(this.props.name)? That is a JavaScript ternary operation that if true, returns the label with extra, highlighted text. Otherwise, just render the same label as always.

By applying this same tactic to the other React components I have for rendering each selection on the UI, I don’t have to go to each component and slap on some new property. Instead, the designation for what’s required and what’s not it kept up top in the state model, making it easier to maintain and reason about.

At the top of the screen is a tab the user clicks on to actually install things and track their progress. To ensure no one clicks on that until all required fields are populated, I updated that tab like this:

A little function that detects whether or not all required fields have been filled out is checked, and if so, renders the HTML LI with its onClick property filled out with the handler. If NOT, then it renders the same component, but NO SUCH onClick property is present, meaning it just won’t respond.

This is the nature of React. Instead of dynamically adjusting the DOM model, you declare variant layouts based on the state of the model. This keeps pushing you to put all such changes up into the model, and writing ancillary functions to check the state. In this case, let’s peek at requiredFieldsFilledOut:

This tiny function checks this.state.required, counts how many are “truthy”, and if the count matches the size of this.state.required itself, we’re good to go.

In case you didn’t know it, React encourages you to keep moving state-based functions up, closer to the state model itself. It’s super simple to pass along a handle to the function to lower level components, so they can still be invoked at lower levels. But anytime one component is trying to invoke another one in a separate part of the hierarchy, that’s a React-smell hinting that the functions should be higher up, where they can meet. And that results can trickle down to lower level components.

I encountered such a function stuffed down below in a lower level component. The need to trigger it sooner based on a change in the state had me move it up there. Now, when the Installation tab is clicked, that function is run, instead of waiting for the user to click some button down below.

Suffice it to say, I rehabbed the UI quite nicely. The thing is, with React it’s not hard to effect such change in a couple days, compared to the days or weeks of effort combined with testing it might have taken with classic manipulated-the-DOM apps, where you have to hunt down gobs of wired event handlers and find every little nuanced operation you coded to make things operate correctly.

The beauty of coding frontends with React

This industry can be quite brutal. Tools come and go. Programming styles invented fifty years ago suddenly become relevant. But I really enjoy when a certain toolkit nicely presents itself over and over as the way to go. I’m talking about React. Every wonder what it is that has made coding frontends with React so dang popular? Let’s take a peek.

What’s so good about React?

React innovates frontend development by moving the focus off of cobbling together DOM elements. Instead, it shifts things toward laying out a declarative UI and driving everything by a consolidated state model. Update the state and the layout changes automatically.

In traditional JavaScript toolkits, you find yourself writing DOM finagling code bits inside event handlers strewn throughout the code base. (jQuery, I’m looking at you!) Managing, organizing, and maintaining order of this code is a chore that isn’t hard to fail. It’s easy to NOT cleanup properly and let your app leak.

Get on with the example already!

With React, you lay out a series of HTML elements inside the code (and using ES6 makes your eyes stop bleeding!) based on properties and state.

FYI: Properties are read only attributes, State are updateable attributes. In this component, there are NO event handlers. Everything shown is passed through the constructor call and accessed via this.props.

Some people balk at how React mixes HTML with JavaScript in the same file. Frankly, I find keeping things small and cohesive like this as the right level of mixture

It’s possible to have optional components, and they can be based on the centralized state model. Flip a toggle or trigger off some other thing (RESTful payload?) and see components appear/disappear. (NOTE: React smoothly updates the DOM for you.)

Check out the fragment below:

Toward the bottom, orgsAndSpacesLoading is used as a stateful flag to indicate some data is loading. Using JavaScript’s ternary boolean check, it’s easy to display a Spinner. When the code fetching the data completed, it merely needs to update the state of this flag to false, and React will redraw the UI to show the <span> with two dropdowns.

When piecing together event handlers and DOM elements by hand puts you in this mindset of updating the screen you’re looking at. You start to think about hunting down elements with selectors, changing attributes, and monkeying around with low level constructs.

When working with React, you update the state and imagine React redrawing everything for you. The UI is redrawn constantly to catch up to the new state. Everything is about the state, meaning it’s best to invest effort designing the right state model. This pulls your focus up a distinct level, letting you think more about the big picture.

The state must flow

Another neat characteristic you start doing is pushing bits of state down into lower level components as read-only properties. You also push down functions as invocable properties. You may start with functions in the lower level components, but many of them work their way back to manipulating the state. And often the state works best when pulled toward the top. Hence, functions tend to move up, making lower level components easier driven by properties.

This component is a reusable HTML checkbox with a label. You feed it the name of a state attribute and it allows flipping the state attribute on or off. Changes are invoked by the passed in property function, handleChange. This function is actually passed into a lot of various components in this application. You can see how this component is invoked below:

  • The label text is provided – “OAuth?”
  • The name is connected to a property known as settings.oauthEnabled.
  • The function to respond to clicks is this.handleChange.
  • The raw state is passed down as a bit of a free for all.

The point is, nice little components are easy to put together. Bits of state and needed functions are easy to hand off. And we don’t waste frivolous time with building the DOM and thinking about triggering an update in one part of the UI from some other remote corner of the UI.

We simply update the relevant bits of state and let the system redraw itself as needed. Once you get warmed up to this style of building frontends, it’s hard to put it down.

Happy coding!

JavaScript – the mutable functional programming platform

javascript-all-the-thingsJavaScript, amidst its funny quirks, is an interesting platform for functional programming. Especially given its highly mutable nature. Yes, you heard that right: a mutable functional programming language.

Let me head things off real fast. I’m not an expert on JavaScript. Not sure if I would qualify for senior status should I join a JavaScript-only team. Take my comments with a grain of salt. I just happen to express more interest in JavaScript than most of my surrounding teammates, and have learned a little more, so they tend to come to me with questions.

javascript-nested-functionsJavaScript is HEAVILY based on writing functions. You create them, you pass them around, you anonymously declare them, and you invoke one function while passing in two other anonymous functions. Functions within functions within functions. It is, as I like to say, Inception-esque.

But JavaScript is built on some of the craziest notions. Not a week goes by that someone doesn’t post a truth table of JavaScript comparison operations. It’s rules for converting and not converting between strings and other types is absurd. On a fundamental level, JavaScript is broken.

That last comment might ruffle a few feathers.

  • “You talk about Java a lot. It can’t be as bad as Java!”
  • “Python is crazy with its mandated whitespace formatting. Pu-lease!”
  • “AbstractSingletonProxyFactoryBean. Need I say more?”

(Heh, that last one makes me laugh too. Yes, it’s a class from the Spring Framework, and when you say it, it illustrates either everything wrong with Java or with the Spring Framework.)

keep-calm-and-learn-javascriptBut JavaScript doesn’t have a standardized packaging system. With Java, you have JARs. Python has eggs. And Ruby has gems. To fill the gap, there have been several packaging systems (AMD, Webpack, Browserify, UMD, and requireJS come to mind).

JavaScript somehow has made it into every browser out there (arguably the only reason it has grown in stature), yet many people today are coding in the newest spec, ES6, which hasn’t been folded into browsers. So, we use Babel.js. It’s a little toolkit that transpiles ES6 code into ES5 (currently supported version). But to accommodate all the build systems i just mentioned, there a LOTS of recipes to hook it into your packaging system of choice.

JavaScript, something born in the web browser, has made its way server side. Java itself includes a JavaScript engine (Rhino, Nashorn). node.js emerged as a new way to build server + client apps purely in JavaScript.

weird-al-javascriptThe thing is, when you start talking JavaScript, code geek to code geek, you have to do a little content negotiation. Because you might speak native JavaScript when your buddy is heavily into jQuery. (Believe me, the apps look very different on that aspect alone). You might be using Webpack bundles while your buddy wants something simpler like requireJS. You might be coding ES6 while your buddy uses ES5. If you didn’t get it, ALL these are orthogonal choices. You can write jQuery + Webpack + ES6.

learning-spring-boot-2nd-edition-mockIf you haven’t caught my drift, this is why I elected to yank most of the JavaScript code from Learning Spring Boot – 2nd Edition. I had plunked down quite a bit into the 1st edition, and too many people found it distracting. I’d be happy to yak about JavaScript at a conference, but most people aren’t interested in that.

At the end of the day, I find JavaScript cute and fun. I like building frontends using React.js. But if I had to make it my full time job, I’d probably go nuts. It’s that freaking crazy.

Happy coding!

i-love-javascript

In defense of leftpad

Given the time I’ve had to think about the whole leftpad controversy, I have to come to the conclusion that leftpad was PERFECTLY FINE with its decision to build a module with only eleven lines. (As to the brooha over unpublishing and then being forcibly republished by npm, that is a different topic.)

leftpad wrote code anyone with half a brain should be able to write

laptop_chimpThat must be the biggest sentiment I’ve heard. Blogs, podcasts, and other forums have thrown out this strong criticism of leftpad’s code. It’s best summarized as “have people forgotten how to code?”

Gee, leftpad getting unpublished broke React.js, Babel.js, and how many other systems? If those impressive projects saw value in leftpad, sounds pretty big of me to judge them all for making such a foolish decision. After all, that’s what I’m doing, right? I’m ascribing judgment for using it.

Let me be clear: I haven’t actually READ leftpad’s code. I’m not defending the physical lines of code in that module. The market spoke and accepted leftpad. I am defending the choice others made because I myself haven’t invested the time to make a better choice.

leftpad wasn’t REALLY used by React.js, etc. It was just a transitive dependency

2001This one doesn’t sit right. It’s kind of like saying, “React.js is good. The people writing it would never need something like leftpad. They just got caught by some intermediate dependency.” Can you smell the disdain?

If leftpad was used by an intermedia dependency, and that is what all the big weights used, then the transitive property applies. Not only has the market said leftpad met needs, but the intermediate dependencies are just as valuable. See what I did there? Transitive dependency, transitive value.

leftpad isn’t actually the best way to do what it did

Kaypro_in_Israel_1984Here is where it gets interesting. This is what I hear from those that have spotted the transitive link. Can’t criticize React.js, because they didn’t REALLY use leftpad. Let’s look elsewhere.

People have been singing the UNIX tune of “do one thing and do it well” as microservices arise. Defenders of leftpad point it out as a composable function, adhering to the UNIX philosophy. But if you can tear out “do it well”, then leftpad doesn’t qualify for this concept. Hence, leftpad was a badly written composable function.

Sorry, maties, but as software engineers, we seek out solutions on a daily basis. And in the land of open source, we constantly make “build or buy” decisions. Whenever someone asked me, “what is an engineer”, my answer has always been, “we find a good enough solution for the problem at hand.” We don’t seek perfect answers, because we don’t have an infinite budget.

For a LOT of people, leftpad was good enough. They could have written a better solution, but they could also have written a better solution for LOTS of other modules. Imagine the cost of perfecting every single thing you use. Or how about this: imagine the cost of tens of thousands of developers writing an equivalent to leftpad. Perhaps 15 minutes tops, but multiplied by 10,000 and your talking 2500 hours of effort. Doesn’t that defy the concept of open source?

What’s next?

imageI know people that don’t like certain tools out there. They have written their own version of things. At first glance, there’s underscore and lodash. These two libraries essentially do the same thing. But one project was not satisfied with the other project. Hence, they built a fork and whole community around it.

These are people I respect, because they took the time to evaluate the current state of affairs and write their own solution. When I go pick from one of these two solutions, I can find out the basis of one or the others. Has the bulk of the JavaScript community picked one of the other? Or is it a big split? These are factors in choosing.

I can spend all my time building everything from scratch and live under the haughty label “I know how to program. I’ll build it myself.” But we already have a term for developers like that: “Not Invented Here“. Some people will only touch code they themselves wrote.

If you actually spent the time to read leftpad’s code, then used it or decided otherwise, that’s fine. But don’t go around criticizing others for using leftpad. After all, you’re criticizing the choices of MANY others.

Trying to write #JavaScript without Promises? TL;DR Don’t! Using @cujojs when.js instead

danielskullIt’s weird, but I dodged a lot of the web development churn that happened in the late 90s, early 2000 era due to my involvement in thick client, closed source work. Basically, I never worked with JavaScript in the early days. And back then, when I would peek at the source of a website, the stuff I saw was cryptic and appeared unassailable.

Suffice it to say, in recent years, I have gotten real excited about JavaScript. For starters, I have enjoyed its function-oriented nature. If you can get past some of the really cryptic and hard to understand syntax decisions, and only adopt “the good parts”, it’s quite intriguing. I don’t think I could make it 100% my career, but learning more about JS has been quite interesting. And being dubbed “JavaScript Padawan” by some past colleagues was quite endearing.

But one thing I learned real fast was that JavaScript has some sneaky APIs. And by sneaky, I mean that here is async behavior at every turn. I was trying to fix a usage problem with my Spring Data REST demo app (shrink images way down before upload) when I found what clearly appeared to be an async issue. I thought I had found the answer, but Brian Cavalier quickly pointed out that my assumptions were mistaken, and spotted something I would never have realized.  “img.src = /*new image data*/” is an async operation.

Seeing that, I knew what to do. Wrap the subsequent operations in a when.promise, stuff the “return” statement inside a “resolve” operation, and THEN do the img.src assignment.

You see, the only way to really handle asynchronous operations is to embrace Promises, when.js is a killer library for that. It won’t drag in other stuff not needed like some of these universal toolkits. With a Promise-based approach, I have been able to easily build up my snap-a-pic-upload-to-the-server demonstration of Spring Data REST. It really makes things easy to read, and easy to maintain. The first rule about writing software is that you need to be able to come back six months later and understand what you wrote. By breaking up clearly async steps into tiny, chained promises, the results become obvious.

So if you are getting frustrated with JavaScript’s hidden async bits and pieces (after you start using === for equality checking), ask yourself, “Am I using Promises to manage this?”

Kaypro_in_Israel_1984

Gearing up for @SpringOne2GX. (It’s not too late to register!)

DSC05391This is a short week for US citizens, since this past Monday was Labor Day. Of course, while I took time off, it didn’t really save me from the fact that I still have a boat load of stuff to do before I fly off to Dallas this upcoming Sunday.

I look forward to seeing many colleagues face-to-face. It’s a great time of cameraderie. And it’s also one of the most heating times of the year when we want to get certain things released to the Spring community.

I’ve been working primarily on two teams this past year: Spring Data and the Allspark team. Primarily I have worked on Spring Data REST, a project that lets you export any Spring Data repo with powerful RESTful endpoints supported by hypermedia. I have also made significant contributions on converting all their reference docs to asciidoctor. (Stay tuned for more on that).

At the same time, I have been using my RESTful skills and knowledge to interact with the Allspark team. This group is focused on a mobile R&D. As people are becoming aware, not only is software consuming the world, but mobile is consuming the software world. With billions of mobile devices in circulation, many businesses deal with mobile traffic as a primary means for lots of customers.

spring-a-gram-catRESTful services are a key facet to developing mobile apps, so I have used Spring Data REST to bridge the gap between Spring Data and mobile interfaces by building a demo application. Roy Clarkson and I will be demonstrating it next week. The app is called Spring-a-Gram and has been developed to move as much development as possible off of the server and onto the client.

In our demo, I’ll show an iPhone mobile web app that can take pictures and upload them to a backend database. Then it will let you tweet links to all your friends. Roy will demo an Android app that does similar things. All the while, it showcases the power of Spring Data REST and hypermedia.

My goal that I am trying to accomplish this week is to get the latest Spring Data GA release into my demo so I can show of the new ALPS metadata. This will be a signature achievement, because it will remove the need for a client developer to actually peek at the apps domain model. Instead, one can interrogate the RESTful service purely with a tool like curl and figure out how to a interact with the backend.

At the same time, I’m polishing up the getting started guides so that readers can skip over the build steps and jump right to the content. The process of putting such dynamic features into an asciidoctor-based guide was quite enlightening. I wrote JavaScript, CSS, and HTML and learned a lot of really fascinating things. I just can’t wait to gather with my colleagues and have a toast to this past year’s work!

If you happen to be coming (it’s not too late to register!!!!), send me a tweet or a message on this blog site. I’m trying to gather notes on all the people I plan to link up with. (In the meantime, I’ve told my editor for Learning Spring Boot that I’m basically unavailable to work on rewrites for the next two weeks.)

Happing coding!

Having a ton of fun with Spring Data REST + Javascript

Today has been 100% fun coding with Spring Data #REST, javascript, and pics of cats. 🙂 —https://twitter.com/gregturn/status/448219842056052736

Since last fall, I have shifted to working full time on Spring Data REST. This is an amazing project. It takes Spring HATEOAS & Spring Data and combines them together. This way, your Spring Data repositories are exported with an automatically generated hypermedia interface.

What does this mean? Maybe it’s not obvious, but data stored in a persistent repository is now available to desktop web apps, smart phone hybrid apps (those that basically wrap a browser), and native iOS/Android apps.

I’ve spent several months getting up to speed on this project by fixing bugs, adding new features, and adding to the test suite. This has slowly but surely helped me understand how it works. I don’t have it all down, but when we reached 2.0.0.GA, and had the basic CRUD functionality working, I proceeded to write a handful of getting started guides. This way, other people could quickly see through simple examples how to add a hypermedia interface to their existing Spring Data-powered apps.

But for at least six months, I’ve had a vision for where I could take this project. I finally felt I had enough know how to start working on a sample application that would heavily use this hypermedia + some javascript to build a dynamic web app. (NOTE: There are pictures of cats!) That’s what I’ve been working on for the past couple weeks.

Thankfully, we have some super sharp javascript coders on our team. I’ve been able to get solid feedback on my newbie javascript code. And it’s been fun! Javascript has a neat, function-oriented perspective. Instead of focusing on classes, i.e. nouns, I have been writing in terms of verbs. When you click this, do that, then that. It’s a big shift. But I ran into familiar territory when I needed to splice some data together. One of my javascript colleagues told me about reduce(), and when I read about it, I recognized it was the same as foldLeft.

Ultimately, I didn’t use it, because it didn’t fit what I needed, but nonetheless, it was nice to run into javascript’s nice functional APIs.

I have been having an extra dose of fun this past week. My colleague commented, “hey @Greg. looks like you’re having a ton of fun! :)” That was the truth! I just didn’t realize it was so obvious.

I’ve always been a language junky. While I enjoy writing Java full time and am really good at it, I love the opportunity to write code in any language. (Okay maybe not COBOL, but I think you get the idea.)

Hopefully I’ll be able to offer a presentation at SpringOne on this exact topic. It’s not guaranteed, but I’ll see if I can get a talk approved. Now…back to coding javascript!

Please don’t build your website with heavy-handed Javascript

Last night my family and I traveled down to St. Cloud, Florida, where we have a nice little town home. Unfortunately, we forgot to put our Sunpass back in the vehicle after loaning it to some family members. This device lets us fly through toll booths without stopping because it automatically makes payments for us. We stopped at a gas station on the Florida Turnpike and bought a Sunpass transponder preloaded with $20.

This afternoon I got online to register it so it would automatically replenish when it dipped down to a certain level, only to be foiled by a horrendous website. I ended up closing my laptop and calling the 1-800 service number.

The website LOOKED nice, but each field was trying to HELP ME. When I would enter my phone number in typical area code/prefix/last 4 digits style, it was setup to automatically tab to the next field when the last digit was entered. Coupling that with my inbuilt habit of hitting the tab key caused me to end up on the wrong field. DON’T HELP ME LIKE THAT! Most websites require uses to either click on the next field, or use the tab key, so why must you hinder me by going against the established norm. Instead, effort would have been much better spent by making sure the tab keys cycled through the proper order of fields.

Part of the registration process includes filling in your name and home address. I entered the street address then hit tab, and thought I was on the state field. I was already using the DOWN arrow key to go through the list, when I realized that wasn’t it. Instead it was for the county. County? Who uses this for personal information? Well, I scanned the list, only to discover it was Florida counties. At the top was “Out of State”. The city/state/zip code field were on the second column, in a non-standard location. PUT YOUR FIELDS IN PRACTICAL LOCATIONS. Address are entered by street address (1 and 2 for apartments), city, state, and zip code. Special stuff like county can come after that. Do this, and your users won’t love you, but at least they won’t hate you for showing your lack of user experience skills.

Another screen required me to enter the serial number of the transponder, and then confirm it. That was a pretty common thing I see. I entered the values, but somehow the second field kept moving the cursor around. I was trying to type a complicated, lengthy number, so I was looking at the keyboard, not the screen. I would like up and see the numbers being entered in the middle, between the first and last digits. Huh? Had I tapped the mouse or something? I started to empty the field and start over, when it seemed to happen repeatedly. Something was screwy, because the MacBook Pro requires a physical ‘click’ of the trackpad, not just a sensory touch like my wife’s netbook. I couldn’t figure it out, but somehow, I think it was trying to help me with yet more heavy-handed Javascript code.

I have seen other websites that do this. The developers on this web page seemed to want to show off their Javascript skills, and frankly, it made them look like amateurs. Go look at something else, like Zimbra, which is really Javascript intense, but doesn’t feel so heavy handed. I used TurboTax web a few years ago when I switched to Linux and couldn’t run the desktop app. It worked…but I could feel the heavy handed Javascript. I guess they were really making sure the data you entered was valid and no pure garbage so you could get your taxes done right. But it had a heavy feeling that was a little distracting. I haven’t used the site for years, but I hope they left that behind.

Go visit something like GMail. They have tons of Javascript in there. When my network connection is off, I can still leave through emails that I already loaded into the browser. And there is the crux of it. GMail works like you think that it should and DOESN’T feel like a web app. The app itself stays out of your way and instead focuses on putting data in your hands. You don’t notice the magic of Javascript running to handle things like keyboard shortcuts. You can write sophisticated Javascript for your site. Just don’t make it heavy handed.