Dependency Inversion Principle And "String" - string

I know you can't create a program that adheres 100% to the Dependency Inversion Principle. All of us violate it by instantiation strings in our programs without thinking about it. Since String is a class and not a datatype, we always become dependent on a concrete class.
I was wondering if there are any solutions for this (purely theoretical speaking). Since String is pretty much a blackbox with very few 'leaks', and has a complex background algorithm, I don't expect an actual implementation ofcourse :)

The intent of the principle is not to avoid creating instances within a class, or to avoid using the "new" keyword. Therefore instantiating objects (or strings) does not violate the principle.
The principle is also not about always creating a higher-level abstraction (e.g. an interface or base class) in order to inject it and promote looser coupling. If an abstraction is already reasonable, there is no reason to try to improve on it. What benefit would you ever gain by swapping out the implementation of string?
I actually posted this question a few years ago (semi-relevant): IOC/DI: Is Registering a Concrete Type a Code Smell?
So what is the principle about? It's about writing components that are highly focused on their own responsibilities, and injecting components that are highly focused on their own responsibilities. These components are usually services when using a dependency injection framework and constructor injection, but can also be datatypes when doing other types of injection (e.g. method injection).
Note that there is no requirement for these services or datatypes to be interfaces or base classes--they can absolutely be concrete types without violating the principle.

Dependeny inversion is not about creation of object, its about high-level/low-level module dependency and who define the Domain (object and interface).
You are talking about dependency injection, a sub-part of the Inversion of Control principle.

Related

Where to put *serialization* in SOLID programming

I have business objects, that I would like to (de)serialize from and into a .yaml file.
Because I want the .yaml to be human readable, I need a certain degree of control over the serialize and deserialize methods.
Where should the serialization logic go?
A) If I teach every object, how to de/serialize itself, but that probably violates the single-responsibility-principle.
B) If I put it inside a common serialization module, that might violate the open-closed-principle, since more business objects will be added in the future. Also, changes to objects need now be performed in two places.
What is the SOLID approach to solve this conundrum for tiny-scale applications?
Usually in this kind of situation, you'll want the business objects to handle their own serialization. This doesn't necessarily violate the single responsibility principle, which asserts that each object should have one job and one boss. It just means that the one job includes serializability. The user owns the business object, and wants to be able to serialize it, so the requirement for serializability comes from the same place as those other requirements -- the user.
There are a couple danger areas, though. Firstly, do you really need to insist that the business object is serializable, or can you leave it up to the user to decide whether they are serializable or not? If you are imposing a serializability requirement, then there's a good chance that your are violating the SRP that way, because as you evolve the serialization system, you will be imposing your own requirements on the objects.
Second, you probably want to think long and hard about the interface the these objects use to serialize themselves. Does it have to be yaml? Why? Does it have to be to a file? Try not to impose requirements that are subject to change, because they depend on particular implementation decisions that you're making in the rest of the system. That ends up being a violation of SRP as well, because they those objects have to evolve according to requirements from 2 different sources. It's better if the objects themselves initiate their own serialization, and can choose the implementation to the greatest extent possible.

Normalization versus multiple inheritance

I have to model a situation where I would like to use specializations to ensure classes are somewhat normalized, but:
Risk multiple inheritance problems, especially in the long run
Will need to derive an XML-compliant UML model from it (a.o., only one superclass allowed)
The simplified situation is as follows (see also diagram below): we have Parts, like doors, bolts, wheels, etc., and Tools, like drills, ladders, and bigger machinery. All of these may be used in generic processes, like Orders, Shipments, etc. As such, I would like to have one superclass (Powertype, maybe?) that represents them, say Item.
Both Tools and Parts have specialized classes that carry a serial number. As such, I figured that a SerializedItem class with a SerialNumber, which both SerializedPart and SerializedTool inherit, would ensure that all serialized 'things' we have carry at least the same information. However, I also need these Serialized items to carry at least the same information as their more generic parts, and hence I would introduce multiple inheritance.
I have considered making the Item classes interfaces. This would at least mitigate some (many, all?) multiple inheritance problems. This is where another however comes in: aside from an attribute SerialNumber, I would also like to enforce that all Serialized specializations have an aggregation relation with a Manufacturer. Aggregation to an interface is not allowed, so I feel like I cannot with one relation to the superclass enforce this relation.
As such, I have the following considerations/problems:
Have two disjoint 'branches' of Item, with little to no technical governance on content of Serialized specializations
Item classes as Interfaces, but then little governance w.r.t. use of Manufacturer by Serialized specializations
All concrete classes, but then there exist multiple inheritance issues which must be solved when trying to derive XML classes from the model
Which option would you prefer, and why? Did I miss any considerations?
If you want to have a (platform-independent) information design model (similar in spirit to a conceptual model), then you should use multiple-inheritance if this reflects the concepts of your problem domain.
According to such a model-based engineering approach, your model is a pretty good design model that can be used as a basis for making (platform-specific) implementation models such as, e.g., a Java class model or an XML Schema model.
For making an XML Schema model, you would have to choose a certain mapping. In particular, you need to choose a mapping for resolving the multiple inheritance pattern, see also https://stackoverflow.com/a/27102169/2795909.
I just would not make SerializedItem a superclass. Nothing is a serialized thing which generalization would mean. Things can conform to a serialization protocol which is the same as implementing an interface (maybe called Serializable). If you happen to deal with serializable things without bothering about their content you would just deal with Serializable and only know the number.
Basically you should make your SerializedItem an interface (eventually renaming it to Serializable), remove the generalization upwards and make the two horizontal ones realizations.
This is probably not an ultima ratio. But to me this approach sounds more reasonable.

UML dependency reliationship

I can't find answer for my question . Is there a limit to how much dependency reliationship can be between two classes ? Does UML class-diagrams in general can't have more than one reliationship of the same type between two classes but they can have 2 or more reliationship of different types (for example between two classes they both can have composition and generalization reliantionship ?
You can have many associations between two classes, as well as many dependencies. You should stereotype those dependencies to differentiate them.
In general the UML specification does not restrict how many relationships of a specific type can be between the same classes, but due to the logic and meaning of a relationship you can assume some limitations.
Generalization, realization have a meaning where if there exists this relationship between two classes, it directly implies some consequences. Repeating the same relationship for the second time will have no further impact so it doesn't make any sense. It's also hard to specialize further those relationships through stereotypes.
Simple dependency provide some information that again cannot be "repeated" by having next dependency. Yet stereotyped dependency can bring more value and information so you can have more than one of dependency but with different stereotypes. Once you have one dependency of specific stereotype repeating the same one doesn't provide additional value, yet another dependency of different stereotype is a fully understandable and reasonable case. In theory the same dependency could be applied twice in two different directions, but I would then investigate deeply - it is usually showing that there is something wrong with the project.
Associations (including aggregation - both shared and composite) between two classes can have many different meanings. They should be differentiated either by association name, association roles, stereotype or by mixing those methods. So you can have multiple associations of the same "type" between the same two classes and they will have significant meaning. So many associations between the same classes are absolutely OK and it is a typical situation.
Mixing different relationships are also absolutely OK, however sometimes one relationship implies other. In general any (or almost any) relationship imply non-stereotyped dependency (in the same direction) so using it explicitly doesn't give any additional information or effect.
There is no limit to how many dependencies can be between two classes. But you have to consider a couple of important moments. On the website https://vaughnvernon.co of a principal architect Vaughn Vernon I have found interesting comments about usage of UML dependencies:
While dependency may have a broad meaning, it is best not to overuse
the dependency relationship. In an analysis model class diagram such
as a domain model diagram, you may be tempted to convey that all the
classes just depend on each other. Interestingly, however, the
Rational Unified Process (RUP) specifies that the general class
relationship that should be used in the analysis model is association,
and not dependency. Therefore, even when you are modeling higher-level
concepts it is best not to use the dependency relationship loosely. It
is just too nebulous.
Further, unless you use the dependency relationship in a constrained
manner your model consumers (yourself or other developers) will simply
have too broad an interpretation of its meaning. Generally those
filling architect and designer roles in a project are there to give
guidance to less experienced developers. Thus the dependency
relationship should be used to convey a specific kind of guidance from
architects and designers to developers.
So what should a dependency relationship represent? In our UML example
above the dependency means that class A uses class B, but that class A
does not contain an instance of class B as part of its own state. It
also means that if class B’s interface changes it will likely impact
class A and require it to change. I suggest that you constrain your
use of dependency relationships to non-state related concerns. You
would use dependency to indicate that, for example, class A receives
an instance of class B as a parameter to at least one of its methods.
You would also use dependency to indicate that class A creates an
instance of class B local to one of its methods. You
would not, however, use dependency to indicate that class A declares
an instance variable of class B, as that would indicate a
state-related concern. Again, use association to do that.

How to model a mixin in UML

What is the best way to represent a "mixin" using UML?
As documented in this article:
In object-oriented programming languages, a mixin refers to a defined
amount of functionality which can be added to a class. An important
aspect of this is that it makes it possible to concentrate more on the
properties of a particular behaviour than on the inheritance
structures during development.
I will give more details about my particular use case.
I have a collection of classes that model different types of objects. Because all of them can be stored on a storage, I want to use a mixin to implement all the functionality related to "being stored".
Of course, I can use abstract classes but I do not like it because these classes should be part of a different hierarchy of classes and the fact that they can be stored is only a secondary property.
Another option can be to use composition and add the "storage node" as a field of this classes. I do not like this option either for the same reason: I do not want to create any dependency between the classes and the storage.
I have already implemented the solution in Java using a mixin based on dynamic proxies and I would like to document the solution with a clear UML class diagram. Is there a standard way to represent this mixin?
I am also wondering whether it is a good idea to model also how the mixin has been implemented (using proxies) or it is better to use a more abstract representation.
Thanks
Actually there are many ways to model this in UML:
One approach could be to stereotype the operations and properties with <<mixin>> or the like and then use tagged values to describe where you got them from.
Another (I'd prefer) is to actually use a <<mixin>> stereotyped Generalization and attach a note to that telling which operations/properties should be mixed. That would give the implementer a guide to just "lean implementation of the general class".
Eventually you could create <<mixin>> sub-classes with subsets of the ops/props you want to mix in the final class and then Generalize from those.
Probably one could come up with more solutions. Use an approach which suits you best. There is not generic mixin pattern in UML (to my knowledge).

DDD domain services: what should a service class contain?

In Domain Driven Design, domain services should contain operations that do not naturally belong inside an entity.
I've had the habit to create one service per entity and group some methods inside it (Organization entity and OrganizationService service).
But the more I think about it: OrganizationService doesn't mean anything, "Organization" is not a service, it's a thing.
So right now I have to add a Organization deep copy functionality that will duplicate a whole Organization aggregate, so I want to put it in a service.
Should I do: OrganizationService::copyOrganization(o)?
Or should I do: OrganizationCopyService::copyOrganization(o)?
More generally: is a "service" an abstract concept containing several operations, or is a service a concrete operation?
Edit: more examples given the first one wasn't that good:
StrategyService::apply()/cancel() or StrategyApplicationService::apply()/cancel()? ("Application" here is not related to the application layer ;)
CarService::wash() or CarWashingService::wash()?
In all these examples the most specific service name seems the most appropriate. After all, in real life, "car washing service" is something that makes sense. But I may end up with a lot of services...
*Note: this is not a question about opinions! This is a precise, answerable question about the Domain Driven Design methodology. I'm always weary of close votes when asking "should I", but there is a DDD way of doing things.*
I think it's good if a domain service has only one method. But I don't think it is a rule like you must not have more than one method on a domain service or something. If the interface abstracts only one thing or one behaviour, it's certainly easy to maitain but the granularity of the domain service totally depends on your bounded context. Sometimes we focus on low coupling too much and neglect high cohesive.
This is a bit opinion based I wanted to add it as a comment but ran out space.
I believe that in this case it will make sense to group the methods into one a separate OrganizationFactory-service with different construction method.
interface OrganizationFactory{
Organization createOrganization();
Organization createOrganizationCopy(Organization organization);
}
I suppose it will be in accordance with information expert pattern and DRY principle - one class has all the information about specific object creation and I don't see any reason to repeat this logic in different places.
Nevertheless, an interesting thing is that in ddd definition of factory pattern
Shift the responsibility for creating instances of complex objects and
AGGREGATES to a separate object, which may itself have no
responsibility in the domain model but is still part of the domain
design. Provide an interface that encapsulates all complex assembly
and that does not require the client to reference the concrete classes
of the objects being instantiated.
the word "object" is in a generic sense doesn't even have to be a separate class but can also be a factory method(I mean both the method of a class and the pattern factory method) - later Evans gives an example of the factory method of Brokerage Account that creates instances of Trade Order.
The book references to the family of GoF factory patterns and I do not think that there's a special DDD way of factory decomposition - the main points are that the object created is not half-baked and that the factory method should add as few dependecies as possible.
update DDD is not attached to any particular programming paradigm, while the question is about object-oriented decomposition, so again I don't think that DDD can provide any special recommendations on the number of methods per object.
Some folks use strange rules of thumb, but I believe that you can just go with High Cohesion principle and put methods with highly related responsibilities together. As this is a DDD question, so I suppose it's about domain services(i.e. not infrastructure services). I suppose that the services should be divided according to their responsibilities in the domain.
update 2 Anyway CarService can do CarService::wash()/ CarService::repaint() / CarService::diagnoseAirConditioningProblems() but it will be strange that CarWashingService will do CarWashingService::diagnoseAirConditioningProblems() it's like in Chomsky's generative grammar - some statements(sentences) in the language make sense, some don't. But if your sentence contains too much subjects(more than say 5-7) it also will be difficult to understand, even if it is valid sentence in language.

Resources