About us
Services

Capabilities

Cloud
Legacy Modernization
Data Platforms
AI & Advanced Analytics
Agentic AI

Industries

Automotive
Finance
Manufacturing
Aviation
Looking for something else?

Contact us for tailored solutions and expert guidance.

Contact
Products

Cloudboostr

Platform

Sovereign AI

Sovereign Cloud

Virtualization

Implementation & support

Databoostr

Use cases

Data monetization

Data regulatory compliance

Fleet management

Industry

Manufacturing

Automotive

Material Handling

Aiboostr

Product

Products

Products

Databoostr

Data Sharing & Monetization Platform

Cloudboostr

Open Cloud Foundation for intelligent workloads

Aiboostr

AI Orchestration & Governance Platform

Use cases

Data monetization

Data regulatory compliance

Fleet management

Industry

Manufacturing

Automotive

Material Handling

Platform

Sovereign AI

Sovereign Cloud

Virtualization

Implementation & support

Product

AI Orchestration

Private AI

EU AI Act

Case studies
Resources

Resources

Blog

Read our blog and stay informed about the industry’s latest trends and technology.

Ready to find your breaking point?

Stay updated with our newsletter.

Subscribe

Insights

Ebooks

Explore our resources and learn about building modern software solutions from experts and practitioners.

Read more
Careers
Contact
Andrii Biehunov
Expert Software Engineer

Expert Software Engineer at Grape Up. His main area of expertise is the design and development of distributed software systems based on the cloud-native approach and microservices. Has experience in iOS mobile and macOS development. He also provides full support to clients at all stages of the solution design process, as well as development and deployment. In his free time, he likes to travel, he’s into photography and reading.

Blog

Read articles

AI
Software development

Spec-driven development: Scaling AI-assisted coding across microservices

Why AI coding agents struggle with multi-repository projects

Modern web applications almost always consist of multiple modules and services located in different components or repositories, including microservices, common code, configuration per environment, etc. When it comes to AI-assisted development with a  multi-component structure, it becomes harder for AI tools to properly understand the system and make changes efficiently and consistently when implementing entire features. From our experience with AI-assisted development, we identified several challenges that are the most impactful and important from our perspective.

5 Challenges of AI-Assisted Development in Large-Scale Systems

1. Maintaining AI Context Across Components and Repositories

A new feature implementation is usually spread across multiple services and repositories. This means that the agent context is “stretched” over multiple code bases. And since context size is limited, the agent may know well only some parts of the feature e.g. in micro service containing business logic, but miss important details about interfaces or functionality in other micro services the current one is communicating with.
The challenge here is to define feature in a way that, on one hand, accurately describes the desired functionality on level of the entire system and, on the other hand, provides as much details as needed for accurate tracking of interactions and dependencies between services.

2. Cross-Component and Cross-Repository Coordination

As implementation switches from one repository to another, we need to transfer the information about the required code changes between the agents or AI sessions. In the simplest case the information might be generated as prompt by one agent session and copied manually into the dedicated chat or session for the next repository. With more advanced approach, the coordinating agent might pass the information about what functionality should be implemented to another agent in Markdown or JSON format. However, the information passed to the agent often contains only the concrete functionality description. So, some important details might be missing on receiving agent’s side as it might need more context about the code it works on.

3. Inconsistent Feature Definitions for AI Agents

Regular prompts in a single AI agent chat session lack structure and repeatability. Each time the work on new feature is started, the way we describe the tasks for AI agent may differ. Some important details might be missing from the feature description, the high-level business requirements mixed with technical ones. This might cause more editing of same code to make it work properly, adding new requirements and constraints at different stags of feature development. One of two very similar features might require twice as much effort and reiteration as the other simply because initially some requirements were unclear or missing when put into prompt for AI agent. This effect is also amplified by nondeterministic nature of generative AI making it harder to achieve consistent level of feature implementation quality. So, the consistency in feature definition is important as makes implementation predictable and complete with minimum reiteration.

4. Implicit API Contracts and Hidden Coupling

The implicit API contracts are undocumented API properties defining what data the requests or responses might contain. For example, some field of response object may be missing from real JSON data under a particular condition. The service might work only because it’s not using that field under some implicit condition baked into business logic or basing on other field values, data from other endpoints, etc. Another example is AI agent incorrectly defining the default value for logically empty response data, like empty vs null value for strings, empty JSON object vs null, etc. In this case the API client assuming that, e.g., a particular object’s field should be null breaks when an empty object is returned instead after the code update.

5. Losing Knowledge as Software Evolves

The more system evolves the harder it becomes for AI to keep track of all the reasoning behind the changes made and how the features were implemented. We either need to continuously update the documentation describing feature details or manually provide a portion of that knowledge required by AI in prompt to understand how feature is integrated with other features or how the old feature should be extended as part of the prompt.

There are several AI-related tools and development approaches that help to resolve the challenges above. In this article we’ll focus on Spec-driven development methodology as currently it’s the most advanced tool almost fully addressing the described challenges.

What Is Spec-Driven Development (SDD)?

Spec-driven development (SDD) is an AI-assisted software development methodology in which the specification of each feature is defined before implementation, in a form optimized for AI understanding, allowing the AI to implement the feature code based on the spec.

What a Feature Specification Contains

Each feature specification defines:

-    High-level spec: user stories, business requirements, expected behavior, and acceptance criteria. This part should answer the “why” and “what” questions about the feature, but not “how”, which relates to the implementation details.

-    Technical-level spec: implementation plan, architecture, technologies, technical approach and constraints, system design details. This part should answer the “how” question about the feature implementation.

The spec should be written with the level of details, precision and descriptiveness sufficient for AI coding agents to consistently and reliably generate code based on it.

The Spec-Driven Development Workflow

In SDD the development workflow consists of several steps. Initially, during the setup, once per project, we create a file defining generic development principles, guidelines and constraints the coding AI agent will follow at every stage of development. After the setup, we can proceed with feature development. The common generic steps of SDD are shown in the diagram below:

‍

The files generated by the SDD workflow should be committed to the repository. As  the product evolves and features are added, new specifications are created. The set of all features specs describes the functionality of the whole application, capturing both business logic and implementation details.

SDD Tools and Repository Structure

In practice, SDD is introduced in a software project as an external application or tool built on top of existing well-known coding agents like Claude Code or Copilot. Such tools use agent skills or a different agent types for the SDD steps.

The generic example structure of typical SDD tool data is shown in the diagram below:

How spec-driven development solves AI-assisted development challenges

Let’s now take a look at how SDD helps to overcome, or at least mitigate, the challenges we identified earlier. We'll describe it in the context of the SDD workflow in general, independently of specific SDD-enabling tools or frameworks.

1. Keeping AI Context Consistent Across Repositories

The specification and plan determine the context boundaries. The AI agent uses them as a primary source for implementation. This enables precise collection of all the information needed to implement the feature without loading the entire system into the agent’s context.

From the practical point of view, to effectively maintain the context:

  • All the feature-related files: spec, plan and tasks should be kept in a separate repository that is accessible for every agent working on the project at any point of development. These files are a source of truth for the agents.
  • The feature spec created in the Specify step should define the feature on the system level only, without technical implementation details. The spec should be as clear as possible but also not too specific.
  • The plan files created in the Plan step are split into several parts, one per affected service. Reference the relevant existing code or docs instead of copying them.
  • Since the context is captured in spec and plan, at any point we may start a new AI chat session – one for the whole feature, per task or in the middle of a task implementation.
2. Coordinating AI Agents Across Components and Repositories

With SDD the dependencies between components are explicit. In practice, coordination between them is resolved mostly at the decomposition level:

  • Each task created in the Decomposition step should clearly specify the target repository or component, dependencies on other tasks and its completion criteria.
  • The tasks have a predefined order so that shared parts like API schemas or events are implemented first, followed by the dependent components one by one through the dependency tree.
  • Those tasks that can run in parallel are clearly marked accordingly in the generated task definitions.
  • As tasks describe fine-grained units of implementation, they replace prompt transferring between agents.
  • The agent may mark tasks as done in the tasks file to keep track of the work.
3. Standardizing Feature Definitions with Specs

Here is where SDD works best as it ensures repeatability and consistent structure by design:

  • For every feature the AI agent uses the generic project development principles and guidelines defined once during the SDD tool setup. All the steps from Specify to Implementation are based on these principles.
  • The predefined sequence of steps in the feature implementation process along with reiteration on each step makes the spec structure consistent.
  • The Verify step makes it easy to identify gaps in implementation and fix them through iterative refinements.

It's worth mentioning that SDD itself cannot guarantee that the initial specification is fully complete since AI itself is nondeterministic. It also cannot reveal requirements that initially were not included in the spec. It only provides a convenient mechanism to define the specification iteratively and continuously refine it, making it as complete as possible.

4. Making Implicit API Contracts Explicit

The following principles ensure explicit definition of API interactions and coupling:

  • The feature implementation plan is the natural place where the API contracts and coupling between components should be described. Some SDD tools, like GitHub SpecKit, even have a separate directory storing the API contracts created during the Plan step.
  • The generic project development principles should require the agent to document every consumed or exposed API contract in the plan, including optional fields, null vs empty values, default values, etc.
  • In the Plan phase, we may ask the agent to analyze the existing code and find the implicit dependencies related to the new feature being implemented.
  • When an implicit dependency is discovered during the implementation, the AI should be prompted to add it to the spec or plan, so it becomes explicit for other features.

However, SDD does not provide a mechanism for automatically discovering implicit dependencies or contracts. The AI will still need to infer those from the code if they are not captured in the plan or when the SDD is introduced into an existing project.

5. Preserving Project Knowledge in Version-Controlled Specs

Since SDD is based on feature specs, it naturally captures the knowledge about the project. To efficiently ensure knowledge preservation, we should follow certain rules:

  • All feature requirements are stored in a version control repository since they serve as a source of knowledge about the current application state and behavior.
  • Spec and plan files are treated as part of the definition of done: a feature is complete only when its specification fully reflects its behavior.
  • When new changes are needed in an existing feature, the prompt used in the Specify step should refer to the existing feature spec. The agent may either update an existing spec or add a new spec containing only the changes required by the feature update, referencing the original spec.
  • In the Verification step, the AI agent should be prompted to compare the spec with the code. If there are any differences, after we review them, the agent should update the spec.

Spec-driven development: Benefits, trade-offs and when to use it

Spec-driven development is a powerful methodology for AI-assisted software development. However, like any other approach or technology, it’s not a silver bullet. It has its pros and cons. On the one hand, it adds overhead related to specification management and spec-designing ceremonies. The SDD tools generate spec-related files that need to be reviewed and maintained in addition to the code itself. On the other hand, this enables achieving more consistent, reliable and repeatable results when writing software with AI agents. It’s a good fit for large-scale multi-component applications. When used properly, it helps to resolve many issues caused by the nature of AI agents. Defining a good specification, following the clear rules when designing specs and a consistent approach to applying the development workflow consistently is the key to making AI-assisted development efficient.

Further reading on spec-driven development

https://github.github.io/spec-kit/reference/agentic-sdd.html

https://speckit.org/

https://developer.microsoft.com/blog/spec-driven-development-ai-native-engineering

https://martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html

‍

Read more
Software development
AI

Spring AI Alternatives for Java Applications

In today's world, as AI-driven applications grow in popularity and the demand for AI-related frameworks is increasing, Java software engineers have multiple options for integrating AI functionality into their applications.

This article is a second part of our series exploring java-based AI frameworks. In the previous article we described main features of the Spring AI framework. Now we'll focus on its alternatives and analyze their advantages and limitations compared to Spring AI.

Supported Features

Let's compare two popular open-source frameworks alternative to Spring AI. Both offer general-purpose AI models integration features and AI-related services and technologies.

LangChain4j - a Java framework that is a native implementation of a widely used in AI-driven applications LangChain Python library.

Semantic Kernel - a framework written by Microsoft that enables integration of AI Model into applications written in various languages, including Java.

LangChain4j

LangChain4j has two levels of abstraction.

High-level API, such as AI Services, prompt templates, tools, etc. This API allows developers to reduce boilerplate code and focus on business logic.

Low-level primitives: ChatModel, AiMessage, EmbeddingStore etc. This level gives developers more fine-grained control on the components behavior or LLM interaction although it requires writing of more glue code.

Models

LangChain4j supports text, audio and image processing using LLMs similarly to Spring AI. It defines a separate model classes for different types of content:

  • ChatModel for chat and multimodal LLMs
  • ImageModel for image generation.

Framework integrates with over 20 major LLM providers like OpenAI, Google Gemini, Anthropic Claude etc. Developers can also integrate custom models from HuggingFace platform using a dedicated HuggingFaceInferenceApiChatModel interface. Full list of supported model providers and model features can be found here: https://docs.langchain4j.dev/integrations/language-models

Embeddings and Vector Databases

When it comes to embeddings, LangChain4j is very similar to Spring AI. We have EmbeddingModel to create vectorized data for further storing it in vector store represented by EmbeddingStore class.

ETL Pipelines

Building ETL pipelines in LangChain4j requires more manual code. Unlike Spring AI, it does not have a dedicated set of classes or class hierarchies for ETL pipelines. Available components that may be used in ETL:

  • TokenTextSegmenter, which provides functionality similar to TokenTextSplitter in Spring AI.
  • Document class representing an abstract text content and its metadata.
  • EmbeddingStore to store the data.

There are no built-in equivalents to Spring AI's KeywordMetadataEnricher or SummaryMetadataEnricher. To get a similar functionality developers need to implement custom classes.

Function Calling

LangChain4j supports calling code of the application from LLM by using @Tool annotation. The annotation should be applied to method that is intended to be called by AI model. The annotated method might also capture the original prompt from user.

Semantic Kernel for Java

Semantic Kernel for Java uses a different conceptual model of building AI related code compared to Spring AI or LangChain4j. The central component is Kernel, which acts as an orchestrator for all the models, plugins, tools and memory stores.

Below is an example of code that uses AI model combined with plugins for function calling and a memory store for vector database. All the components are integrated into a kernel:

public class MathPlugin implements SKPlugin {
   @DefineSKFunction(description = "Adds two numbers")
   public int add(int a, int b) {
       return a + b;
   }
}
...
OpenAIChatCompletion chatService = OpenAIChatCompletion.builder()
   .withModelId("gpt-4.1")
   .withApiKey(System.getenv("OPENAI_API_KEY"))
   .build();
KernelPlugin plugin = KernelPluginFactory.createFromObject(new MyPlugin(), "MyPlugin");
Store memoryStore = new AzureAISearchMemoryStore(...);
// Creating kernel object
Kernel kernel = Kernel.builder()
   .withAIService(OpenAIChatCompletion.class, chatService)
   .withPlugin(plugin)
   .withMemoryStorage(memoryStore)
   .build();
KernelFunction<String> prompt = KernelFunction.fromPrompt("Some prompt...").build();
FunctionResult<String> result = prompt.invokeAsync(kernel)
   .withToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true))
   .withMemorySearch("search tokens", 1, 0.8) // Use memory collection
   .block();

Models

When it comes to available Models Semantic Kernel is more focused on chat-related functions such as text completion and text generation. It contains a set of classes implementing AIService interface to communicate with different LLM providers, e.g. OpenAIChatCompletion, GeminiTextGenerationService etc. It does not have Java implementation for Text Embeddings, Text to Image/Image to Text, Text to Audio/Audio to Text services, although there are experimental implementations in C# and Python for them.

Embeddings and Vector Databases

For Vector Store Semantic Kernel offers the following components: VolatileVectorStore for in-memory storage, AzureAISearchVectorStore that integrates with Azure Cognitive Search and SQLVectorStore/JDBCVectorStore for an abstraction of SQL database vector stores.

ETL Pipelines

Semantic Kernel for Java does not provide an abstraction for building ETL pipelines. It doesn't have dedicated classes for extracting data or transforming it like Spring AI. So, developers would need to write custom code or use third party libraries for data processing for extraction and transformation parts of the pipeline. After these phases the transformed data might be stored in one of the available Vector Stores.

Azure-centric Specifics

The framework is focused on Azure related services such as Azure Cognitive Search or Azure OpenAI and offers a smooth integration with them. It provides a functionality for smooth integration requiring minimal configuration with:

  • Azure Cognitive Search
  • Azure OpenAI
  • Azure Active Directory (authentication and authorization)

Because of these integrations, developers need to write little or no glue code when using Azure ecosystem.

Ease of Integration in a Spring Application

LangChain4j

LangChain4j is framework-agnostic and designed to work with plain Java. It requires a little more effort to integrate into Spring Boot app. For basic LLM interaction the framework provides a set of libraries for popular LLMs. For example, langchain4j-open-ai-spring-boot-starter that allows smooth integration with Spring Boot. The integration of components that do not have a dedicated starter package requires a little effort that often comes down to creating of bean objects in configuration or building object manually inside of the Spring service classes.

Semantic Kernel for Java

Semantic Kernel, on the other hand, doesn't have a dedicated starter packages for spring boot auto config, so the integration involves more manual steps. Developers need to create spring beans, write a spring boot configuration, define kernels objects and plugin methods so they integrate properly with Spring ecosystem. So, such integration needs more boilerplate code compared to LangChain4j or Spring AI.

It's worth mentioning that Semantic Kernel uses publishers from Project Reactor concept, such as Mono<T> type to asynchronously execute Kernel code, including LLM prompts, tools etc. This introduces an additional complexity to an application code, especially if the application is not written in a reactive approach and does not use publisher/subscriber pattern.

Performance and Overhead

LangChain4j

LangChain4j is distributed as a single library. This means that even if we use only certain functionality the whole library still needs to be included into the application build. This slightly increases the size of application build, though it's not a big downside for the most of Spring Boot enterprise-level applications.

When it comes to memory consumption, both LangChain4j and Spring AI have a layer of abstraction, which adds some insignificant performance and memory overhead, quite a standard for high-level java frameworks.

Semantic Kernel for Java

Semantic Kernel for Java is distributed as a set of libraries. It consists of a core API, and of various connectors each designed for a specific AI services like OpenAI, Azure OpenAI. This approach is similar to Spring AI (and Spring related libraries in general) as we only pull in those libraries that are needed in the application. This makes dependency management more flexible and reduces application size.

Similarly to LangChain4j and Spring AI, Semantic Kernel brings some of the overhead with its abstractions like Kernel, Plugin and SemanticFunction. In addition, because its implementation relies on Project Reactor, the framework adds some cpu overhead related to publisher/subscriber pattern implementation. This might be noticeable for applications that at the same time require fast response time and perform large amount of LLM calls and callable functions interactions.

Stability and Production Readiness

LangChain4j

The first preview of LangChain4j 1.0.0 version has been released on December 2024. This is similar to Spring AI, whose preview of 1.0.0-M1 version was published on December same year. Framework contributor's community is large (around 300 contributors) and is comparable to the one of Spring AI.

However, the observability feature in LangChain4j is still experimental, is in development phase and requires manual adjustments. Spring AI, on the other hand, offers integrated observability with micrometer and Spring Actuator which is consistent with other Spring projects.

Semantic Kernel for Java

Semantic Kernel for Java is a newer framework than LangChain4j or Spring AI. The project started in early 2024. Its first stable version was published back in 2024 too. Its contributor community is significantly smaller (around 30 contributors) comparing to Spring AI or LangChain4j. So, some features and fixes might be developed and delivered slower.

When it comes to functionality Semantic Kernel for Java has less abilities than Spring AI or LangChain4j especially those related to LLM models integration or ETL. Some of the features are experimental. Other features, like Image to Text are available only in .NET or Python.

On the other hand, it allows smooth and feature-rich integration with Azure AI services, benefiting from being a product developed by Microsoft.

Choosing Framework

For developers already familiar with LangChain framework and its concepts who want to use Java in their application, the LangChain4j is the easiest and more natural option. It has same or very similar concepts that are well-known from LangChain.

Since LangChain4j provides both low-level and high-level APIs it becomes a good option when we need to fine tune the application functionality, plug in custom code, customize model behavior or have more control on serialization, streaming etc.

It's worth mentioning that LangChain4j is an official framework for AI interaction in Quarkus framework. So, if the application is going to be written in Quarkus instead of Spring, the LangChain4j is a go-to technology here.

On the other hand, Semantic Kernel for Java is a better fit for applications that rely on Microsoft Azure AI services, integrate with Microsoft-provided infrastructure or primarily focus on chat-based functionality.

If the application relies on structured orchestration and needs to combine multiple AI models in a centralized consistent manner, the kernel concept of Semantic Kernel becomes especially valuable. It helps to simplify management of complex AI workflows. Applications written in reactive style will also benefit from Semantic Kernel's design.

Links

https://docs.langchain4j.dev

https://learn.microsoft.com/en-us/azure/app-service/tutorial-ai-agent-web-app-semantic-kernel-java

https://gist.github.com/Lukas-Krickl/50f1daebebaa72c7e944b7c319e3c073

https://objectcomputing.com/how-we-share/news1/2024/06/27/maximizing-performance-netty-and-reactive-programming-java

https://javapro.io/2025/04/23/build-ai-apps-and-agents-in-java-hands-on-with-langchain4j

‍

Read more
Software development

Variable key names for Codable objects: How to make Swift Codable protocol even more useful?

 It’s hard to imagine modern     Swift iOS application    that doesn’t work with multiple data sources like servers, local cache DB, etc, or doesn’t parse/convert data between different formats. While Swift Codable protocol is a great solution for this purpose it also has some important drawbacks when developing a complex app that deals with multiple data formats. From this article, you will know how to improve the Swift Codable mechanism and why it’s important.

 Swift has a great feature for encoding/decoding data in key-value formats called Coding protocol. That is, you may choose to store data in e.g. JSON format or plist by at minimum just defining names of the keys for which the corresponding values should be stored.

Advantages and disadvantages of Swift Codable protocol

Here are the advantages of Codable protocol:

1)  Type safety . You don't need typecasting or parsing the strings read from the file. Swift does for you all the low-level reading and parsing only returning you a ready to use object of a concrete type.

2)  The Simplicity of usage . At a minimum, you may just declare that your type that needs to be encodable or decodable confirms to the corresponding protocol (either Codable or it's parts Decodable or Encodable). The compiler will match the keys from your data (e.g., JSON) automatically based on the names of your type's properties. In case you need advanced matching of keys' names with your type's properties (and in most real life cases you need it), you may define an enum CodingKeys that will do the mapping.

3)  Extensibility . When you need some advanced parsing, you may implement initialization and encoding methods to parse/encode the data. This, for example, allows you to decode several fields of JSON combining them into a single value or make some advanced transformation before assigning value to your codable object's property.

Despite its flexibility, the Codable approach has a serious limitation. For real-life tasks, it's often needed to store the same data in several data formats at the same time. For example, data coming from a server may be stored locally as a cache. Info about user account coming from the server is often stored locally to keep user sign in. At first glance, the Swift Codable protocol can be perfectly used in this case. However, the problem is that, as soon as one data source changes names of the keys for the stored values, the data won't be readable anymore by Codable object.

As an example let's imagine a situation when an application gets user info for a user account from the server and stores it locally to be used when the app is relaunched. In this case, the proper solution for parsing JSON data from the server into a model object is to use Codable protocol. The simplest way to store the object locally would be to just use Codable to encode the object (e.g. in plist format) and to store it locally. But codable object will use a certain set of keys that is defined by server JSON field names in our example. So if the server changes names of the JSON fields it returns, we'll have to change Codable implementation to match the new fields' names. So Codable implementation will use new keys to encode/decode data. And since the same implementation is used for local data, as well the user info that was previously saved locally will become unreadable.

To generalize, if we have multiple data sources for the same keyed data, the Codable implementation will stop working as soon as one of the data sources changes the names of the keys.

 Approach with multiple entities

Let's see how to improve the Swift Codable protocol to properly handle such a situation. We need a way to encode/decode from each data source without restriction to have the same key names. To do it, we may write a model object type for each data source.

Back to our example with server and local data, we’ll have the following code:

// Server user info

struct ServerUserInfo: Codable {

 let user_name: String

 let email_address: String

 let user_age: Int

}



// Local user info to store in User Defaults

struct LocalUserInfo: Codable {

 let USER_NAME: String

 let EMAIL: String

 let AGE: Int

}

So we have two different structures: one to encode/decode user info from server and the other to encode/decode data for local usage in User Defaults. But semantically, this is the same entity. So code that works with such object should be able to use any of the structures above interchangeably. For this purpose, we may declare the following protocol:

protocol UserInfo {

 var userName: String { get }

 var email: String { get }

 var age: Int { get }

}

Each user info structure will then conform to the protocol:

extension LocalUserInfo: UserInfo {

 var userName: String {

return USER_NAME

 }



 var email: String {

return EMAIL

 }



 var age: Int {

return AGE

 }

}

extension ServerUserInfo: UserInfo {

 var userName: String {

return user_name

 }



 var email: String {

return email_address

 }



 var age: Int {

return user_age

 }

}

So, code that requires user info will use it via  UserInfo protocol.

Such solution is a very straightforward and easy to read. However, it requires much code. That is, we have to define a separate structure for each format a particular entity can be encoded/decoded from. Additionally, we need to define a protocol describing the entity and make all the structures conform to that protocol.

 Approach with variational keys

Let’s find another approach that will make it possible to use a single structure to do the encoding/decoding from different key sets for different formats. Let’s also make this approach maintain simplicity in its usage. Obviously, we cannot have Coding keys bound to properties’ names as in the previous approach. This means we’ll need to override  init(from:) and  encode(to:) methods from Codable protocol. Below is a  UserInfo structure defined for coding in JSON format from our example.

extension UserInfo: Codable {

 private enum Keys: String, CodingKey {

case userName = "user_name"

case email = "email_address"

case age = "user_age"

 }



init(from decoder: Decoder) throws {

let container = try decoder.container(keyedBy: Keys.self)

self.userName = try container.decode(String.self, forKey: .userName)

self.email = try container.decode(String.self, forKey: .email)

self.age = try container.decode(Int.self, forKey: .age)

 }



func encode(to encoder: Encoder) throws {

var container = encoder.container(keyedBy: Keys.self)

try container.encode(userName, forKey: .userName)

try container.encode(email, forKey: .email)

try container.encode(age, forKey: .age)

 }

}

In fact, to make the code above decode and encode another data format we only need to change the keys themselves. That is, we’ve used simple enum conforming to the  CodingKey protocol to define the keys. However, we may implement arbitrary type conforming to the  CodingKey protocol. For example, we may choose a structure. So, a particular instance of a structure will represent the coding key used in calls to  container.decode() or  container.encode() . While implementation will provide info about the keys of a  particular data format.  The code of such structure is provided below:

struct StringKey: CodingKey {

 let stringValue: String

 let intValue: Int?



 init?(stringValue: String) {

self.intValue = nil

self.stringValue = stringValue

 }



 init?(intValue: Int) {

self.intValue = intValue

self.stringValue = "\(intValue)"

 }

}

So, the  StringKey just wraps a concrete key for a particular data format. For example, to decode userName from JSON, we’ll create the corresponding  StringKey instances specifying JSON  user_name field into  init?(stringValue:) method.

Now we need to find a way to define key sets for each data type. To each property from  UserInfo , we need somehow assign keys that can be used to encode/decode the property’s value. E.g. for property  userName corresponds to  user_name key for JSON and  USER_NAME key for plist format. To represent each property, we may use Swift’s  KeyPath type. Also, we would like to store information about which data format each key is used for. Translating the above into code we’ll have the following:

enum CodingType {

 case local

 case remote

}



extension UserInfo {

 static let keySet: [CodingType: [PartialKeyPath<UserInfo>: String]] = [

// for .plist stored locally

.local: [

  \Self.userName: "USER_NAME",

  \Self.email: "EMAIL",

  \Self.age: "AGE"

],

// for JSON received from server

.remote: [

  \Self.userName: "user_name",

  \Self.email: "email_address",

  \Self.age: "user_age"

]

 ]

}

To let the code inside  init(from:) and  encode(to:) methods aware of the decode/encode  data format we may use user info from  Decoder/Encoder objects:

extension CodingUserInfoKey {

 static var codingTypeKey = CodingUserInfoKey(rawValue: "CodingType")

}



...



let providedType = <either .local or .remote from CodingType enum>

let decoder = JSONDecoder()

if let typeKey = CodingUserInfoKey.codingTypeKey {

 decoder.userInfo[typeKey] = providedType

}

When decoding/encoding, we’ll just read the value from user info for  CodingUserInfoKey.codingTypeKey key and pick the corresponding set of coding keys.

Let’s bring all the above together and see how our code will look like:

enum CodingError: Error {

 case keyNotFound

 case keySetNotFound

}



extension UserInfo: Codable {

 static func codingKey(for keyPath: PartialKeyPath<Self>,

                    in keySet: [PartialKeyPath<Self>: String]) throws -> StringKey {

guard let value = keySet[keyPath],

      let codingKey = StringKey(stringValue: value) else {

throw CodingError.keyNotFound

}



return codingKey

 }



 static func keySet(from userInfo: [CodingUserInfoKey: Any]) throws -> [PartialKeyPath<Self>: String] {

guard let typeKey = CodingUserInfoKey.codingTypeKey,

      let type = userInfo[typeKey] as? CodingType,

      let keySet = Self.keySets[type] else {

  throw CodingError.keySetNotFound

}



return keySet

 }



 init(from decoder: Decoder) throws {

let keySet = try Self.keySet(from: decoder.userInfo)

let container = try decoder.container(keyedBy: StringKey.self)

self.userName = try container.decode(String.self, forKey: try Self.codingKey(for: \Self.userName,

                                                                                in: keySet))

self.email = try container.decode(String.self, forKey: try Self.codingKey(for: \Self.email,

                                                                             in: keySet))

self.age = try container.decode(Int.self, forKey: try Self.codingKey(for: \Self.age,

                                                                        in: keySet))

 }



 func encode(to encoder: Encoder) throws {

let keySet = try Self.keySet(from: encoder.userInfo)

var container = encoder.container(keyedBy: StringKey.self)

try container.encode(userName, forKey: try Self.codingKey(for: \Self.userName,

                                                         in: keySet))

try container.encode(email, forKey: try Self.codingKey(for: \Self.email,

                                                          in: keySet))

try container.encode(age, forKey: try Self.codingKey(for:

\Self.age,

                                                        in: keySet))

 }

}

Note we’ve added two helper static methods:  codingKey(for keyPath ,  in keySet) and  keySet(from userInfo) . Their usage makes code of  init(from:) and  encode(to:) more clear and straightforward.

 Generalizing the solution

Let’s improve the solution with coding key sets we’ve developed to make it easier and faster to apply. The solution has some boilerplate code for transforming KeyPath of the type into a coding key and choosing the particular key set. Also, encoding/ decoding code has a repeating call to  codingKey(for keyPath, in keySet) that complicates the  init(from:) and  encode(to:) implementation and can be reduced.

First, we’ll extract helping code into helper objects. It will be enough to just use structures for this purpose:

private protocol CodingKeyContainable {

 associatedtype Coding

 var keySet: [PartialKeyPath<Coding>: String] { get }

}



private extension CodingKeyContainable {

 func codingKey(for keyPath: PartialKeyPath<Coding>) throws -> StringKey {

guard let value = keySet[keyPath], let codingKey = StringKey(stringValue: value) else {

  throw CodingError.keyNotFound

}



return codingKey

 }

}

struct DecodingContainer<CodingType>: CodingKeyContainable {

 fileprivate let keySet: [PartialKeyPath<CodingType>: String]

 fileprivate let container: KeyedDecodingContainer<StringKey>



 func decodeValue<PropertyType: Decodable>(for keyPath: KeyPath<CodingType, PropertyType>) throws -> PropertyType {

try container.decode(PropertyType.self, forKey: try codingKey(for: keyPath as PartialKeyPath<CodingType>))

 }

}

struct EncodingContainer<CodingType>: CodingKeyContainable {

 fileprivate let keySet: [PartialKeyPath<CodingType>: String]

 fileprivate var container: KeyedEncodingContainer<StringKey>



 mutating func encodeValue<PropertyType: Encodable>(_ value: PropertyType, for keyPath: KeyPath<CodingType, PropertyType>) throws {

try container.encode(value, forKey: try codingKey(for: keyPath as PartialKeyPath<CodingType>))

 }

}

Protocol  CodingKeyContainable just helps us to reuse key set retrieving code in both structures.

Now let’s define our own Decodable/Encodable-like protocols. This will allow us to hide all the boilerplate code for getting the proper key set and creating a decoder/encoder object inside of the default implementation of  init(from:) and  encode(to:) methods. On the other hand, it will allow us to simplify decoding/encoding the concrete values by using  DecodingContainer and  EncodingContainer structures we’ve defined above. Another important thing is that by using the protocols, we’ll also add the requirement of implementing:

 static let keySet: [CodingType: [PartialKeyPath<UserInfo>: String]] by codable types for which we want to use the approach with variational keys.

Here are our protocols:

// MARK: - Key Sets

protocol VariableCodingKeys {

 static var keySets: [CodingType: [PartialKeyPath<Self>: String]] { get }

}



private extension VariableCodingKeys {

 static func keySet(from userInfo: [CodingUserInfoKey: Any]) throws -> [PartialKeyPath<Self>: String] {

guard let typeKey = CodingUserInfoKey.codingTypeKey,

      let type = userInfo[typeKey] as? CodingType,

      let keySet = Self.keySets[type] else {

  throw CodingError.keySetNotFound

}



return keySet

 }

}

// MARK: - VariablyDecodable

protocol VariablyDecodable: VariableCodingKeys, Decodable {

 init(from decodingContainer: DecodingContainer<Self>) throws

}



extension VariablyDecodable {

 init(from decoder: Decoder) throws {

let keySet = try Self.keySet(from: decoder.userInfo)

let container = try decoder.container(keyedBy: StringKey.self)

let decodingContainer = DecodingContainer<Self>(keySet: keySet, container: container)

try self.init(from: decodingContainer)

 }

}

// MARK: - VariablyEncodable

protocol VariablyEncodable: VariableCodingKeys, Encodable {

 func encode(to encodingContainer: inout EncodingContainer<Self>) throws

}



extension VariablyEncodable {

 func encode(to encoder: Encoder) throws {

let keySet = try Self.keySet(from: encoder.userInfo)

let container = encoder.container(keyedBy: StringKey.self)

var encodingContainer = EncodingContainer<Self>(keySet: keySet, container: container)

try self.encode(to: &encodingContainer)

 }

}



typealias VariablyCodable = VariablyDecodable & VariablyEncodable

Let’s now rewrite our  UserInfo structure to make it conform to newly defined  VariablyCodable protocol:

extension UserInfo: VariablyCodable {

 static let keySets: [CodingType: [PartialKeyPath<UserInfo>: String]] = [

// for .plist stored locally

.local: [

  \Self.userName: "USER_NAME",

  \Self.email: "EMAIL",

  \Self.age: "AGE"

],

// for JSON received from server

.remote: [

  \Self.userName: "user_name",

  \Self.email: "email_address",

  \Self.age: "user_age"

]

 ]



init(from decodingContainer: DecodingContainer<UserInfo>) throws {

self.userName = try decodingContainer.decodeValue(for: \.userName)

self.email = try decodingContainer.decodeValue(for: \.email)

self.age = try decodingContainer.decodeValue(for: \.age)

 }



 func encode(to encodingContainer: inout EncodingContainer<UserInfo>) throws {

try encodingContainer.encodeValue(userName, for: \.userName)

try encodingContainer.encodeValue(email, for: \.email)

try encodingContainer.encodeValue(age, for: \.age)

 }

}

This is where a true power of protocols comes. By conforming to  VariablyCodable our type automatically becomes Codable. Moreover, without any boilerplate code, we now have the ability to use different sets of coding keys.

Going back to the advantages of the Codable protocol we outlined at the beginning of the article, let’s check which ones  VariablyCodable has.

1)  Type safety . Nothing changed here comparing to the Codable protocol.  VariablyCodable protocol still uses concrete types without involving any dynamic type casting.

2)  The simplicity of usage . Here we don’t have declarative style option with enum describing keys and values. We always have to implement  init(from:) and  encode(to:) methods. However, since the minimum implementation of the methods is so simple and straightforward (each line just decodes/encodes single property) that it is comparable to defining  CodingKeys enum for the Codable protocol.

3)  Extensibility . Here we have more abilities comparing to the Codable protocol. Additionally to the flexibility that can be achieved by implementing  init(from:) and  encode(to:) methods, we have also  keySets map that provides an additional layer of abstraction of coding keys.

 Summary

We defined two approaches to extend the behavior of the Codable protocol in Swift to be able to use a different set of keys for different data formats. The first approach implying separate types for each data format works well for simple cases when having two data formats and a single data flow direction (e.g. decoding only). However, if your app has multiple data sources and encodes/decodes arbitrarily between those formats you may stick to approach with  VariablyCodable protocol. While it needs more code to be written at the beginning, once implemented, you will  gain great flexibility and extensibility in coding/decoding data for any type you need .

Read more
View all
About UsCase studiesContactCareers
Capabilities:
CloudLegacy ModernizationData PlatformsAI & Advanced AnalyticsAgentic AI
Industries:
AutomotiveFinanceManufacturingAviation
Solutions:
DataboostrCloudboostrAiboostr
Resources
BlogInsights
© Grape Up 2025
Cookies PolicyPrivacy PolicyTerms of use
Grape Up uses cookies

This website uses cookies to improve its user experience and provide personalized content for you. We use cookies for web analytics and advertising. You can accept these cookies by clicking "OK" or go to Details in order to manage your cookies preferences more precisely. To learn more, check out our Privacy and Cookies Policy

Accept allDetails
Grape Up uses cookies

Essential website cookies are necessary to provide you with services available through the website, autosave your settings and preferences, and to enhance the performance and security of the website - you have the right not to accept them through your web browser's settings, but your access to some functionality and areas of our website may be restricted.

Analytics cookies: (our own and third-party : Google, HotJar) – you can accept these cookies below:

Marketing cookies (third-party cookies: Hubspot, Facebook, LinkedIn) – you can accept these cookies below:

Ok