Service access Entity attributes - oop

In oop we seek to encapsulation. We try not to expose internal state via getters or by public fields, only expose methods.
So far so good.
In situation when we would like to operate on multiple Entities we introduce Service.
But how this service can operate freely on these entities?
If all (both Service and Entities) were in the same package, Entities could expose package private methods or fields and Service could use them, preserving encapsulation. But what when Entities and Service are from different packages? It seems that Entities should either expose public getters (first step to anemic model and leackage of logic from Entities), or public methods executing logic that is specific to the needs of service, possibly introduced only by requirements of this service - also seems bad. How to tackle this?

In the context of OO, the most important thing for you to understand is that objects respond to messages, and that in OOP in particular, methods are how these responses are implemented.
For example, imagine you have a Person object to which you (as the programmer) have assigned the responsibility to respond to the "grow" message. Generally, you would implement that as a Person.grow() method, like this.
class Person {
int age;
public void grow() { this.age++; }
}
This seems fairly obvious, but you must note that from the message sender's perspective, how Person object reacts is meaningless. For all it cares, the method Person.grow() could be triggering a missile launch, and it would not matter because some other object (or objects) could be responding in the right way (for example, a UI component updating itself on the screen). However, you decided that when the Person object handles the "grow" message, it must increment the value of its age attribute. This is encapsulation.
So, to address your concern, "public methods executing logic that is specific to the needs of service, possibly introduced only by requirements of this service - also seems bad", it is not bad at all because you are designing the entities to respond to messages from the services in specific ways to match the requirements of your application. The important thing to bear in mind is that the services do not dictate how the entities behave, but rather the entities respond in their own way to requests from the services.
Finally, you might be asking yourself: how do entities know that they need to respond to certain messages? This is easy to answer: YOU decide how to link messages to responses. In other words, you think about the requirements of your application (what "messages" will be sent by various objects) and how they will be satisfied (how and which objects will respond to messages).

In situation when we would like to operate on multiple Entities we introduce Service.
No we don't. Well, I guess some people do, but the point is they shouldn't.
In object-orientation, we model a particular problem domain. We don't (again, shouldn't) discriminate based on what amount of other objects a single object operates. If I have to model an Appointment and a collection of Appointment I don't introduce an AppointmentService, I introduce a Schedule or Timetable, or whatever is appropriate for the domain.
The distinction of Entity and Service is not domain-conform. It is purely technical and most often a regression into procedural thinking, where an Entity is data and the Service is a procedure to act on it.
DDD as is practiced today is not based on OOP, it just uses object syntax. One clear indication is that in most projects entities are directly persisted, even contain database ids or database-related annotations.
So either do OOP or do DDD, you can't really do both. Here is a talk of mine (talk is german but slides are in english) about OO and DDD.

I don't see the usage of getters as a step towards an anaemic model. Or at least, as everything in programming, it depends.
Downside of anaemic model is that every component accessing the object can mutate it without any enforcing of its invariants (opening to possible inconsistency in data), it can be done easily using the setter methods.
(I will use the terms command and query to indicate methods that modify the state of the objects and methods that just return data without changing anything)
The point of having an aggregate/entity is to enforce the object invariants, so it exposes "command" methods that don't reflect the internal structure of the object, but instead are "domain oriented" (using the "ubiquitous language" for their naming), exposing its "domain behavior" (an avoidance of get/set naming is suggested because they are standard naming for representing the object internal structure).
This is for what concern the set methods, what about get?
As set methods can be seen as "command" of the aggregate, you can see the getters as "query" methods used to ask data to the aggregate. Asking data to an aggregate is totally fine, if this doesn't break the responsability of the aggregate of enforcing invariants. This means that you should watch out to what the query method returns.
If the query method result is a value object, so, immutable, it is totally fine to have it. In this way who query the aggregate has in return something that can be only read.
So you could have query methods doing calculation using the object internal state (eg. A method int missingStudents() that calculate the number of missing student for a Lesson entity that has the totalNumber of students and a List<StudentId> in its internal state), or simple methods like List<StudentId> presentStudent() that just returns the list in its internal state, but what change from a List<StudentId> getStudents() its just the name).
So if the get method return something that is immutable who use it can't break the invariants of the aggregate.
If the method returns a mutable object that is part of the aggregate state, whoever access the object can query for that object and now can mutate something that stays inside the aggregate without passing for the right command methods, skipping invariants check (unless it is something wanted and managed).
Other possibility is that the object is created on the fly during the query and is not part of the aggregate state, so if someone access it, also if it is mutable, the aggregate is safe.
In the end, get and set methods are seen as an ugly thing if you are a ddd extremist, but sometimes they can also be useful being a standard naming convention and some libraries work on this naming convention, so I don't see them bad, if they don't break the aggregate/entity responsibilities.
As last thing, when you say In situation when we would like to operate on multiple Entities we introduce Service., this is true, but also a service should operate (mutate, save) on a single aggregate, but this is another topic 😊.

Related

is it acceptable to provide an API that is undefined a large part of the time?

Given some type as follows:
class Thing {
getInfo();
isRemoteThing();
getRemoteLocation();
}
The getRemoteLocation() method only has a defined result if isRemoteThing() returns true. Given that most Things are not remote, is this an acceptable API? The other option I see is to provide a RemoteThing subclass, but then the user needs a way to cast a Thing to a RemoteThing if necessary, which just seems to add a level of indirection to the problem.
Having an interface include members which are usable on some objects that implement the interface but not all of them, and also includes a query method to say which interface members will be useful, is a good pattern in cases where something is gained by it.
Examples of reasons where it can be useful:
If it's likely than an interface member will be useful on some objects but not other instances of the same type, this pattern may be the only one that makes sense.
If it's likely that a consumer may hold references to a variety of objects implementing the interface, some of which support a particular member and some of which do not, and if it's likely that someone with such a collection would want to use the member on those instances which support it, such usage will be more convenient if all objects implement an interface including the member, than if some do and some don't. This is especially true for interface members like IDisposable.Dispose whose purpose is to notify the implementation of something it may or may not care about (e.g. that nobody needs it anymore and it may be abandoned without further notice), and ask it to do whatever it needs to as a consequence (in many cases nothing). Blindly calling Dispose on an IEnumerable<T> is faster than checking whether an implementation of IEnumerable also implements IDisposable. Not only the unconditional call faster than checking for IDisposable and then calling it--it's faster than checking whether an object implements IDisposable and finding out that it doesn't.
In some cases, a consumer may use a field to hold different kinds of things at different times. As an example, it may be useful to have a field which at some times will hold the only extant reference to a mutable object, and at other times will hold a possibly-shared reference to an immutable object. If the type of the field includes mutating methods (which may or may not work) as well as a means of creating a new mutable instance with data copied from an immutable one, code which receives an object and might want to mutate the data can store a reference to the passed-in object. If and when it wants to mutate the data, it can overwrite the field with a reference to a mutable copy; if it never ends up having to mutate the data, however, it can simply use the passed-in immutable object and never bother copying it.
The biggest disadvantage of having interfaces include members that aren't always useful is that it imposes more work on the implementers. Thus, people writing interfaces should only include members whose existence could significantly benefit at least some consumers of almost every class implementing the interface.
Why should this not be acceptable? It should, however, be clearly documented. If you look at the .net class libraries or the JDK, there are collection interfaces defining methods to add or delete items, but there are unmodifiable classes implementing these interfaces. It is a good idea in this case - as you did - to provide a method to query the object if it has some capabilities, as this helps you avoid exceptions in the case that the method is not appropriate.
OTOH, if this is an API, it might be more appropriate to use an interface than a class.

Does MVC break encapsulation?

Let's say I have an class to model a city. Its characteristics are the following:
It has only two properties "name" and "population", both private, that are set in the constructor.
It has getters for these properties, but not setters.
I don't want any user of this class to set the properties, I want them to use a public .edit() method.
This method needs opens up a form to input the new name of the city and population, i.e.: a view. Then, if I have a view, I would like to implement the MVC pattern, so the idea would be that the controller receives the .edit() call, renders the view, retrieves the data back, and sends it to the view so that it changes its state.
But, if I do so, I have to change the properties of the city model from private to public. So, if any user instantiates my class, she/he can directly change the properties.
So, the philosophical question: Isn't that breaking the encapsulation?
EDIT Just to make it more explicit:
This city_instance.edit() method should be the only way to mutate the object.
Besides, I see that part of my problems comes from the misunderstanding that a model is an object (you can read that on php mvc frameworks), when it is actually a different abstraction, it's a layer that groups the business logic (domain objects + I guess more things)
Disclaimer: I don't really understand where are you proposing the .edit() method to be implemented, so it would help if you could clarify that a little bit there.
The first thing to consider here is that in the bulleted list of your question you seem to imply that a City instance acts like an immutable object: it takes its instance variables in the constructor and doesn't allow anybody in the outside to change them. However, you later state that you actually want to create a way to visually edit a City instance. This two requirements are clearly going to create some tension, since they are kind of opposites.
If you go the MVC approach, by separating the view from the model you have two main choices:
Treat your City objects as immutable and, instead of editing an instance when the values are changed in the form, throw away the original object and create a new one.
Provide a way to mutate an existing City instance.
The first approach keeps your model intact if you actually consider a City as an immutable object. For the second one there are many different ways to go:
The most standard way is to provide, in the City class, a mutator. This can have the shape of independent setters for each property or a common message (I think this is the .edit() method you mentioned) to alter many properties at once by taking an array. Note that here you don't take a form object as a parameter, since models should not be aware of the views. If you want your view to take note of internal changes in the model, you use the Observer pattern.
Use "friend" classes for controllers. Some languages allow for friend classes to access an object's internals. In this case you could create a controller that is a friend class of your model that can make the connection between the model and the view without having to add mutators to your model.
Use reflection to accomplish something similar to the friend classes.
The first of this three approaches is the only language agnostic choice. Whether that breaks encapsulation or not is kind of difficult to say, since the requirements themselves would be conflicting (It would basically mean wanting to have a model separated from the view that can be altered by the user but that doesn't allow the model itself to be changed for the outside). I would however agree that separating the model from the view promotes having an explicit mutation mechanism if you want mutable instances.
HTH
NOTE: I'm referring to MVC as it applies to Web applications. MVC can apply to many kinds of apps, and it's implemented in many kinds of ways, so it's really hard to say MVC does or does not do any specific thing unless you are talking strictly about something defined by the pattern, and not a particular implementation.
I think you have a very specific view of what "encapsulation" is, and that view does not agree with the textbook definition of encapsulation, nor does it agree with the common usage of it. There is no definition of "Encapsulation" I can find that requires that there be no setters. In fact, since Setters are in and of themselves methods that be used to "edit" the object, it's kind of a silly argument.
From the Wikipedia entry (note where it says "like getter and setter"):
In general, encapsulation is one of the four fundamentals of OOP (object-oriented programming). Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Now, that's not to say that MVC doesn't break encapsulation, I'm just saying that your idea of what Encapsulation is is very specific and not particularly canonical.
Certainly, there are a number of problems that using Getters and Setters can cause, such as returning lists that you can then change directly outside of the object itself. You have to be careful (if you care) to keep your data hidden. You can also replace a collection with another collection, which is probably not what you intend.
The Law of Demeter is more relevant here than anything else.
But all of this is really just a red herring anyways. MVC is only about the GUI, and the GUI should be as simple as possible. It should have almost no logic in either the view or the controller. You should be using simple view models to deserialize your form data into a simple structure, which can the be used to apply to any business architecture you like (if you don't want setters, then create your business layer with objects that don't use setters and use mutattors.).
There is little need for complex architecture in the UI layer. The UI layer is more of a boundary and gateway that translates the flat form and command nature of HTTP to whatever business object model you choose. As such, it's not going to be purely OO at the UI level, because HTTP isn't.
This is called an Impedance Mismatch, which is often associated with ORM's, because Object models do not map easily to relational models. The same is true of HTTP to Business objects. You can think of MVC as a corollary to an ORM in that respect.

Correct OOP design without getters?

I recently read that getters/setters are evil and I have to say it makes sense, yet when I started learning OOP one of the first things I learned was "Encapsulate your fields" so I learned to create class give it some fields, create getters, setters for them and create constructor where I initialize these fields. And every time some other class needs to manipulate this object (or for instance display it) I pass it the object and it manipulate it using getters/setters. I can see problems with this approach.
But how to do it right? For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument? Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
Can you suggest some good resources where best practices in OOP design are presented? I'm planning to start a project in my spare time and I want it to be my learning project in correct OOP design..
Allen Holub made a big splash with "Why getter and setter methods are evil" back in 2003.
It's great that you've found and read the article. I admire anybody who's learning and thinking critically about what they're doing.
But take Mr. Holub with a grain of salt.
This is one view that got a lot of attention for its extreme position and the use of the word "evil", but it hasn't set the world on fire or been generally accepted as dogma.
Look at C#: they actually added syntactic sugar to the language to make get/set operations easier to write. Either this confirms someone's view of Microsoft as an evil empire or contradicts Mr. Holub's statement.
The fact is that people write objects so that clients can manipulate state. It doesn't mean that every object written that way is wrong, evil, or unworkable.
The extreme view is not practical.
"Encapsulate your fields" so I learned to create class give it some fields, create getters, setters
Python folks do not do this. Yet, they are still doing OO programming. Clearly, fussy getters and setters aren't essential.
They're common, because of limitations in C++ and Java. But they don't seem to be essential.
Python folks use properties sometimes to create a getter and setter functions that look like a simple attribute.
The point is that "Encapsulation" is a Design strategy. It has little or nothing to do with the implementation. You can have all public attributes, and still a nicely encapsulated design.
Also note that many people worry about "someone else" who "violates" the design by directly accessing attributes. I suppose this could happen, but then the class would stop working correctly.
In C++ (and Java) where you cannot see the source, it can be hard to understand the interface, so you need lots of hints. private methods, explicit getters and setters, etc.
In Python, where you can see all the source, it's trivial to understand the interface. We don't need to provide so many hints. As we say "Use the source, Luke" and "We're all adults here." We're all able to see the source, we don't need to be fussy about piling on getters and setters to provide yet more hints as to how the API works.
For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument?
Good idea.
Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
That's why the Render object is separate. Your design is quite nice.
No reason why a Person object can't call a general-purpose renderer and still have a narrow set of responsibilities. After all the Person object is responsible for the attributes, and passing those attributes to a Renderer is well within it's responsibilities.
If it's truly a problem (and it can be in some applications), you can introduce Helper classes. So the PersonRenderer class does Rendering of Person data. That way a change to Person also requires changes to PersonRenderer -- and nothing else. This is the Data Access Object design pattern.
Some folks will make the Render an internal class, contained within Person, so it's Person.PersonRenderer to enforce some more serious containment.
If you have getters and setters, you don't have encapsulation. And they are not necessary. Consider the std::string class. This has quite a complicated internal representation, yet has no getters or setters, and only one element of the representation is (probably) exposed simply by returning its value (i.e. size()). That's the kind of thing you should be aiming for.
The basic concept of why they are considered to be evil is, that a class/object should export function and not state. The state of an object is made of its members. Getters and Setters let external users read/modify the state of an object without using any function.
Hence the idea, that except for DataTransferObjects for which you might have Getters and a constructor for setting the state, the members of an objects should only be modified by calling a functionality of an object.
Why do you think getters are evil? See a post with answers proving the opposite:
Purpose of private members in a class
IMHO it contains a lot of what can rightfully be called "OOP best practices".
Update: OK, reading the article you are referring to, I understand more clearly what the issue is. And it's a whole different story from what the provocative title of the article suggests. I haven't yet read the full article, but AFAIU the basic point is that one should not unnecessarily publish class fields via mindlessly added (or generated) getters and setters. And with this point I fully agree.
By designing carefully and focusing on what you must do rather than how
you'll do it, you eliminate the vast majority of getter/setter methods in
your program. Don't ask for the information you need to do the work;
ask the object that has the information to do the work for you.
So far so good. However, I don't agree that providing a getter like this
int getSomeField();
inherently compromises your class design. Well it does, if you haven't designed your class interface well. Then, of course, it might happen that you realize too late that the field should be a long rather than an int, and changing it would break 1000 places in client code. IMHO in such case the designer is to blame, not the poor getter.
In some languages, like C++, there's the concept of friend. Using this concept you can make implementation details of a class visible to only a subset of other classes (or even functions). When you use Get/Set indiscriminately you give everyone access to everything.
When used sparingly friend is an excellent way of increasing encapsulation.
Assume you have many entity classes in your designs, and suppose they have a base class like Data. Adding different getter and setter methods for concrete implementations will pollute the client code that uses these entities like lots of dynamic_casts, to call required getter and setter methods.
Therefore, getter and setter methods may remain where they are, but you should protected client code. My recommendation would be to apply Visitor pattern or data collector for these cases.
In other words, ask yourself why do I need these accessor methods, how do I manipulate these entities? And then apply these manipulations in Visitor classes to keep client code clean, also extend the functionality of entity classes without polluting their code.
In the following paper concerning endotesting you'll find a pattern to avoid getters (in some circumstances) using what the author calls 'smart handlers'. It has a lot in common with how Holub approaches avoiding some getters.
http://www.mockobjects.com/files/endotesting.pdf
Anything that is public is part of the API of the class. Changing these parts may break other stuff, relying on that. A public field, that is not only connected with an API, but with internal representation, can be risky. Example: You save data in a field as an array. This array is public, so the data can be changed from other classes. Later you decide to switch to a generic List. Code that use this field as an array is broken.

Should entities have behavior or not?

Should entities have behavior? or not?
Why or why not?
If not, does that violate Encapsulation?
If your entities do not have behavior, then you are not writing object-oriented code. If everything is done with getters and setters and no other behavior, you're writing procedural code.
A lot of shops say they're practicing SOA when they keep their entities dumb. Their justification is that the data structure rarely changes, but the business logic does. This is a fallacy. There are plenty of patterns to deal with this problem, and they don't involve reducing everything to bags of getters and setters.
Entities should not have behavior. They represent data and data itself is passive.
I am currently working on a legacy project that has included behavior in entities and it is a nightmare, code that no one wants to touch.
You can read more on my blog post: Object-Oriented Anti-Pattern - Data Objects with Behavior .
[Preview] Object-Oriented Anti-Pattern - Data Objects with Behavior:
Attributes and Behavior
Objects are made up of attributes and behavior but Data Objects by definition represent only data and hence can have only attributes. Books, Movies, Files, even IO Streams do not have behavior. A book has a title but it does not know how to read. A movie has actors but it does not know how to play. A file has content but it does not know how to delete. A stream has content but it does not know how to open/close or stop. These are all examples of Data Objects that have attributes but do not have behavior. As such, they should be treated as dumb data objects and we as software engineers should not force behavior upon them.
Passing Around Data Instead of Behavior
Data Objects are moved around through different execution environments but behavior should be encapsulated and is usually pertinent only to one environment. In any application data is passed around, parsed, manipulated, persisted, retrieved, serialized, deserialized, and so on. An entity for example usually passes from the hibernate layer, to the service layer, to the frontend layer, and back again. In a distributed system it might pass through several pipes, queues, caches and end up in a new execution context. Attributes can apply to all three layers, but particular behavior such as save, parse, serialize only make sense in individual layers. Therefore, adding behavior to data objects violates encapsulation, modularization and even security principles.
Code written like this:
book.Write();
book.Print();
book.Publish();
book.Buy();
book.Open();
book.Read();
book.Highlight();
book.Bookmark();
book.GetRelatedBooks();
can be refactored like so:
Book book = author.WriteBook();
printer.Print(book);
publisher.Publish(book);
customer.Buy(book);
reader = new BookReader();
reader.Open(Book);
reader.Read();
reader.Highlight();
reader.Bookmark();
librarian.GetRelatedBooks(book);
What a difference natural object-oriented modeling can make! We went from a single monstrous Book class to six separate classes, each of them responsible for their own individual behavior.
This makes the code:
easier to read and understand because it is more natural
easier to update because the functionality is contained in smaller encapsulated classes
more flexible because we can easily substitute one or more of the six individual classes with overridden versions.
easier to test because the functionality is separated, and easier to mock
It depends on what kind of entity they are -- but the term "entity" implies, to me at least, business entities, in which case they should have behavior.
A "Business Entity" is a modeling of a real world object, and it should encapsulate all of the business logic (behavior) and properties/data that the object representation has in the context of your software.
If you're strictly following MVC, your model (entities) won't have any inherent behavior. I do however include whatever helper methods allow the easiest management of the entities persistence, including methods that help with maintaining its relationship to other entities.
If you plan on exposing your entities to the world, you're better off (generally) keeping behavior off of the entity. If you want to centralize your business operations (i.e. ValidateVendorOrder) you wouldn't want the Order to have an IsValid() method that runs some logic to validate itself. You don't want that code running on a client (what if they fudge it. i.e. akin to not providing any client UI to set the price on an item being placed in a shopping cart, but posting a a bogus price on the URL. If you don't have server-side validation, that's not good! And duplicating that validation is...redundant...DRY (Don't Repeat Yourself).
Another example of when having behaviors on an entity just doesn't work is the notion of lazy loading. Alot of ORMs today will allow you to lazy load data when a property is accessed on an entities. If you're building a 3-tier app, this just doesn't work as your client will ultimately inadvertantly try to make database calls when accessing properties.
These are my off-the-top-of-my-head arguments for keeping behavior off of entities.

Dealing with "global" data structures in an object-oriented world

This is a question with many answers - I am interested in knowing what others consider to be "best practice".
Consider the following situation: you have an object-oriented program that contains one or more data structures that are needed by many different classes. How do you make these data structures accessible?
You can explicitly pass references around, for example, in the constructors. This is the "proper" solution, but it means duplicating parameters and instance variables all over the program. This makes changes or additions to the global data difficult.
You can put all of the data structures inside of a single object, and pass around references to this object. This can either be an object created just for this purpose, or it could be the "main" object of your program. This simplifies the problems of (1), but the data structures may or may not have anything to do with one another, and collecting them together in a single object is pretty arbitrary.
You can make the data structures "static". This lets you reference them directly from other classes, without having to pass around references. This entirely avoids the disadvantages of (1), but is clearly not OO. This also means that there can only ever be a single instance of the program.
When there are a lot of data structures, all required by a lot of classes, I tend to use (2). This is a compromise between OO-purity and practicality. What do other folks do? (For what it's worth, I mostly come from the Java world, but this discussion is applicable to any OO language.)
Global data isn't as bad as many OO purists claim!
After all, when implementing OO classes you've usually using an API to your OS. What the heck is this if it isn't a huge pile of global data and services!
If you use some global stuff in your program, you're merely extending this huge environment your class implementation can already see of the OS with a bit of data that is domain specific to your app.
Passing pointers/references everywhere is often taught in OO courses and books, academically it sounds nice. Pragmatically, it is often the thing to do, but it is misguided to follow this rule blindly and absolutely. For a decent sized program, you can end up with a pile of references being passed all over the place and it can result in completely unnecessary drudgery work.
Globally accessible services/data providers (abstracted away behind a nice interface obviously) are pretty much a must in a decent sized app.
I must really really discourage you from using option 3 - making the data static. I've worked on several projects where the early developers made some core data static, only to later realise they did need to run two copies of the program - and incurred a huge amount of work making the data non-static and carefully putting in references into everything.
So in my experience, if you do 3), you will eventually end up doing 1) at twice the cost.
Go for 1, and be fine-grained about what data structures you reference from each object. Don't use "context objects", just pass in precisely the data needed. Yes, it makes the code more complicated, but on the plus side, it makes it clearer - the fact that a FwurzleDigestionListener is holding a reference to both a Fwurzle and a DigestionTract immediately gives the reader an idea about its purpose.
And by definition, if the data format changes, so will the classes that operate on it, so you have to change them anyway.
You might want to think about altering the requirement that lots of objects need to know about the same data structures. One reason there does not seem to be a clean OO way of sharing data is that sharing data is not very object-oriented.
You will need to look at the specifics of your application but the general idea is to have one object responsible for the shared data which provides services to the other objects based on the data encapsulated in it. However these services should not involve giving other objects the data structures - merely giving other objects the pieces of information they need to meet their responsibilites and performing mutations on the data structures internally.
I tend to use 3) and be very careful about the synchronisation and locking across threads. I agree it is less OO, but then you confess to having global data, which is very un-OO in the first place.
Don't get too hung up on whether you are sticking purely to one programming methodology or another, find a solution which fits your problem. I think there are perfectly valid contexts for singletons (Logging for instance).
I use a combination of having one global object and passing interfaces in via constructors.
From the one main global object (usually named after what your program is called or does) you can start up other globals (maybe that have their own threads). This lets you control the setting up of program objects in the main objects constructor and tearing them down again in the right order when the application stops in this main objects destructor. Using static classes directly makes it tricky to initialize/uninitialize any resources these classes use in a controlled manner. This main global object also has properties for getting at the interfaces of different sub-systems of your application that various objects may want to get hold of to do their work.
I also pass references to relevant data-structures into constructors of some objects where I feel it is useful to isolate those objects from the rest of the world within the program when they only need to be concerned with a small part of it.
Whether an object grabs the global object and navigates its properties to get the interfaces it wants or gets passed the interfaces it uses via its constructor is a matter of taste and intuition. Any object you're implementing that you think might be reused in some other project should definately be passed data structures it should use via its constructor. Objects that grab the global object should be more to do with the infrastructure of your application.
Objects that receive interfaces they use via the constructor are probably easier to unit-test because you can feed them a mock interface, and tickle their methods to make sure they return the right arguments or interact with mock interfaces correctly. To test objects that access the main global object, you have to mock up the main global object so that when they request interfaces (I often call these services) from it they get appropriate mock objects and can be tested against them.
I prefer using the singleton pattern as described in the GoF book for these situations. A singleton is not the same as either of the three options described in the question. The constructor is private (or protected) so that it cannot be used just anywhere. You use a get() function (or whatever you prefer to call it) to obtain an instance. However, the architecture of the singleton class guarantees that each call to get() returns the same instance.
We should take care not to confuse Object Oriented Design with Object Oriented Implementation. Al too often, the term OO Design is used to judge an implementation, just as, imho, it is here.
Design
If in your design you see a lot of objects having a reference to exactly the same object, that means a lot of arrows. The designer should feel an itch here. He should verify whether this object is just commonly used, or if it is really a utility (e.g. a COM factory, a registry of some kind, ...).
From the project's requirements, he can see if it really needs to be a singleton (e.g. 'The Internet'), or if the object is shared because it's too general or too expensive or whatsoever.
Implementation
When you are asked to implement an OO Design in an OO language, you face a lot of decisions, like the one you mentioned: how should I implement all the arrows to the oft used object in the design?
That's the point where questions are addressed about 'static member', 'global variable' , 'god class' and 'a-lot-of-function-arguments'.
The Design phase should have clarified if the object needs to be a singleton or not. The implementation phase will decide on how this singleness will be represented in the program.
Option 3) while not purist OO, tends to be the most reasonable solution. But I would not make your class a singleton; and use some other object as a static 'dictionary' to manage those shared resources.
I don't like any of your proposed solutions:
You are passing around a bunch of "context" objects - the things that use them don't specify what fields or pieces of data they are really interested in
See here for a description of the God Object pattern. This is the worst of all worlds
Simply do not ever use Singleton objects for anything. You seem to have identified a few of the potential problems yourself