Chris Padilla/Blog
My passion project! Posts spanning music, art, software, books, and more
You can follow by Newsletter or RSS! (What's RSS?) Full archive here.
- The Controller layer is responsible for connecting our data from the service layer with a means of rendering or presentation.
- The Model layer handles communication between our application and external database.
- The Repositories layer is responsible for querying logic to our database. If the model layer is establishing communication with the database, then the repositories layer is handling what type of requests we're making available to our application.
- The Service layer handles all the business logic for our application. This layer relies on the repositories layer to provide the data so that it then can be transformed in whatever way we need it to be before delivery.
Two Years of Blogging
From Austin Kleon:
The way I show up for myself, the way I discover who I really am, is to make an appointment every day to show up to the page. If I show up to the page, I show up to myself.
Two years of blogging! A small part of many years of creating and making, and it's certainly worth marking the occasion.
Last year I shared my Lessons From a Year of Blogging. I'd largely echo those points this year. I still enjoy the clarity of thought that comes from writing and making, the ability to carry a long term conversation while leaving a trail, and having a stage to perform on.
One other thing I've come to appreciate with blogging as a medium is this:
It's Malleable
I took a moment to look back at what I've made this year. For context: This started largely as a text blog, mostly developer logs. Out of the soil, buds of more literary posts on what I was reading began to sprout. Soon after that, I started sharing art and music.
I've since traded words for color and sound! Lately I only write for my tech posts. And the switch is intentional — I want to get more miles out of music and drawing, and there are only so many hours in the day.
When I started, a was wringing my hands trying to decide what one thing I would blog about. What a relief that it doesn't have to be one niche!
What I admire in the blogs I read is the spectrum of humanity that shines through. There's no predefined formula, and no algorithm to juice if you don't want to. So I end up seeing people as polyhedrons through the diversity they share and make.
On top of that, tomorrow I could decide that I'm all in on fly fishing. There's no barrier to me making this blog all about that for a couple of years. And I would revel in being able to look back fondly on the different phases and eras.
Starting out, I was worried about the idea that, if no one read what I wrote, I'd be doing all this for nothing. Turns out the rewards that come from a creative act alone absolutely eclipse any hit to the ego I would take if a post gets overlooked!
Elizabeth Gilbert in Big Magic:
You might end up dancing with royalty. Or you might just end up having to dance alone in the corner of the castle with your big, ungainly red foam claws waving in the empty air. that's fine, too. Sometimes it's like that. What you absolutely must not do is turn around and walk out. Otherwise, you will miss the party, and that would be a pity, because - please believe me - we did not come all this great distance, and make all this great effort, only to miss the party at the last moment.
And, of course, even if my inbox doesn't get flooded with mail on the eureka moment someone had reading a tech blog post, writing publicly is still a phenomenal tool for clarifying thinking in that craft.
I'm thinking much about the question offered through James Hollis' work: "What is seeking expression through me?" The wonderful thing about a personal blog is an opportunity to flexibly celebrate that expression.
The generous part of that showing up is that, by doing so, we then bring our fullest selves to the people we serve.
So start with where ever you are! Bring all parts of yourself along for the ride. You may find, as I have, it's an excellent way to explore the answers to that question.
Layers in a Java Spring Boot API
Spring Boot is a well embraced and powerful framework for developing web applications. Getting a backend API setup is fairly quick and allows for a great deal of durability up front. A fine balance between moving quickly on an app while giving you the guard rails to maintain organization, scalability, and durability.
Here's the quick-start guide to getting an API setup:
Layers
If you're used to the MVC pattern in software development, you'll find a similar intent of organization around Spring Boot Architecture. However, the categories we group our logic in will be slightly different.
In Spring Boot, these categories are referred to as layers of the application. They have their own directories and are bundled in their own package within the application.
Here's a simple directory structure within the src
folder of our app:
project/src/main/java/com/projectname
|-- controller
| |-- ArtistController.java
|-- model
| |-- Artist.java
|-- repositories
| |-- ArtistRepository.java
+-- service
|-- ArtistService.java
Note that tests will live in their own directory outside of the src
folder.
Above, all layers are represented:
In Action
Ok! So say that I have my base app setup for a Spotify Popularity Monitor API. From here, I want to setup a feature for each layer that supports CRUD operations for an Artist
.
I'll start with the model:
Model
package com.chrispadilla.spotifyperformancemonitor.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Artist {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column
private String name;
@Column
private String[] genres;
@Column
private String spotifyId;
@Column
private String spotifyUrl;
// Getters/Setters here
}
For brevity, I'm leaving out the Getters and Setters. What I'm showing is the schema for an Artist as I want it setup in my relational DB.
By adding @Entity
, I'm denoting this as a persistence layer class for the JPA.
Next, I'll add the repository:
Repository
package com.chrispadilla.spotifyperformancemonitor.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.chrispadilla.spotifyperformancemonitor.model.Artist;
@Repository
public interface ArtistRepository extends CrudRepository<Artist, Long>{
Artist findByName(String name);
Artist findBySpotifyId(String spotifyId);
}
Fairly simple! Spring Repositories already come with several CRUD methods. I enable them by extending from CrudRepository
. By default, I'll be able to call findById
, but if I want to query by another field, I specify it on the interface with a method. I've done this with findByName
and findBySpotifyId
above. Spring will automatically make the connection that if I'm passing in a variable spotifyId
, that this is what I'm querying by on the model. No extra logic required!
Service
The service layer will largely depend on what I'm trying to do with the data. It goes beyond the scope of today's blog, so here's the bare bones setup for a service class:
package com.chrispadilla.spotifyperformancemonitor.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chrispadilla.spotifyperformancemonitor.model.Artist;
@Service
public class ArtistService implements IArtistService {
@Autowired
private ArtistRepository artistRepository;
public void collectArtist(String spotifyId) {
// Do your stuff
}
}
It's good practice to create an interface outlining the methods you'll implement, so here I'm extending from an IArtistService
instance above.
Again, an annotation of @Service
marks this as a bean that can be injected throughout my other layers.
Controller
It all comes together in the controller! Here I'll setup a controller to GET and POST artists:
package com.chrispadilla.spotifyperformancemonitor.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.chrispadilla.spotifyperformancemonitor.model.Artist;
import com.chrispadilla.spotifyperformancemonitor.repositories.ArtistRepository;
import com.chrispadilla.spotifyperformancemonitor.service.ArtistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@RestController
@RequestMapping("/api/artist")
public class ArtistController {
@Autowired
private ArtistRepository artistRepository;
@Autowired
private ArtistService artistService;
@GetMapping
@ResponseStatus(HttpStatus.OK)
public Iterable<Artist> getArtists() {
return artistRepository.findAll();
}
@GetMapping("/{id}")
public Artist getArtist(@PathVariable Long id) {
Artist artist = artistRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No matching ID"));
return artist;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Artist postArtist(@RequestBody Artist artist) {
return artistRepository.save(artist);
}
}
Several nice annotations are made available here! RequestMapping
, GetMapping
, and PostMapping
allow us to define the path for our controller. PathVariable
gives access to the id
that's listed as part of my path in my get request.
Here, you'll see I'm using Autowired
to tell Spring to inject an instance of my repository and service layer classes created above. I can then use them freely within my controller.
It can be tempting to write the business logic directly in the controller. To maintain flexibility, though, it's best to leave minimal db logic in the controller and wrap up data transformation within a method on your service layer classes. This allows for a more highly decoupled system. Were I to add a Presentation layer, it would be far simpler to access the service layer object, as opposed to refactoring a bloated controller method.
That's It!
With just a few files written, we have a strong basis for a flexible and easily extendable API! All with type checking along the way and a largely decoupled system! 👏
Minako Adachi — Iki Town from Pokemon Sun & Moon
Summer is coming! Only felt appropriate to play some Pokemon island music 🏝
Duck Fam
Polymorphism in Java
Of the core pillars of Object Oriented Programming, Polymorphism affords a great deal of flexibility. While inheritance allows for encapsulated and abstracted data to be shared, polymorphism allows for the redefining of both the data and the attached methods based on context.
Java supports polymorphic behavior through two means: Method Overloading and Method Overriding.
Demonstration
Say that I have an ArchiveItem
class that stores the basic details of a name and id. Here I'll demonstrate both overloading and overriding:
package polymorphism;
public class ArchiveItem {
private String id;
private String name;
// Overloaded constructor with all instance variables supplied
public ArchiveItem(String id, String name) {
this.id = id;
this.name = name;
}
// alternative constructor with only the name provided
public ArchiveItem(String name) {
this.name = name;
this.id = IDPackage.generate();
}
// Override the base equals() method
@Override
public boolean equals(Object compared) {
if (compared == this) return true;
if (!(compared instanceof ArchiveItem)) return false;
ArchiveItem comparedItem = (ArchiveItem) compared;
return this.id.equals(comparedItem.id);
}
// Override the base toString() method
@Override
public String toString() {
return String.format("%s: %s", this.id, this.name);
}
}
Taking a look at my constructors, I'm overloading the ArchiveItem
method by declaring the same method, but with a different number of arguments both times. When instantiated, Java will know which of the two methods to run based on what arguments are provided. Another way of putting it: One of the two methods will be called depending on their signature.
Looking further down, I've written an equals
and a toString
method. All Objects in Java come with these methods. Every class inherits from the base Java Object class, and on that class are implementations for equals
and toString
. In fact, toString
is what's called anytime you print an object to the console.
Without any adjustments, passing an object to System.out.println()
would return something like this:
ArchiveItem guitar = new ArchiveItem("Guitar");
System.out.print(guitar);
// "polymorphism.ArchiveItem@28d93b30"
The base print method will print the classname to the left of the @
symbol and the location in memory to the right. Typically, we want something more descriptive representing our class instance.
In the example above, I'm pringint instead the provided id and name of the ArchiveItem
By adding the @Override
annotation, I'm declaring that I'm intending to implement my own logic for the already inherited toString
method. The @Override
annotation is actually not necessary, but recommended. This will flag to the compiler to check that you're in fact overriding an existing method. Great for catching typos!
Putting It All Together
ArchiveItem piano = new ArchiveItem("Piano");
System.out.print(piano);
// "Piano, 93nkf903f"
Here it is in action! The ArchiveItem
is instantiated with only one argument, so it calls the matching method. One line down, I'm calling my implementation of toString
by passing my piano object into the print method.
Here is the same class but with a different constructor signature:
ArchiveItem piano = new ArchiveItem("custom-id", "Piano");
System.out.print(piano);
// "Piano, custom-id"