How does Java composition work? [closed] - java

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

Related

Java Sealed Classes and Coupling [closed]

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

One-on-one relation between interfaces and classes [closed]

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.

What are the things hiding in abstraction? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Most of the people says that abstraction is hiding something and showing only functionality to the user. Can anyone explain me what are all the things you are hiding and what are all the things you are showing?? please don't explain with the examples of animal, engine, vehicle.
I think this is a case where a concrete example would help a lot.
HashMap has an internal structure for handling hash collisions, which is an implementation of a singly-linked list. Now, do you know how that internal structure works, what it's called, what its fields are called, etc? More importantly, do you care, so long as the HashMap "just works"?
If the answer to both of those is "no" — which is what it should be for anything other than curiosity/learning purposes — then those details have been hidden from you and exposed via the abstraction of Map's interface.
The result is a class that's easier for you to reason about (because you have less to learn), and easier for the library maintainers to maintain (because they don't need to worry about a change they make breaking your code, so long as they still abide by the interface).
Abstraction is an overloaded term.
Abstraction, in object oriented languages, basically means leaving away unnecessary details when modeling real world objects. You could also think of it as a simplifying process.
Abstraction, in computer science as a whole, also means hiding complexity by providing some sort of simpler interface. Your question seems to aim at "data abstraction" which means hiding the exact way data is represented with an abstraction layer. This could be e.g. the Number data type in databases. You just know it is a number, but not how it is stored on disk.
Abstraction sometimes is used equivalently to encapsulation, too.

Design SuperHeroes game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Question might be silly for experts but please help me with pointers if it is already solved somewhere.
Interview Question : "Design class diagram in best possible way"
You need to design a game "SuperHeroes".
Super hero examples are Batman, Spider-Man, Thor, Hal Jordan, Wonder Woman, Captain America .... n
Spiderman can jump, crawl, generateFire ....n
Batman can jump, crawl, fly .... n
Thor can swim, fly .... n
There can be millions of behaviour.
There can be millions of Super heroes.
Some have few behaviours common in them and some specific to hero.
Design should be flexible enough to add behaviours to the super heroes
Important point to focus was told that "System should be scalable"
I tried twisting decorator pattern to accommodate problem requirements but was failing at many places, also I have to make many interfaces for this, so scalability was questionable.
I tried another approach as Writing all behaviours in one class(If require will classify behaviours in respective classes, kind of utility class which will have all implementations of behaviours). and an Spiderman class which will have list of allowable Behaviours(kind of enum). and it is allowed to call methods from behaviour utility only if such behaviour is allowed in list. I think it is not a good approach.
Please help me with best way to achieve this.
If I understood the question correctly, the problem could be solved with the mixin pattern; however, multiple inheritance is required for a straightforward implementation, which is not available in Java. The subject is discussed in this question.
In games it is pretty easy to get a very huge inheritance tree up to the point, where it is very difficult, if not impossible to add a new entity with a different behaviour. To solve this, something called the Entity Component System is used. It is very flexible, does not limit you to inheritance and is commonly used in larger games.
There is also a follow-up article that describes a specific implementation, and has examples on how it can be used in different situations.

What is the best pattern to persist objects? [closed]

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
I need to persist objects and I want to keep my data classes as clean as possible. The persisted classes do not feature any business-logic code, but only data with getters/setters.
I'm currently implementing a solution with the Observer pattern. Each time an Observable persisted object is modified, it fires a message to an Observer object that takes care of persistence. This way, the only constraint for the persisted object is to be "Observable". It keeps things clean.
Another solution (maybe better?) would be to implement some DAO pattern, and I'm not very aware of the way it works. Maybe it would look like persistedObject.save(); or persistedObject.readById(id);. But it means I would have to define some DAO interface and then to implement the read/create/update/delete method in each and every persisted class
There are many, many, many answers to this question, data serialization or persistence is a core problem in software engineering. Options include using databases, memory mapped files, binary and textual formats, and more.
My personal favorite for quickly persisting objects is GSON, however your use case will dictate what works best for you.
You mention wanting design patterns for persisting Java objects, and while such patterns are approximately as numerous as there are libraries, here are a couple general suggestions:
Use immutable objects
Use the transient keyword for any fields that are not necessary to reconstruct an object
Avoid defining sanity checks or otherwise limiting the range of acceptable values in your objects - an instance constructed from a deserialize call may not correctly trigger your checks, allowing possibly invalid objects to be constructed
Use your serializable objects to construct more complex objects if you need more sanity checking, e.g. serialize a StubPerson POJO, and have a Person object that can be constructed from a StubPerson only as long as the stub's values are valid
I don't know if it fits for you but since you have only bean classes you could use the Java persistence api.
The DAO pattern is the best one to manage data access and persistence as it has been designed specifically for that.
Considering your needs you will probably have to couple it with some factory pattern in order to manage the different implementations (persistence adapters).
I don't know your requirements but if your application can be used by many persons at the same time you will have to care about concurrent accesses and define a policy (transaction, locking, etc... otherwise people will overwrite data each others).
Regarding your question i'd suggest JDO (with data nucleus as implementation) but the learning curve may be too expensive for your effective needs.

Categories

Resources