Shameless re-post, but great content!
http://somethingdoneright.net/2015/07/30/when-object-orientation-works-a-rule-of-thumb.html
Showing posts with label OO. Show all posts
Showing posts with label OO. Show all posts
Wednesday, 30 September 2015
Tuesday, 16 September 2014
State in Functional Programming and OO
Just some musing...
In OO the global state, present in the old procedural programming, is broken up and the shards are moved into small, independent moving parts of the system, the objects. The objects don't expose their state, instead they expose behaviour. So the state disappears and and intricate net of acting agents fill its place. I have, like OO-fans, always seen this as an advantage, fascinated by the elegance of the transformation itself. But the disadvantage became obvious when I started learning FP. Since the state is obfuscated behind the objects' APIs, for a developer it can be hard to determine in exactly what state the system is. When I call a method on an object to return something it might send a message to another object or write into the DB and I won't know about it. Debugging is hard. Again I'm not sure it's a bad thing and I suppose sometimes it's good, e.g. in the case of logging. FP goes against this information hiding paradigm and promotes side-effect-free programming. Of course a program should have side-effects, otherwise what's the point? But FP forces the programmer to be very explicit about side-effects (= state changes). In an ideal FP architecture the inside of the onion is composed of pure functions and all the "impure stuff", like DB-operations, user input reading, web-service calling, etc, are in the outer layer, very visible, very explicit. So paradoxically, FB, being a state-shunning paradigm, is much more about the state than OO, which is about behaviour.
When I have some time and feel the creativity to do it, I'll append some examples.
Tuesday, 2 September 2014
Mars Rovers in Clojure - Rewriting an Akka project to a Core Async one
I've decided to to reimplement Kaloz's Mars Rover Scala (for brevity's sake SMR from now on) project in Clojure (CMR). SMR is based on Actors of the Akka framework. Actors are the manifestation of the original idea of object orientation, that is, independent entities hiding their internal state and communicating via message passing. Since the whole model is purely about side effects, it seemed a nice challenge to implement in a functional way.
I wanted to have a jar as an end product that can be substituted to the backend of the original Scala, using the original presentation layer. I'm not there yet, but a first version is available on Github, where mars rovers can run in the REPL, spitting out their positions simply to the console.
All in all the project is a nice round 600 LOC. The Scala version had 548, which is not surprising. Scala, much like Clojure, is a very concise language, but because of its syntax you can compress the code more and still retain readability.
The main differences between SMR and CMR are
I wanted to have a jar as an end product that can be substituted to the backend of the original Scala, using the original presentation layer. I'm not there yet, but a first version is available on Github, where mars rovers can run in the REPL, spitting out their positions simply to the console.
All in all the project is a nice round 600 LOC. The Scala version had 548, which is not surprising. Scala, much like Clojure, is a very concise language, but because of its syntax you can compress the code more and still retain readability.
The main differences between SMR and CMR are
- Instead of complecting state, identity and behavioural logic, the Clojure version uses pure functions to capture the behaviour.
- All the "actors" have a receive method that takes the state of the "actor" and the received message (plus some additional information sometimes) and returns the new state with possibly a list of messages and executable effects.
- Context changes in actors are implemented in a surprisingly elegant way via multimethods. Different version of receive is called based on the state of the "actor"
- The actors are simple atoms. The state of the atom is the input of the receive and the state part of the output is swap!-ed into it
- The Clojure version, for the time being, lacks the distributed nature of Akka, and also its error handling mechanism.
- It uses the core.async for asynchronous communication. Where in the Scala version actors hold references to other actors, here channels are passed around
- The architecture, not surprisingly, is quite different
Application = 75% pure functions + 6% glue + 8% application-level + 11% other
During the reimplementation I dissected the code to form 4 distinct parts. LOC-wise the sizes of these parts are
- 75% is pure, framework-neutral functional code. I moved all those source files under marsrover.pure package.
- 6% is the glue, a mini messaging-framework I built over core.async in marsrover.glue.clj. In this "framework" a component's state is preserved in an atom. The component has an in-channel, an atom, and a function defining its behaviour. When a message arrives on the channel the component's state (value of the atom) and the message are the inputs of the behaviour function, and the output is the new state, the messages it has to send out, and possibly some effects. It's all very high level, doesn't know anything about our particular domain.
- 8% is the application layer, it's in marsrover.app.clj. This takes the pure part and injects it in the glue.
- 11% is other stuff like reading the expedition config (number of rovers, size of the plateau, etc).
So there is a big bulk of pure functional blob and a very thin layer glueing it together to form a proper application. I find this really fascinating. In the original Scala/Akka implementation the Akka framework and the logic was undisentangibly intertwined. Now the glue uses core.async, but if I wanted to use an actor-framework instead or any other approach, I would only need to change that 35 lines confined in a single source file. I say it again, it's fascinating. With functional approach we can push the framework/technology -related code to the outmost layer of our application, making it seem almost insignificant. The pure functions won't change if we want to move from the asynchronous model to synchronous, or replace core.async with any other integration solution. Imagine you'd wanna rewrite Mars Rovers in Scala, but not using Actors.
Finally, you can run the app by running marsrover.mars_expedition.clj in the REPL.
Finally, you can run the app by running marsrover.mars_expedition.clj in the REPL.
Wednesday, 26 February 2014
Defining your own exception types
I'm in a habit of creating different classes for different exceptions, as opposed to for example using RuntimeException-s or IllegalStateException-s describing details as a string in the constructor. I'm not hundred percent sure that's an ultimately better practice and recently I've watched a talk where the speaker adviced against class proliferation. True, in a language like Java, creating classes is very boilerplate. In Scala an exception class is probably half a line of code, and you can stuff a dozen in the same source file.
But, yesterday I realized there is a situation where a custom exception class comes handy. Imagine you put some validation logic in your domain class.
The Validate can be a validator class from Apache Commons or some custom class you wrote throwing IllegalArgumentException-s. At the project I'm working on right now we are using messaging and ActiveMQ as the integration solution. If there is an exception, the message is bounced back to the queue and the broker retries to deliver it a couple of times before it gives up and puts the message in the Dead Letter Queue. So if the message had a null as a player id, no matter how many times the broker retries it will always fail, but in the meantime the process consumes time and threads, possibly generating the same error log for a number of times. Instead of this if you create a( possibly abstract) n custom exception for domain problems, like
And at the entry point of your system you do a try-catch for it
Then you can catch and handle the problems where there is no chance of recovery in retrying.
But, yesterday I realized there is a situation where a custom exception class comes handy. Imagine you put some validation logic in your domain class.
public class PlayerId {
private final String id;
public PlayerId(String id) {
Validate.notNull(id);
this.id = id;
}
}
The Validate can be a validator class from Apache Commons or some custom class you wrote throwing IllegalArgumentException-s. At the project I'm working on right now we are using messaging and ActiveMQ as the integration solution. If there is an exception, the message is bounced back to the queue and the broker retries to deliver it a couple of times before it gives up and puts the message in the Dead Letter Queue. So if the message had a null as a player id, no matter how many times the broker retries it will always fail, but in the meantime the process consumes time and threads, possibly generating the same error log for a number of times. Instead of this if you create a( possibly abstract) n custom exception for domain problems, like
public abstract class DomainException extends RuntimeException {
public DomainException(String msg) {
super(msg);
}
}
And at the entry point of your system you do a try-catch for it
try {
// do the real thing
} catch(DomainException ex) {
//do something, e.g. logging
}
Then you can catch and handle the problems where there is no chance of recovery in retrying.
Labels:
exceptions
,
OO
Friday, 25 October 2013
Represent your IDs as Value Objects
I'm a big fan of creating Value Object classes for ids. It might seem over-engineering at first, so if you think so, please suspend your disbelief for a short time and let me try to show you some (3) benefits.
Let's have the following example. In your RPG game a Player can choose an Avatar for herself from a bunch. Let's assume first that you haven't followed my advice and used simply primitives (or their autoboxed versions) for ids. It's easy to imagine that the code for this use case includes an application service (or facade if you like) which does everything application services are supposed to do, and delegates to a domain service.
In the Domain all kind of checks and fiddling could ensue with passing on and on the playerId and the avatarId to various objects and methods.
Problem 1
Now, since both ids are Integers imagine how easy to make a small mistake and pass playerId instead of avatarId somewhere. I assure you, in a fairly complex code with many moving parts, hours of debugging can follow before you detect this mistake. Introducing id classes like
Problem 2
At some point it turns out that Integer is too limited to hold the playerIds and the decision to convert to Long is made. Without a wrapper class every single method which has it as an Integer argument must change (see the code above). It can mean a pretty large number of changes. If it's wrapped around with a Value Object, the only places we need to change are the ones when it's actually evaluated (at the boundaries of the anti-corruption layers, where it is transformed to/from primitive).
Problem 3
Let's assume the client was sloppy and sent us a Null as playerId. The code passes it around for a while before something tries to actually use it (like the database), then most probably blows up with some strange exception. If it happened deep enough (long way from the entry point, the app service), it might prove tricky to locate the source of the problem. If in our Value Object class constructor we add some validation and wrap the primitive value in it at once when it steps inside our domain, like this
Let's have the following example. In your RPG game a Player can choose an Avatar for herself from a bunch. Let's assume first that you haven't followed my advice and used simply primitives (or their autoboxed versions) for ids. It's easy to imagine that the code for this use case includes an application service (or facade if you like) which does everything application services are supposed to do, and delegates to a domain service.
In the Domain all kind of checks and fiddling could ensue with passing on and on the playerId and the avatarId to various objects and methods.
//application service - orchestrates beetween domain services and objects,
//authenticates, handles transactions, ....
class PlayerAccessoriesService {
public void assignAvatarToPlayer(Integer playerId, Integer avatarId) {
authenticationCheck();
logging();
transactionStart();
playerService.assignAvatarToPlayer(playerId, avatarId);
transactionEnd();
}
}
//domain service
class PlayerService {
public void assignAvatarToPlayer(Integer playerId, Integer avatarId) {
avatarRepository.checkAvatarIdIsValid(avatarId);
Player player = playerRepository.find(playerId);
player.setAvatar(avatarId);
playerRepository.update(player);
}
}
interface PlayerRpository {
Player find(Integer playerId);
}
interface AvatarRepository {
void checkAvatarIdIsValid(Integer avatarId);
}
So let's see the various problems with this approach!Problem 1
Now, since both ids are Integers imagine how easy to make a small mistake and pass playerId instead of avatarId somewhere. I assure you, in a fairly complex code with many moving parts, hours of debugging can follow before you detect this mistake. Introducing id classes like
class PlayerId {
private final Integer value;
public PlayerId(Integer value) { this.value = value; }
public Integer getValue() { return this.value; }
}
eliminates this problem. The new method signatures would look like
class PlayerService {
public void assignAvatarToPlayer(PlayerId playerId, AvatarId avatarId) { ... }
}
The difference is somewhat similar to the one between static and dynamic typing. The transformation from primitives to Value Objects happens in the Anti-corruption layer, wherever you may draw it (between application and domain layer, or outside of the application layer).Problem 2
At some point it turns out that Integer is too limited to hold the playerIds and the decision to convert to Long is made. Without a wrapper class every single method which has it as an Integer argument must change (see the code above). It can mean a pretty large number of changes. If it's wrapped around with a Value Object, the only places we need to change are the ones when it's actually evaluated (at the boundaries of the anti-corruption layers, where it is transformed to/from primitive).
Problem 3
Let's assume the client was sloppy and sent us a Null as playerId. The code passes it around for a while before something tries to actually use it (like the database), then most probably blows up with some strange exception. If it happened deep enough (long way from the entry point, the app service), it might prove tricky to locate the source of the problem. If in our Value Object class constructor we add some validation and wrap the primitive value in it at once when it steps inside our domain, like this
class PlayerId {
private final Integer value;
public PlayerId(Integer value) {
Validate.notNull("Player Id must be non-null", value)
this.value = value;
}
public Integer getValue() { return this.value; }
}
it will blow up immediately, making the problem very easy to locate. What we actually did here is applying the Fail-fast principle.Naming of interfaces and abstract classes
This gonna be a short one. What naming conventions (if any) do you follow for interfaces, abstract classes and implementations? Sometimes I come across the C# way of using the prefix 'I' in interfaces and feel an instant dislike. I think by referring to the type of the reference we are breaching encapsulation and going against polymorphism as well. Let's see the following example
But since it seems a default convention in C# circles (and I've come across some cases in Java projects), I'd be interested in any counter-arguments.
class UserLifecyleService {
private IUserRepository userRepository;
public void createUser(User user) {
//do some stuff, logging, authentication,...
userRepository.create(user);
//do some stuff, send out an event or whatever
}
}
So the repository it's an interface. What if later the need arise to make it an abstract class instead? Or a concrete one? Or the other way around, it was concrete then we realised that we are supposed to depend on abstractions? What's happening here is that we've exposed some implementation detail to the client of the repository, creating an unwanted coupling. If we change the type of our component, then we need to do code change in the client (here the UserLifecycleService), too.But since it seems a default convention in C# circles (and I've come across some cases in Java projects), I'd be interested in any counter-arguments.
Thursday, 24 October 2013
Testing different implementations of the Domain Repository interface
The post is about a simple but useful way of writing tests against different implementations of a Repository interface. Assuming you have a PlayerRepository in your Domain (this is just an interface) and two implementations in the Infrastructure layer, InMemoryPlayerRepository and MongoPlayerRepository. The latter is used in production, the former is mainly for tests.
interface PlayerRepository {
boolean exists(PlayerId playerId);
}
class InMemoryPlayerRepository implements PlayerRepository {
@Override public boolean exists(PlayerId playerId) { ... }
}
class MongoPlayerRepository implements PlayerRepository {
@Override public boolean exists(PlayerId playerId) { ... }
}
I used to maintain different test suites for them, since MongoPlayerRepository required for example a running Mongo process and a running Spring application context, while the in-memory version did not. But most tests were identical so it was simply duplicated code. The solution I'm using nowadays is extracting the tests in an abstract test template class and do implementation specific test configuration in the subclasses.
abstract class AbstractPlayerRepositoryTestTemplate {
protected PlayerRepository testObj;
@Test
public void exists() {
// setup
...
//assert
assertTrue(testObj.exists(playerId));
}
}
class InMemoryPlayerRepositoryTest extends AbstractPlayerRepositoryTestTemplate {
@Before
public void before() {
testObj = new InMemoryPurchaseStore();
}
}
@ContextConfiguration("classpath:applicationContext-test.xml")
@RunWith(SpringJUnit4ClassRunner.class)
class MongoPlayerRepositoryITest extends AbstractPlayerRepositoryTestTemplate {
@Resource
private MongoPlayerRepository mongoRepository;
@Before
public void before() {
testObj = mongoRepository;
testObj.clear();
}
}
Of course you can use the approach for anything where there are multiple implementations of an interface, I just come across the need most frequently with Repositories.
Subscribe to:
Posts
(
Atom
)