Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am a C# programmer. Both at my last job and my current one, it is very common to create interfaces for most classes we write. E.g. when we have a class named Spork, we will add an interface ISpork that contains the public methods of Spork.These interfaces are used for dependency injection (e.g. via StructureMap) and for creating mocks in unit tests (e.g. with Rhino Mocks or Moq).
Some weeks ago I attended a talk by a Javs developer. We somehow got to talking about interfaces, and he seemed really surprised that anyone would have lots and lots of one-one-relations between classes and interfaces.
Now my questions: Have I been doing it wrong all the years? Or is this a Java vs C# thing? If it is, how are mocking and dependency injection handled in Java?
P.S.: I am mainly interested in the DI and mocking aspects and the related need (or not?) for lots of interfaces that have only one implementing class. I think the situation re. classes that are neither going to be mocked nor injected is quite similar. But I was surprised that something that seemed like a no-brainer to me as a C# developer was completely unheard of for that Java guy.
DI can be made with classes only without interfaces. You register the type, you inject the type. That's all. The difference comes when talking about mocks in unit tests. In c# you can mock only virtual or abstract (that are also virtual) members. Hence if you want your code to be testable you need to mark all public members with virtual keywords or use an interface instead of real class in your implementation. In Java all methods are virtual by default so they don't have this mess with one-to-one interfaces because they can mock everything.
Dependency injection is used to contain and separate concerns. You want to do something new in your code, you add a dependency interface that does that. You can then test your code without even bothering with the implementation of that interface until later on.
Your question, though, is about one on one relationship between interface and implementation. From my standpoint, that's irrelevant, since you care about the implementation only in the context of the interface you have already declared, not where it is used. You can have a class inheriting multiple injectable interfaces, for example, which is usually a sign that it has too many responsibilities, but it can be done. You can have multiple classes that inherit the same interface and then used based on DI configuration. There are even cases where the DI container handles stuff that I usually relegate to factories, mainly give you the implementation for an interface based on some parameters.
Either way, what does it matter? If (reducing to the absurd) there is one developer per class, then they will only write their code and their tests and define the interfaces of the dependencies needed, letting others implement them.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
I have a java class with 4 Maps in it. I want all those Map's to be singleton what is the best way in the following ways. if there is any other better way please suggest
making the class singleton and leaving the variables. That is making the constructor private and creating getInstance method.
making the class singleton and making the variables static. That is making the constructor private and creating getInstance method. making all the methods which deal with these 4 maps static
making class singleton, variables static and making each getmethod check if the map is null/size zero and if it is null/size zero calling the initalize method which will initalize all four maps. <issue here will be 4 maps will have 4 get methods and we need to call synchronized on the initalize method>
At first I recommend reading this question (well, its answer): What are drawbacks or disadvantages of singleton pattern? and this: What is dependency injection?
Singleton pattern is about object existing in a single instance, so that it can be used in multiple places. Problem is not with the concept of a singleton, but how it is frequently implemented (through some statically accessed field/method).
So, what you need is a singleton object, but without all the problems mentioned above.
Therefore in the class (which you want to be a singleton), just define all those maps as normal fields, add all the methods you need as well as its dependencies (that should be injected through constructor).
Once that class is defined, you just need to:
create single object of it
provide it to other objects (that needs access to it) when creating them (ideally through their constructor, or a setter method).
How to implement above two points depends on your application. You basically need a dependency injection system.
You can manually implement it, which basically means having a factory method that creates all singleton objects and wires them together).
If you use spring, then you can rely on its dependency injection capabilities (In this case you just annotate your singleton with #Component and inject to other components with #Autowired).
You can even setup dependency injection yourself using for instance https://github.com/google/guice
However, if it's your first contact with the concept of dependency injection. I recommend implementing it manually, this way you'll understand better how above mentioned dependency injection frameworks work.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
When programming, there are many indicators that coupling is bad. A class should know as little as possible about other classes. So it is modular and can easily be replaced.
Now, with the introduction of sealed classes, the abstract super-class knows about its sub-classes. As I understand it, the sub-classes would normally be in the same package (or even the same file) as their sealed interface. So there should not be a problem of cyclic dependencies between packages.
So I guess what I am asking is: Should a sealed interface and its sub-classes be regarded as one unit, and not as modular parts that are dependent on each other?
Example where the sub-classes are outside the package:
import asdf.Car;
import asdf.Truck;
public sealed interface Service permits Car, Truck {
To trigger-happy close-voters: An implementor of a sealed interface cannot exist outside the interface's module so the answer is pretty cut and dry. Not opinion-based at all. Here is a comment from Brian Goetz that you might be interested in: Sealed classes for classes in different packages
I already got my answer though so I don't really care if no one else can answer. Have a nice day!
Inheritance is always strong coupling between types; hence most often you should follow
Favor composition over inheritance
Most of the cases when you use inheritance could be resolved with composition and dependency injection.
Keeping subclasses close to the base class inside the one module is a good practice and doing otherwise is not recommended. You don't want to have a strong coupling between not related packages or modules.
There are exceptions to everything I said. F.e You might want to create a library of abstract classes than developers in your project could extend without duplicating utility code. F.ex java collections and abstract collection classes.
.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Anyone know what the opposite of a Plain Old Java Object is?
I'm talking about your typical terrible java class. Very complicated, tightly coupled, non-modular quagmire of ridiculousness?
Is there a term for a such a class?
Not sure you understand what is meant by POJO, from wiki-pedia a POJO object is simple an object that doesn't:
Extend a prespecified class, implement a prespecified interface or use annotations.
Basically this means an object that isn't part of a broader framework. Most badly designed, tightly coupled java objects are still POJO.
There is no such thing such the "opposite" of the POJO.
POJO is a simple java object (as you correctly say) and is used to separate them from objects which server special causes. I mention some example object categories which are not POJOs:
EJB
java bean
DTO
COM objects
CORBA objects
Hope I helped!
I know "Big Ball of Mud" is a term applied to software architectures that have the characteristics you describe, so maybe you could apply this term to classes as well.
The term POJO is a bit overused. You need to define it clearly so that you can come up with an opposite in your line of thinking. Following could give you an idea.
"POJO describes Java objects or classes that can function on any java context."
Following this description you can probably consider it to be the opposite of Enterprise Java Beans in a Java EE context.
Have a look at Enterprise Java Beans for more information.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I have been learning composition and inheritance. Now I understand inheritance is an "is-a" type relationship, and composition is a "has-a" relationship. But does this mean a composition simply refers to a class having an object (or field) of something?
Basically yes, but it has more implications.
The outer object has to protect the enclosed objects from modifications to avoid data corruption. This is usually done through defensive copies creation. If the enclosed objects are immutable this is not necessary
Other implication is to have the enclosing object isolated from the object API so it may change in the future. Let's say the object uses an array and then it decide to use a list instead, by disallowing references to the internal object, the external may change implementation without breaking existing clients.
You may take a look to the chapter: "Prefer composition over inheritance" in the "Effective Java Book" which describes in great these and much other implications.
When you have a situation where a class could extend another class (inheritance), or use another class as a field (composition), go for composition, because it allows you to change the implementation later without affecting any code that uses your class.
When you don't, you forever lock the implementation to be a subclass of the extended class. Any time you do that, it's bad.
An example from the JDK of where inheritance was chosen over composition is the Properties class, which extends Hashtable, when all needed was to use a Hashtable internally and implement a suitable interface. That means you can't substitute in your own implementation of a Properties class, for example with a simple anonymous class.
There are far more examples from the JDK where they got it right, for example HashMap uses a Hashtable, but could easily be changed to use some other hash-based class without affecting its contract or API.
You should always strive to make classes flexible in their implementation.
See Liskov substitution principle
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In Java I have the abstract class Place, with two concrete subclasses Area and Level; a Level must have a parent Area. But in trying to make unit tests for Level, I don't want to have create a full-fledged instance of Area. I see two ways of dealing with this:
1) Create an interface IPlace, extended by interface IArea, which Place and Area implement. Then create a MockArea class which implements IArea, and pass that to Level when testing it.
2) Use a mocking framework which will automatically create mock objects for me.
Which way is better? Or is there a third way to do it?
You're not giving us the reason why you don't want to create a full-fledged Area, but lets assume it does something difficult to test, like connect to a DB or read a file or something. Those are dependencies that it has. Dependency Injection is the answer.
For example, let's say Area does this in its constructor:
public Area() {
//get db connection
//do something with db connection
}
Now when you create a Level, it'll connect to a DB. Here's how you'd rewrite the constructor to use Dependency Injection:
public Area(Connection con) {
//do something with db connection
}
Now, when you create a Level, you can give it a fake Connection and are able to test your Level.
Now you can use a mocking framework to make a fake Connection. I recommend Mockito.
As you've written it, I'd suggest using a mocking framework.
Dependency Injection is great. Using it lets your classes state in an obvious way what types of things they need to interact with. If done properly, the need for mocked objects is often unavoidable. Get used to working with a mocking framework. I like Mockito personally.