I am currently in the process of writing a (custom) Minecraft server application in C#. I figured it’s a good way to teach me a lot of important things like concurrency and especially memory efficiency (due to simply the vastness of the object space in Minecraft).
While on the train yesterday, I was finding it hard to really “think” of a way to organize the network module. I wanted a simple external interface that would give out the necessaries (Let users react to a connection being received, message being received, and when a connection is dropped). However, I also wanted it to be fairly abstract such that I could allow for either real game clients to connect or simple fake clients.
I started over-engineering things a la IConnection
, INetworkModule
, IConnectionFactory
, IConnectionProtocol
, IMessageEncoder
, IMessageDecoder
and so on. Kingdom of nouns galore. Not only that but I wasn’t really getting anywhere – it just felt like I was putting the fundamental problem behind other layers of abstraction in that I had no idea how I wanted to organize the communication between all these modules.
Then I came to the thought – why don’t I just use verbs (actions/functions/methods/whatever) instead of nouns (types) – let’s focus on what I want to achieve for now, and split it up into nouns later!
And so, I came up with something similar to this:
private static Func<IDisposable> Listen(
Action<TcpClient> onConnectionReceived,
Action<TcpClient> onConnectionDropped,
Action<TcpClient, int, byte[]> onBytesReceived,
Func<bool> isOpen)
{
// todo: 25565 needs to be injected
// todo: give opportunity to supply listener
// todo: refactor listener into role interface
var listener = new TcpListener(IPAddress.Any, 25565);
return () => Observable.FromAsync(listener.AcceptTcpClientAsync)
.DoWhile(isOpen)
.Subscribe(client =>
{
var stream = client.GetStream();
// on subscribe invoke the delegate first
onConnectionReceived(client);
// the delegate has the option to disconnect the client
// based on whatever criteria it see fit.
// we should now create an observable to
// listen for messages on this client.
Observable.Defer(() =>
{
// 8kb buffer for each connection
// this is actually fairly small
var buffer = new byte[8024];
// we can handle the 'doing' of things with these bytes
// inside the passed function. This function will be doing too much otherwise
return Observable.FromAsync(ct => stream.ReadAsync(buffer, 0, buffer.Length, ct))
.Select(n => new {Read = n, Bytes = buffer});
}).Subscribe(a =>
{
// drop connection if nothing was read
if (a.Read <= 0)
onConnectionDropped(client);
else
onBytesReceived(client, a.Read, a.Bytes);
});
});
}
Really simple. Well, I mean, not quite, but this basically does the role of all of the nouns (except IMessageEncoder/Decoder
that I listed earlier), but only making assumptions of the fact that we need a TcpClient
(obviously, that isn’t what I want right now, but I can work to that in iteration 2!)
However, my problem with this is, is that this isn’t really typical C# code.. and it surely breaks the SRP in that this function is returning a function for the entire execution of a server.
But – it makes sense to me.
So my question is, is there any real inherent downside to using a functional-esque paradigm like this as opposed to traditional Kingdom of Nouns OOP inside of C# – traditionally a multi-paradigm language? And if there are downsides, what would I face and why?
For the record, I intend for this to be OSS, so there’s another issue in that some developers might not understand the code style because it’s simply not OOP orientated, just pure functions.
2
If there’s something bad about mixing programming paradigms, then it’s clearly lost on the C# designers; Linq is essentially a functional programming pipeline.
Clearly you already know about Steve Yegge’s post, since you’re referring to the Kingdom of Nouns. Of course, the world didn’t suddenly see the error of its ways and stop using Java. Why?
- Because Java is already widely used and well-understood.
- Because the Kingdom of Nouns is well-suited for building data-based business systems (the efforts of Architecture Astronauts to overtake the plumbing notwithstanding).
- Languages like Java have lots of ceremony like classes, interfaces, methods, scope and so on that programmers can use to understand the program’s architecture. This ceremony is largely absent in most functional languages, or at least not overtly visible.
So does that mean that you abandon functional programming altogether? Of course not. The lack of ceremony allows certain things to be done more quickly and more intuitively in a functional paradigm than in the Kingdom of Nouns. This is especially true of math-like operations.
Mixing programming metaphors is a perfectly valid way to program. Were this not true, we’d only need the One True Programming Language to Rule Them All.
1
I believe you should be extremely careful when mixing programming paradigms in one place. The main reason is that when you mix paradigms, it will become problematic to apply “idiomatic” solutions on one paradigm to problems, that mix multiple paradigms.
I do have problem with your example, because it is not inherently functional. You could easily replace those “Actions” and “Funcs” with “Commands”. It would become pure OOP code, when you start composing functions and start using higher-order functions.
Example where I found mixing to be problematic was, when once in code, we needed to “decorate” some method with pre and post-running action. The first obvious way was to create function, that would get Action, run it between pre and post code. But then, it become extremely problematic to slightly change this pre and post behavior and we had to introduce function parameters and mix multiple behaviors in single method. If we instead implemented it as class which could decorate the method, then it would be easy to use inheritance to change the pre and post actions. The slight problem with this solution is that it needs you to create a new class, which has little bit more of code than simple method.
So for me, it is great to have functional capabilities for something like LINQ, but I would think hard before using functional composition as piece of architecture or design in .NET/C# application.
I would also like to emphasize on Command pattern. I believe this pattern is heavily underappreciated and underused. Both functional and object design is all about composing behaviors. It is just that both use slightly different tools to get to the same end result. And it is probably problem of education, that many people doing OOP design don’t understand that.
9