refactor: use StringBuilder in RSS generation

- Replaced string concatenation with StringBuilder for efficiency.
- Moved DateTimeFormatter to a static final field to improve reusability and readability.
- Improved structure and readability of RSS generation logic.

Signed-off-by: Minecon724 <git@m724.eu>
This commit is contained in:
Minecon724 2025-02-08 16:00:44 +01:00
parent 0a6d8c09c5
commit e89252bb71
Signed by: Minecon724
GPG key ID: 3CCC4D267742C8E8

View file

@ -4,6 +4,8 @@ import java.time.format.DateTimeFormatter;
import java.util.List; import java.util.List;
public class Feed { public class Feed {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz");
/** /**
* Generates an RSS feed XML string for a given website and its list of blog posts. * Generates an RSS feed XML string for a given website and its list of blog posts.
* *
@ -12,16 +14,22 @@ public class Feed {
* @return a {@code String} containing the formatted RSS feed in XML * @return a {@code String} containing the formatted RSS feed in XML
*/ */
public static String generateRss(Site site, List<Post> posts) { public static String generateRss(Site site, List<Post> posts) {
var content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><rss version=\"2.0\">"; var content = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
content += "<channel><title>%s</title><link>%s</link>".formatted(site.name(), site.baseUrl()); content.append("<rss version=\"2.0\"><channel>");
content.append("<title>%s</title>".formatted(site.name()));
content.append("<link>%s</link>".formatted(site.baseUrl()));
var formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz");
for (var post : posts) { for (var post : posts) {
content += "<item><title>%s</title><link>%s/post/%s.html</link><description>%s</description><pubDate>%s</pubDate></item>".formatted(post.title(), site.baseUrl(), post.slug(), post.summary(), post.createdAt().format(formatter)); content.append("<item>");
content.append("<title>%s</title>".formatted(post.title()));
content.append("<link>%s/post/%s.html</link>".formatted(site.baseUrl(), post.slug()));
content.append("<description>%s</description>".formatted(post.summary()));
content.append("<pubDate>%s</pubDate>".formatted(post.createdAt().format(formatter)));
content.append("</item>");
} }
content += "</channel></rss>"; content.append("</channel></rss>");
return content; return content.toString();
} }
} }