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

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.

Related

Service access Entity attributes

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 😊.

Why does COM interface return different values for same invoking method?

When I invoke a method on a COM interface that returns another interface, the punkVal is different each time.
Yet if I use the old punkVal's to invoke that interfaces methods, it too works. It seems like a lot of unnecessary objects(or probably pointers to objects) are being created but I need someway to determine if the returned interface is unique. All I know is that I invoke is returning an interface(punkVal) and the value is different every instance. The value pointed by that value is always the same, but I think it is because it points to the vtable or something, doesn't seem to be a reliable check. That, or even seemingly disparate interfaces are all actually the same interface.
To be clear:
someCOMInterface foo();
I call invoke on foo and expect punkVal to be someCOMInterface, which I must later on query to call it's methods using invoke. But each time I call the first invoke I get a different someCOMInterface(the "same" but "different" in that the value returned by invoke).
This isn't uncommon. It is entirely up to the developer of the COM library whether interface pointers returned from multiple calls to the same method will return the same pointer or not.
One of the reasons that different pointers may be returned is that the core object model used within a specific COM library may not be COM. I have, for example, written object models in C++ using things like shared_ptr, which arguably yields a better object model for C++ clients. But when I expose my C++ object model for interoperability (or, more generally, expose it as a DLL), COM is often a better choice. Since keeping an complex, hierarchical object model in sync with a set of wrapper classes can be difficult, wrapper objects may just be temporary -- created as necessary and destroyed whenever clients no longer use them.
In these circumstances, the client may still need to know that the objects are "equal" -- two different objects that wrap the same inner object can be considered "equal." To determine that, Microsoft defines the IObjectEquality interface. This interface may be implemented by COM wrapper classes so that a client can explicitly check if two non-equal pointers are conceptually "equal" objects. The objects you're using may or may not implement this interface. This blog post shows a complete example of determining object equality using this interface.
If IObjectEquality is not implemented, it is up to the developer of the COM object to provide some means of making such a determination, usually by providing some sort of Name or ID or other identifying property. For example, Excel's Application.Range property will return different pointers from subsequent calls with the same arguments. To determine if two ranges are equal, you can use the Range.Address method to get an "identifier" of that range, and then compare those identifiers.

Where to not use IDisposable implementation?

My question is specific to, why and where not to implement IDisposable interface.
If I am not using & consuming any unmanaged resources, still is it good practice to implement IDisposable interface.
What are the advantages or disadvantages if I do it? or is it good practice to implement it?
Please advise.
You implement IDisposable for one of two reasons:
If you have Unmanaged resources to free.
You do this because this is the only way for the GC to know how to free unmanaged resources which otherwise it doesnt know about. This is about WHAT resources to free. This case is actually quite rare - more often than not you access unmanaged resources through existing managed objects. This case requires a full "official recommended" implementation. Generally you should wrap unmanaged resources in their own separate (managed) class that does the IDisposable implimentation (rather than including unmanaged resources in other larger objects).
If your class contains objects that impliment IDisposable.
You do this not because the objects won't get free if you don't (they will) but because you want to be able to control WHEN those resources are freed. Having a dispose impliementation that disposes disposable members of a class means that consumer can apply a using statement to easily control WHEN resources are freed. In pratice more often than not this is the main reason for implementing IDisposable. Note that if your class is sealed you can get away with a mimimal IDisposable implementation here - I.e just Dispose - there is no need for the full blown "official recommended' implimenation.
It follows that if neither of these cases applies then no need to implement.
If a class implements IDisposable, that will generally impart to any code which creates instances of that class a responsibility to ensure that Dispose gets called on that instance before it is abandoned; it may fulfill this responsibility either by calling Dispose on the object itself when it is no longer needed, or by making sure that some other object that receives a reference accepts "ownership" and responsibility for it. In the majority of cases, when code is written correctly, each IDisposable object upon which Dispose has not yet been called, will at every point in time, have exactly one other entity (object or execution scope) which "owns" it. During the lifetime of the IDisposable object, ownership may get passed among different entities, but when one object receives ownership the former object should relinquish it.
In many cases, objects will be used in such a fashion that tracking ownership is not difficult. Generally, any object whose state is ever going to be modified should have exactly one owner and that owner will know when the object is no longer needed. Additionally, because modification of the owned object's state would constitute modification of the owner's state, the owner itself should have a single owner. In such cases, requiring the owner to call Dispose will not pose any difficulty (the owner's owner should call Dispose on it). There is, however, a 'gotcha' with this principle: it's possible for an object to create an instance of a mutable class but never mutate it nor allow anyone else to do so. If the mutable class in question simply holds values and does not implement IDisposable, objects which hold references to the things that will never actually mutate need not concern themselves with ownership. This can allow some major simplifications, since it will be possible for many objects to hold references to the non-changing object and not have to worry about which of them will use it last. If, however, the mutable class in question implements IDisposable, such simplifications are no longer possible.

Reasons to use private instead of protected for fields and methods

This is a rather basic OO question, but one that's been bugging me for some time.
I tend to avoid using the 'private' visibility modifier for my fields and methods in favor of protected.
This is because, generally, I don't see any use in hiding the implementation between base class and child class, except when I want to set specific guidelines for the extension of my classes (i.e. in frameworks). For the majority of cases I think trying to limit how my class will be extended either by me or by other users is not beneficial.
But, for the majority of people, the private modifier is usually the default choice when defining a non-public field/method.
So, can you list use cases for private? Is there a major reason for always using private? Or do you also think it's overused?
There is some consensus that one should prefer composition over inheritance in OOP. There are several reasons for this (google if you're interested), but the main part is that:
inheritance is seldom the best tool and is not as flexible as other solutions
the protected members/fields form an interface towards your subclasses
interfaces (and assumptions about their future use) are tricky to get right and document properly
Therefore, if you choose to make your class inheritable, you should do so conciously and with all the pros and cons in mind.
Hence, it's better not to make the class inheritable and instead make sure it's as flexible as possible (and no more) by using other means.
This is mostly obvious in larger frameworks where your class's usage is beyond your control. For your own little app, you won't notice this as much, but it (inheritance-by-default) will bite you in the behind sooner or later if you're not careful.
Alternatives
Composition means that you'd expose customizability through explicit (fully abstract) interfaces (virtual or template-based).
So, instead of having an Vehicle base class with a virtual drive() function (along with everything else, such as an integer for price, etc.), you'd have a Vehicle class taking a Motor interface object, and that Motor interface only exposes the drive() function. Now you can add and re-use any sort of motor anywhere (more or less. :).
There are two situations where it matters whether a member is protected or private:
If a derived class could benefit from using a member, making the member `protected` would allow it to do so, while making it `private` would deny it that benefit.
If a future version of the base class could benefit by not having the member behave as it does in the present version, making the member `private` would allow that future version to change the behavior (or eliminate the member entirely), while making it `protected` would require all future versions of the class to keep the same behavior, thus denying them the benefit that could be reaped from changing it.
If one can imagine a realistic scenario where a derived class might benefit from being able to access the member, and cannot imagine a scenario where the base class might benefit from changing its behavior, then the member should be protected [assuming, of course, that it shouldn't be public]. If one cannot imagine a scenario where a derived class would get much benefit from accessing the member directly, but one can imagine scenarios where a future version of the base class might benefit by changing it, then it should be private. Those cases are pretty clear and straightforward.
If there isn't any plausible scenario where the base class would benefit from changing the member, I would suggest that one should lean toward making it protected. Some would say the "YAGNI" (You Ain't Gonna Need It) principle favors private, but I disagree. If you're is expecting others to inherit the class, making a member private doesn't assume "YAGNI", but rather "HAGNI" (He's Not Gonna Need It). Unless "you" are going to need to change the behavior of the item in a future version of the class, "you" ain't gonna need it to be private. By contrast, in many cases you'll have no way of predicting what consumers of your class might need. That doesn't mean one should make members protected without first trying to identify ways one might benefit from changing them, since YAGNI isn't really applicable to either decision. YAGNI applies in cases where it will be possible to deal with a future need if and when it is encountered, so there's no need to deal with it now. A decision to make a member of a class which is given to other programmers private or protected implies a decision as to which type of potential future need will be provided for, and will make it difficult to provide for the other.
Sometimes both scenarios will be plausible, in which case it may be helpful to offer two classes--one of which exposes the members in question and a class derived from that which does not (there's no standard idiomatic was for a derived class to hide members inherited from its parent, though declaring new members which have the same names but no compilable functionality and are marked with an Obsolete attribute would have that effect). As an example of the trade-offs involved, consider List<T>. If the type exposed the backing array as a protected member, it would be possible to define a derived type CompareExchangeableList<T> where T:Class which included a member T CompareExchangeItem(index, T T newValue, T oldvalue) which would return Interlocked.CompareExchange(_backingArray[index], newValue, oldValue); such a type could be used by any code which expected a List<T>, but code which knew the instance was a CompareExchangeableList<T> could use the CompareExchangeItem on it. Unfortunately, because List<T> does not expose the backing array to derived classes, it is impossible to define a type which allows CompareExchange on list items but which would still be useable by code expecting a List<T>.
Still, that's not to imply that exposing the backing array would have been completely without cost; even though all extant implementations of List<T> use a single backing array, Microsoft might implement future versions to use multiple arrays when a list would otherwise grow beyond 84K, so as to avoid the inefficiencies associated with the Large Object Heap. If the backing array was exposed as protected member, it would be impossible to implement such a change without breaking any code that relied upon that member.
Actually, the ideal thing might have been to balance those interests by providing a protected member which, given a list-item index, will return an array segment which contains the indicated item. If there's only one array, the method would always return a reference to that array, with an offset of zero, a starting subscript of zero, and a length equal to the list length. If a future version of List<T> split the array into multiple pieces, the method could allow derived classes to efficiently access segments of the array in ways that would not be possible without such access [e.g. using Array.Copy] but List<T> could change the way it manages its backing store without breaking properly-written derived classes. Improperly-written derived classes could get broken if the base implementation changes, but that's the fault of the derived class, not the base.
I just prefer private than protected in the default case because I'm following the principle to hide as much as possibility and that's why set the visibility as low as possible.
I am reaching here. However, I think that the use of Protected member variables should be made conciously, because you not only plan to inherit, but also because there is a solid reason derived classed shouldn't use the Property Setters/Getters defined on the base class.
In OOP, we "encapsulate" the member fields so that we can excercise control over how they properties the represent are accessed and changed. When we define a getter/setter on our base for a member variable, we are essentially saying that THIS is how I want this variable to be referenced/used.
While there are design-driven exceptions in which one might need to alter the behavior created in the base class getter/setter methods, it seems to me that this would be a decision made after careful consideration of alternatives.
For Example, when I find myself needing to access a member field from a derived class directly, instead of through the getter/setter, I start thinking maybe that particular Property should be defined as abstract, or even moved to the derived class. This depends upon how broad the hierarchy is, and any number of additional considerations. But to me, stepping around the public Property defined on the base class begins to smell.
Of course, in many cases, it "doesn't matter" because we are not implementing anything within the getter/setter beyond access to the variable. But again, if this is the case, the derived class can just as easily access through the getter/setter. This also protects against hard-to-find bugs later, if employed consistently. If the behgavior of the getter/setter for a member field on the base class is changed in some way, and a derived class references the Protected field directly, there is the potential for trouble.
You are on the right track. You make something private, because your implementation is dependant on it not being changed either by a user or descendant.
I default to private and then make a conscious decision about whether and how much of the inner workings I'm going to expose, you seem to work on the basis, that it will be exposed anyway, so get on with it. As long as we both remember to cross all the eyes and dot all the tees, we are good.
Another way to look at it is this.
If you make it private, some one might not be able to do what they want with your implementation.
If you don't make it private, someone may be able to do something you really don't want them to do with your implementation.
I've been programming OOP since C++ in 1993 and Java in 1995. Time and again I've seen a need to augment or revise a class, typically adding extra functionality tightly integrated with the class. The OOP way to do so is to subclass the base class and make the changes in the subclass. For example a base class field originally referred to only elsewhere in the base class is needed for some other action, or some other activity must change a value of the field (or one of the field's contained members). If that field is private in the base class then the subclass cannot access it, cannot extend the functionality. If the field is protected it can do so.
Subclasses have a special relationship to the base class that other classes elsewhere in the class hierarchy don't have: they inherit the base class members. The purpose of inheritance is to access base class members; private thwarts inheritance. How is the base class developer supposed to know that no subclasses will ever need to access a member? In some cases that can be clear, but private should be the exception rather than the rule. Developers subclassing the base class have the base class source code, so their alternative is to revise the base class directly (perhaps just changing private status to protected before subclassing). That's not clean, good practice, but that's what private makes you do.
I am a beginner at OOP but have been around since the first articles in ACM and IEEE. From what I remember, this style of development was more for modelling something. In the real world, things including processes and operations would have "private, protected, and public" elements. So to be true to the object .....
Out side of modelling something, programming is more about solving a problem. The issue of "private, protected, and public" elements is only a concern when it relates to making a reliable solution. As a problem solver, I would not make the mistake of getting cough up in how others are using MY solution to solve their own problems. Now keep in mind that a main reason for the issue of ...., was to allow a place for data checking (i.e., verifying the data is in a valid range and structure before using it in your object).
With that in mind, if your code solves the problem it was designed for, you have done your job. If others need your solution to solve the same or a simular problem - Well, do you really need to control how they do it. I would say, "only if you are getting some benefit for it or you know the weaknesses in your design, so you need to protect some things."
In my idea, if you are using DI (Dependency Injection) in your project and you are using it to inject some interfaces in your class (by constructor) to use them in your code, then they should be protected, cause usually these types of classes are more like services not data keepers.
But if you want to use attributes to save some data in your class, then privates would be better.

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