A New Hello World
Whenever I'm learning a new programming language, or refreshing one I haven't used for a while, I like to revisit a small coding challenge I had to do for a job interview: a console-based drawing application I originally wrote in C#.
It's my slightly more elaborate version of Hello World.
The application accepts simple commands to create a canvas, draw lines and shapes, fill areas and display the result using characters in the console.
I've since implemented versions in Ruby, Kotlin, JavaScript and Java. The Ruby and JavaScript versions were deliberately simple, the Kotlin version experimented with the infix operator, but for the Java implementation I wanted to experiment with something else: using Spring Context to map user commands to their implementations.
It's a small application, and Spring certainly isn't necessary for something of this size. But that's part of the point of these exercises — they're an opportunity to explore a language or framework without the complexity of a larger project.
The Command Pattern
The application uses a variation of the Command pattern. Each operation is represented by a class derived from an abstract Command base class.
The base class defines a common execution method:
public abstract void execute(Input in, Canvas canvas);
It also holds metadata describing the command, including its usage, minimum number of arguments and whether it modifies the canvas.
For example, the LineCommand implementation looks like this:
public class LineCommand extends Command {
public LineCommand() {
super("L x1 y1 x2 y2 c", "draws a line with optional 'c' colour", 4, true);
}
@Override
public void execute(Input in, Canvas canvas) {
var x1 = in.x1();
var y1 = in.y1();
var x2 = in.x2();
var y2 = in.y2();
var pen = in.argCount() == 5
? in.pen(4)
: Canvas.PEN;
Line.draw(canvas, x1, y1, x2, y2, pen);
}
}
The command is responsible for interpreting its arguments and invoking the appropriate drawing operation. The actual line-drawing algorithm lives in a separate Line class.
Other commands follow the same general approach.
The interesting question is how the application determines which command to execute.
Mapping Commands with Spring Context
A conventional implementation might use a switch statement or a Map<String, Command> to associate command identifiers with their implementations.
For this version, I decided to let Spring's application context act as the command registry.
Commands are registered as named beans in ProjectConfig:
@Configuration
@ComponentScan
public class ProjectConfig {
@Bean(name = "l")
public LineCommand lineCommand() {
return new LineCommand();
}
@Bean(name = "r")
public RectangleCommand rectangleCommand() {
return new RectangleCommand();
}
@Bean(name = "?")
public HelpCommand helpCommand() {
return new HelpCommand();
}
// Other commands...
}
The important detail is the bean name.
For example, the bean named r represents the rectangle command, while l represents the line command.
The identifiers entered by the user are therefore also the names used to retrieve the corresponding beans from Spring Context. This removes the need for a separate command mapping table.
Resolving and Executing Commands
The CommandManager is responsible for resolving and executing commands.
It receives Spring's ApplicationContext, along with the shared Canvas and Renderer, through constructor injection:
@Autowired
public CommandManager(
ApplicationContext context,
Canvas canvas,
Renderer renderer) {
this.renderer = renderer;
this.context = context;
this.canvas = canvas;
}
When the user enters a command, the manager resolves it using:
cmd = (Command) context.getBean(input.cmd());
That's the central mechanism.
The command identifier extracted from the input is passed directly to Spring's getBean() method. Spring returns the corresponding command instance, which the manager executes through the common Command abstraction.
The relevant execution logic is:if (input.argCount() < cmd.minArgs()) {
return invalidCommand(input, "argument error, expected: " + cmd.example());
}
try {
cmd.execute(input, canvas);
if (cmd.dirty()) {
renderer.drawCanvas();
}
} catch (Exception e) {
cmd = invalidCommand(input, e.getMessage());
}
The manager validates the minimum number of arguments, executes the command and redraws the canvas when required.
It doesn't need to know whether it's executing a line, rectangle, triangle or any other operation.
Adding another command is largely a matter of implementing the Command abstraction and registering a bean with the appropriate name.
Application Architecture
The following simplified UML diagram shows the main components and their relationships.
The application has a few other components worth mentioning.
InputProcessor reads user input and converts it into an Input object. Canvas stores the drawing state in a flat character array, while Renderer is responsible for displaying that state in the console.
Spring manages the shared components, so successive commands operate on the same canvas.
The drawing primitives themselves are separate from the command infrastructure.
A Few Considerations
Using Spring Context this way is an interesting exercise, although it comes with some trade-offs.
For a small console application, a simple map would be easier to understand and would avoid introducing a framework dependency.
The command lookup also uses ApplicationContext.getBean() directly. This is effectively a service-locator-style approach: the manager asks the container for a dependency at runtime, rather than having every possible command injected into it.
That's worth distinguishing from the constructor injection used elsewhere in the application.
Spring beans are singleton-scoped by default, so command instances are generally reused. In this implementation, commands such as LineCommand don't retain execution-specific state, making that behaviour appropriate.
The benefit for this exercise was the opportunity to explore Spring's configuration and bean-resolution mechanisms in a small, practical application.
Source Code
The Java implementation is available on GitHub: Picasso
This remains one of my favourite ways to refresh a language: take a familiar problem, implement it again and use the opportunity to explore a different approach.
In this case, the interesting part wasn't the console graphics. It was discovering how Spring Context could be used to map command identifiers to implementations with the Command pattern providing a common execution interface.