The myth of polymorphism

I remember reading about polymorphism for the first time. I was in high school, and boy it sure looked cool! Too bad I didn’t realize that the myth of polymorphism was a bunch of poppy cock.

You see, polymorphism never seems to be presented in its real state. Instead, we get this goofy, toy-app type presentation. Does Shape -> Rectangle -> Square ring a bell?

The fallacy of geometrical shapes being polymorphic

One of the simplest ways people seem to introduce polymorphism is using geometric shapes. We all know that a Square is a Rectangle. We covered that nicely in geometry, right? Problem is, geometry doesn’t equal software.

When discussing things in light of geometry, the reason we value this relationship is because we are looking at things like angles, parallelism, vertices, and intersections. Hence, squares carry all the attributes of rectangles. They simply have the same width and height.

But software isn’t geometry. The things we construct we must also interact with. The shapes must afford us operations to grab them, interrogate them, draw them, and manipulate them. A rectangle has two attributes: width and height. A square has one: width.

If we grabbed a square, set its width, then set its height, the assumptions of what would happen is unclear. Should a square morph into a rectangle? Or should setting the height induce the side effect of also updating the width? Either way is bad form. Hence, its best to break apart this faulty geometric relationship and realize that squares are NOT rectangles.

The fallacy of inheriting behavior

So shaking off the trivial example of geometric shapes, another common example is to talk about the glorious ability to reuse code. With polymorphism, it will be SO easy to code something once, and then reuse it across dozens if not hundreds of classes! And with late binding options, gobs of 3rd party libraries can go forth and reuse your code.

The problem is, no programming language has adequately been invented to gather ALL the semantic nuances of code. As more and more classes extend a given class, they all either realize EXACTLY what the abstract parent class does and agree with it, or they discover some new wrinkle not quite handled. The API may be supported, but some underlying assumption is buried that requires an update.

As the tail of inheritance grows, maintainers are less likely to accept new changes to the shared code. The risk of breaking someone else grows, because everyone knows not the ENTIRE nature of the code can be captured.

Some of the avenues to remedy this involves opening up the API a bit more. Perhaps a private utility method is needed by a new extender. But opening it up introduces more maintenance down the road. Or more opportunities for others to abuse things that used to be kept tightly controlled.

History has proven that composition beats inheritance for sustainability. Raise your hand if maintenance, not new development, doesn’t encompass much of your work.

The alternative are more sophisticated languages where you can capture more of the concepts. Yet these languages come across as too complex to many, arguably because CAPTURING all semantics is inherently challenging. And more often than not, we don’t KNOW all these semantics on the first round.

The myth of polymorphism vs. the reality

One thing that has emerged is programming to interfaces. Interfaces provide a nice contract to work against. Naturally, we can’t capture everything. But at least every “Shape” can  institute the defined methods. In Java, interfaces can be combined, allowing multiple behaviors to be pulled together.

So when it comes to abstract and refactor, think about extracting interfaces when possible and delegating solutions.

Strangely enough, despite my consternation with static variables, I’ve come to appreciate static methods in the right scenario. Factories that support interfaces can be quite handy dandy. But a well modeled, inheritance hierarchy is to hard to accomplish. If possible, try to avoid multiple layers, and see if it’s not possible to extract share code into various utility classes.

And when the entire hierarchy is nicely contained INSIDE your framework, and not as an extension point to consumers, the fallacies of polymorphism can be contained. But watch out! It takes much effort to put this together. Never think it will be easy.

Of course, I could be entirely wrong. If you have some keen examples, please feel free to share!

Happy coding.

Why take a break?

Good developers take breaks. But why? Last night, I attended a men’s session where two very different people talked on stage about very different breaks. The first was a pastor who was granted a six month sabbatical. The second was someone that was fired, and instead of lunging for the next job, spent time evaluating things carefully. As I listened, it made me reflect upon my own discoveries about taking breaks.

Why do we need breaks?

To be honest, it’s quite easy to burn yourself out. Maybe when you’re a bit wet behind the ears and single, not so much. I once worked extensive hours (despite not getting paid overtime), and I don’t regret that.

But today I can’t do the same thing. I have three kids and many other responsibilities that preclude me from working ALL THE TIME. Well, a big difference between now and then, is that back then, I needed a lot of “tinkering” to figure things out. I was short on experience, but long on drive. And working extra hours helped me learn a lot of valuable lessons.

Today, the valuable lessons are taking breaks, and letting my subconscious continue chugging away. Even today, I’m working on a major review/refactor/rebase task that has already cost me two weeks and will probably cost a couple more. Yet I don’t dread this effort. In fact, I’m not trying to rush it. Because the hours I’m away from my laptop (like now), my mind is still noodling things out. And when my fingers rejoin the keyboard, I feel like my knowledge of this branch is growing at a comfortable pace. If I tried burning ten hours a day, I’d burn out and torch it all.

But by letting my family pull me away, and focus on other important things, I am stopped from burning out. And I can avoid spinning my wheels in the mud of frustration. In the past five years, I feel as if my productivity has actually increased, because I am working smarter not harder.

What good do breaks do?

Let’s just jump right in and state something critical – your work isn’t everything. When you pass from this world, people are less likely to remember the code you wrote, and instead remember the impact you made on your children, your spouse, and your community.

I remember a graphic that came out of Microsoft showing how you could access every aspect of your job from everywhere – a kids soccer game, waiting for an appointment, during breakfast, etc. 37Signals released a mocked up variant with the same style, only they dubbed it Work Can Wait (which you can see linked her). The thing basically stresses the importance of having a life.

But in addition to balancing work and life, I’ve discovered that my work actually flourishes when I get away from it. I once sat in on a talk by Dr. Venkat Subramaniam, who described that classic software eureka moment of realizing the answer to your problem you battled all day. The next morning, in the shower. I’ve experienced that a fair number of times, moreso since I started taking more breaks.

I enjoy, on occasion, merging a Github pull request after hours. But I don’t go out of my way to do that. It’s usually something small, like a typo in a guide. I enjoy being able to shuffle that off my plate in a bit of idleness. But pulling myself AWAY from the keyboard sometimes forces my mind to assess what just happened, and what’s coming next. Seeing that I have less time to spend, my brain hammers out certain details to make better usage of our next keyboard session. And I sincerely believe I code with higher quality because of this.

Try it. You might be surprised.

I’ll close by sharing a reflection I received from Mark Fisher, founding member of the Spring team. He once mentioned that if he had been forced to work nose to the grindstone, and hadn’t taken all the various walks, and simple “think about it” moments, Spring Integration may never have happened. Not everything is a burn-baby-burn coding moment.

Happy coding!

Fun @SpringData team meeting in Deutschland, storified from a bunch of tweets

I had a great team meeting last with my five other co-workers. I wanted to share the majority of it purely in tweets, with a couple comments thrown in here and there. Enjoy!

As my cohorts arrive by other means:

And this draws concern from some!

https://twitter.com/Hameiste/status/849263376375140352

https://twitter.com/olivergierke/status/849490414835044352

https://twitter.com/olivergierke/status/849611590047604737

https://twitter.com/olivergierke/status/849868582901121024

https://twitter.com/olivergierke/status/849933811374796801

That evening, we trekked over to the Berlin-Brandenburg JUG meeting where Christoph and Mark talked about Reactive Spring Data, and I managed to give away a copy of Learning Spring Boot:

Finally glomming onto the fact that Germany dubs the “ground floor” as the 0 floor, I really appreciated being able to do pointer arithmetic based on my floor number!

A nice little event in the midst of our team meeting:

https://twitter.com/olivergierke/status/850226668232781824

https://twitter.com/gregturn/status/850813991030898688

https://twitter.com/gregturn/status/851059503944540160

https://twitter.com/gregturn/status/851190002872717312

And for those of you asking, no I have yet to discover the location of my luggage. ¯\_(ツ)_/¯

UPDATE: The airline found my bag and returned it yesterday. Eventual consistency! 😄👏

Guten Tag Deutschland. Ich bin da!

I just arrived in Germany for our big Spring Data summit. Our team is having a get  together to do some planning and scoping of work for the next year. And I couldn’t be more excited.

I arrived at 7:00 am local time, and waited two and half hours to discover the airline had lost my bag. But pay it no mind. I packed the critical in my carry on so with paperwork filed, it’s no sweat. The fun part (so far) was having the leverage my German to interact with my taxi driver, who spoke hardly any English.

Something i was able to contemplate while traveling, is that one of the biggest things I missed while working on Spinnaker was the jürgenized code base of Spring. The clean, elegant nature of all the portfolio projects really gives me a warm fuzzy.

Its hard to explain if you haven’t seen clean code before. But having a strongly enforced clean, consistent coding policy eases the mind. When we write code, we need to understand it. Sifting through inconsistent spacing, sloppy names, tabs AND spaces, and other aspects of code slows down the brain, making it hard to digest the functional aspects.

My father-in-law once shared that driving while it’s raining tires you out faster. He once had to drive at night through a lot of rain and it wore him out. The same can be said for sifting through sloppy, inconsistent code.

So this week I celebrate being back amongst my Spring Data mateys as he continue hammering out what has to be one of my favorite umbrella projects. Applying the concepts of the Spring programming model to Data management.

Cheers!

API evolvability is key in a system of systems

Heh. That tweet was a follow up to Oliver’s latest presentation on the topic “API evolvability is key in the system of systems”. So what does this stuff mean, and why is it important?

API evolvability is one of the core underpinnings we get when we use the constraints laid out in Roy Fielding’s dissertation. And what is that exactly? In essence, the web grew FAST and is a major success. Many of the reasons are that is constrains us in certain ways, thus forcing certain things forward. Web sites are easy to evolve WITHOUT evolving the web browser. The value of this cannot be stated enough.

For decades, developers have faced the issue of evolving APIs. The concept of REST is take some of the underpinnings of the web and take them into API-land. Evolving APIs with similar constraints should make it possible to scale such changes and avoid some of the brittle, backwards-compatible breaks we have suffered for years, which can lead to slow downs in evolution.

How does this tie in with Spring?

I recently moved back to the Spring Data team. I had been on that team before, working on Spring Data REST. A key library that supports it is Spring HATEOAS. In Spring HATEOAS, we have an API meant to build hypermedia-powered RESTful APIs. And due to the incredible popularity of ALL Spring Data projects, Spring HATEOAS hasn’t received enough love.

No more!

Since jumping on this fab team, I have started putting together a list of proposed updates, enhancements, and polishings. Next week, I’ll be in Germany with the rest of the Spring Data team having a coordinated meeting. Among the many topics, Oliver and I will be hammering out this plan to propel Spring HATEOAS forward to be benefit of the community as well as the Spring Data REST community.

And one thing that Oliver has invested much time in speaking at various conferences about DDD, REST, and API evolvability. I have a strong desire to create some sort of code repository, a playground if you will, where people can checkout things and see how to evolve an RESTful API using Spring HATEOAS and the concepts of REST.

That way, we aren’t just preaching a high falutin’ concept, but showing how it can be done.

And I also imagine that in putting together such a repository, we can also find the gaps and holes in Spring HATEOAS. I suppose it’s risky putting this all out in a blog post, but I just wanted to share some of the ideas floating around in my brain as we ramp up support for Spring HATEOAS.

Laptop on a work table with DIY and construction tools all around top view hobby and crafts concept

Learning Spring Boot 2nd Edition delayed – Find out how to get a FREE advanced copy

Having taken a week off after turning in the last chapter, I geared up and started reading the whole thing, top-to-bottom. Some bits were written before Spring Boot 2.0 was even available on Github, so there is much code that needs updating.

That’s when I got word from my published that due to Boot’s schedule, they are delaying the release. Didn’t say when. We haven’t hammered that out. But this makes me feel good. Encourages me to really polish things up and ensure I can get the right message out there.

In the meantime, I’m putting together my Launch Team.

  • get an advanced reader e-copy of my book
  • be a part of a secret Facebook page and get sneak peeks
  • learn more about my writing journey as it happens

Then the Turnquist Techies is for you!! I will send out FREE advanced reader e-copies to the members of my launch team. There will be a secret Facebook page and a private newsletter just for this team.

What do I ask?

I am encouraging the members of the team to participate in this journey with me by sharing their honest opinion in reviews, tweeting and posting about what they are reading, and the like. For the most part, being a part of the Turnquist Techies is about having fun, reading, connecting, and learning more about the technical writing process.

How do I sign up?

Just click on join The Turnquist Techies and fill out this form.

What do you do when you’re traveling to Germany in two weeks?

At Pivotal I work on the Spring Data team, and our fearless leader is having us all converge in Berlin in just two weeks.

Short of being über awesome, what do you do? Well, considering I’ve studied German off and on since high school, I thought it time to get back into my tools to freshen up my speaking.

For starters, need to use this cue card to remember when to say “bitte”! Heh, that’s a joke. You throw it out about every 3-4 sentences, because it means EVERYTHING.

Anki

But seriously, my favorite app is Anki. To call it a “flashcard app” is a gross understatement. This app uses “spaced repetition”, a concept going back at least to the 1930s from Professor C. A. Mace.

Spaced repetition takes a deck of cards, and as you answer each one, it polls you on whether you did/didn’t know it. Cards you knew are delayed as to when they show up again. Cards you didn’t are reviewed sooner.

There are all kinds of studies backing up the efficacy of such study techniques. In fact you can spend hundreds of dollars on language learning courses based on this. Or you can do what I did (cue dramatic music leading into next section.)

Duolingo

I learned of DuoLingo.com back in 2013, when one of my teammates started tweeting about learning Spanish. Digging in, I found a really cool website/iPhone app that had free, 5-minute lessons on many languages including German.

So I dug in!

It was nothing short of awesome. Each lesson is concentrated. I enjoyed how many verbs I could still conjugate even after being away from German for twenty years.

Then a major breakthrough – after learning of Anki, I discovered someone had built a deck out of DuoLingo and shared it with the community.

Slack + German

If that wasn’t enough, just this week someone launched a German JVM Slack group. Duh! Who wouldn’t sign up for that?

To wrap things up, I find myself roaming around doing chores or work, mumbling little phrases in German. I have written my high school German teacher. And I’ve heckled my teammates.

It’s going to be awesome!

 

 

 

How to write a tech book, or how I stopped worrying and learned to love writing

I just sent in the last chapter of Learning Spring Boot 2nd Edition’s 1st draft. And my brain has collapsed. I’ve been working for several months on this 10-chapter book that embraces Spring Boot 2.0 and reactive programming. There are several books out there on reactive programming, but I believe this will be the first to hit the market about Project Reactor.

I’m not done, not by a long shot. I told my publisher that we’d need at least one big round to make updates to ALL the code, because I started writing when not everything was in place. And it’s still true. But editing, polishing, and updating an existing repository of code and manuscript is easier than creating one out of thin air.

I wanted to write just a little bit about how I approaching writing something like this. Maybe you have been thinking about writing a book yourself, and your curious what goes on. This isn’t the only, but it’s the way that works for me.

Tools

Laptop on a work table with DIY and construction tools all around top view hobby and crafts concept

To write a book, you need a mechanism to capture prose and code. For fiction, I use Scrivener, but when it comes to technical writing, where the code, screenshots, and text are tightly integrated, I use Asciidoctor. With Asciidoctor, the overhead of a word processor is removed, and instead I can focus on pure content.

Also, using Asciidoctor lets me pull in the code to generate the manuscript sent in to my publisher. This way, I have Sublime Text in one window viewing the source prose and IntelliJ open in another viewing the source code. To top it off, I have a Ruby guardfile configure to constantly regenerate an HTML proof of the chapter I’m writing with it refreshing via LiveReload in my browser.

This combination gives me a quick feedback loop as I write.

What to write

This may be the biggest hurdle to some. When you’ve picked the technology, setup your tools, and finally have the editor opened up, what do you type in that black, blank screen?

Waiting for magical words to arrive? Or perhaps you hope elves will scurry in and leave something? Nope. This is where the rubber hits the proverbial road and you have to push yourself to start typing.

What do I do? I actually start earlier than that. From time to time, I have a crazy idea about something I want to show to an audience at a conference. Some demo I want to give with a few pieces of the Spring portfolio. I began to noodle out code to make that happen. Once, I asked “can I snap a picture of the audience and upload it from my phone to a webpage the audience is watching on the overhead?” Thus was born my Spring-a-Gram demo.

That demo has morphed many times to the point that I have built a full blown, cloud native, microservice-based system. And guess what. It’s the system we get to explore in Learning Spring Boot 2nd Edition.

So when I sit down to write a chapter, I first start writing the code I want to walk through. Once it’s humming inside my IDE, I start to typeset it in Asciidoctor. And pages of code fragments, I began to tell a story.

Weaving a story

When writing technical articles, getting started guides, and books, everything is still a story. Even if this isn’t a novel, it’s still a story. People that grant you the honor of reading your work want to be entertained. When it comes to tech work, they want the ooh’s and ahh’s. They want to walk away saying, “That was cool. I could use that right now.”

At least, that’s how I read things. So my goal when I write is to make it fun for me. If it’s fun for me, I trust it will be fun for others.

If I sift through a chapter, and it’s just a boring dump of code, then it’s sad. And that’s not what I want. I can’t promise that all my writing has upheld this lofty goal. But it’s my goal nonetheless.

So oftentimes, I will typeset the code, hand some descriptive details around the code, then read it again, top to bottom, and add extra stuff. Paragraphs talking about why we’re doing this. Mentioning tradeoffs. Issues that maybe exist today and where we have to make a choice. Ultimately, understand not just what the code does but why it does it this way. And what other options are out there.

Letting go

At some point, after all the writing and polishing and fine tuning, you have to turn in your work. I don’t know if there is ever a time where I’m 100% satisfied. I’m kind of picky. But the truth is – you’ll never find every typo, every bug.

My code fidelity is much higher ever since I started using Asciidoctor. But stuff happens. And you have to be happy turning in your work.

You see, if you’ve acquired enough skill to sit down a write a book without someone leaning over your shoulder and coaching you, you might have a lot of good value other developers seek. Eager coders will be able to read what you wrote, look past small mistakes, and most importantly, grok the points you make. That’s what is key.

And one thing is for certain – writing makes you better. I have found that any gaps in my own understanding of certain parts of code lead me to chase down and grasp those bits. And then I want to share them with others. Which is what writing books is all about.

Happy writing!

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.

HTTP + REST + OAuth = say what???

In the past couple of weeks, things have really gotten hopping on the Nashville Java community’s #java slack channel. A recent topic topic of interest is how do we take something like REST, which talks about clean URIs and stateless services, and stir in this crazy OAuth stuff?

I threw in my own $0.02 given I’ve done a bit of work on projects like Spring HATEOAS and Spring Data REST. And my $0.02 is this:

HTTP + REST + OAuth should work hunky dory without compromising any of these principles.

What does this even mean?

HTTP is a spec that goes back twenty years. Or should I say, HTTP is an amalgamation of specs that goes back that long. HTTP includes the request/response protocol, the verbs (GET, POST, etc.), the concept of media types, content negotiation, and more. At the heart of MANY of these specs is none other than Roy Fielding. Yes, the man that wrote his doctoral dissertation on REST had his fingers in a dozen specs that governs how the Internet operates.

REST is doctoral dissertation that was published in 2001. REST not a spec, not an API, not a standard. It’s an idea. An idea that if similar constraints that existed for the web plus a few others were adopted when building Internet-based services, then they too could enjoy the scalability and fault tolerance the web has come to enjoy.

OAuth is an 11-year-old security protocol driven by the explosion of 3rd party social media applications that were requiring users enter their credentials so the apps could log into social media networks on their behalf. It introduces a flow whereby the app, instead of gathering credentials, would take the user over to the source site, have them login there, be issued a token, and thereafter use the token in lieu of actual credentials.

All of these concepts have grown supreme in applications today. Enterprise shops want big apps to support millions of customers, and they want them yesterday. Hence the desire for scale.

We’re all aware of how the web was won the war of the UI. I remember coding Swing apps in data centers, and side stepping the growth of the web, but the web has beaten thick client apps hands down. The only REAL thick client app are the apps found on mobile devices. The standards of web apps is front and center.

EVERYONE wants OAuth. I’ve often stated “it isn’t real until it’s secured” indicating that frameworks without a security solution will get passed over by production shops. That’s because no customer will talk to you unless your solution can be secured. And with the rise of mobile apps and multiple clients talking to a backend, the need for OAuth is gigantic.

So how does this mishmash of ideas all fit together without tragic compromise? Let’s take things apart.

Fundamentals of REST

One of the most fundamental concepts behind REST is to include not just data in the payload, but links to resources from which you can DO SOMETHING with the payload. Or links to a state you can transition toward. For example, a Coffee Shop API that let’s you place orders should include a link to cancel the order WHEN IT’S POSSIBLE. By pushing the link to the human user, they can see when they can/can’t do that. Hence the rise of media types that support including links. For example, the JSON document below shows HAL, with both data and links.

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : {
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

That’s nice, but what do we do when this data needs to be wrapped with OAuth?

OAuth, as briefly stated, is a flow where the website redirects the client to a login page, potentially at a different site altogether. A token is issued, and then we go back to the original site. Now we have a token in hand.

This token nicely fits into an HTTP Authorization header like this:

Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42

If you’ll notice, I said header. HTTP headers don’t infringe upon payloads designed to support REST. HAL doesn’t have to know that the service is protected by OAuth + whatever other security protocols are layered on. Security, as they say, is orthogonal.

That’s because HTTP includes options to extend itself. HTTP has room for new media types (application/hal+json and application/hal+xml), new headers (Authorization), and new payloads.

And why shouldn’t we expect this? The man involved with designing the web also designed REST. Someone trying to take lessons learned from the web and apply them to APIs would surely work to fit it into the nature of the web.

To approach a secured service, I make the call, and if I get a 302 redirect to a login page, my client can come back to the human user and indicate that there is security required. At this stage, it would be completely normal to SHOW the human the login page. Let the user supply what’s needed, and my client should be able to harvest the token, and press on.

Should security be a part of the REST representation?

Yes and no. Security protocols aren’t required to be there. That would clutter up the nature of data and navigation. And clients shouldn’t be giving away any secrets, whether that is a bearer token or credentials.

But hypermedia links should be VERY sensitive to the nature of the client and serve different sets of links based on what the client is allowed to do. If the client will be declined attempting to perform a DELETE, then don’t show them the link to do it.

REST and stateless services

People like to regurgitate this REST-ism about “no state no state no state”. Yet when we get into the subject of security and the STATE of the user’s logged in nature, some people go nuts. Being stateless means that my next REST request should be able to get routed to any server on the backend. In a cloud native environment, there could be twenty copies right now, fifty five minutes from now, and two copies ten minutes after that.

The state of my next REST operation shouldn’t require I go back to the same server. If the server is feverishly trying to push session details around between gobs of servers, that is crazy. That’s why toolkits like Spring Session offer the option to use either cookies or headers. It’s possible to log into a system, get some form of session, offload the session state to a 3rd pary service, like Redis, and then bounce off of that using a header.

As Rob Winch states in the video below, a little bit of state is alright. When done like this, where you security state is managed properly in a data store and NOT on the server itself, you’ll do fine.

So wrap things up, serving up things over the web, securing them with modern practices, while also having scalable APIs should fit together nicely. Because the web was built for flexibility and extensibility, if we just embrace all of its paradigms.