What is the convention with Java beans, and implementing interfaces like Comparable? - java

Java Beans, as far as I know, should always:
Have only an empty constructor
Have only fields, and getter/setter methods for these fields.
However, I am wondering what the convention is for Java beans to implement interfaces like Comparable? I could leave the java bean pure, meaning absolutely no behaviour, only data, and write a custom comparator-class. Implementing comparable is easier though.
Are there any conventions when it comes to implementing simple common interfaces like Comparable to Java Beans? I cannot find any consequences myself, but it feels like I might breaking some rules, and that there might be something I haven't thought of.

IMHO this question is mostly not about conventions but about the needs.
You are right that separation of bean stuff from any business logic is a good style. I'd add here that this typically a good practice because relationship between your beans and comparators are many-to-many, i.e.
You will probably hold several comparators for one bean class and use them in different contexts
Sometimes you can re-use one comparator for several different classes or make hierarchy of comparators.
However you are right that writing comparison logic into class itself is less verbose and in some cases preferable. The choice completely depends on the author taste and requirements of the application he/she is working on.

Related

Should I avoid commonly used class names?

Some class names are so "generic" that they are often found in several different packages, including in libraries and application code. Some examples:
Comment
Component
Factory
Location
Region
In my IDE, attempting to auto-complete the import for a class like one of these summons several competing suggestions.
When naming classes, is it a good idea to avoid class names already used elsewhere?
For some of these examples, I would imagine that using such class name is discouraged because it is simply not meaningful enough (e.g. Factory), but I am wondering whether it is discouraged to use a class name because it is used (frequently) elsewhere.
You should use class names where they make the most sense for you. None of the names above that you've proposed are off limits, and there's no reason why you can't use them (assuming a language that supports namespaces and can avoid naming conflicts in this way).
However, you may consider drilling down to class names that are more specific and precise, which will better describe the meaning of the objects in your code. For example:
Instead of Comment: LineComment or BreakComment could easily be class names in a compiler project where you would like to create semantic blocks for comments.
Instead of Component: ListComponent, CalendarComponent, or ViewComponent make particular sense when implementing a UI library where you have class-based components.
Instead of Factory: PizzaFactory makes more sense if you're trying to make pizzas!
Instead of Location: GeographicLocation or SemanticLocation makes more sense when implementing a directions based navigation app, and you're trying to distinguish between '45 deg N, 77 deg W' and 'next to the pizza place'.
Region: CodeRegion could be used in a compiler, and GeographicRegion could be used in a Maps app.
If you're afraid to be specific, namespaces and packages help. However, there is nothing discouraging you from using the same name for a class as another package where it makes sense. The class names specifically aren't copyrighted, and most IDEs now are smart enough to make distinctions between what packages you're referring to when using autocompletion.
For the most part, specificity is helpful in assisting other developers to read your code, which every developer can appreciate!
Comment, Region, and Location seem fine. Personally, so subjectively, Component and Factory are definitely too common to use but objectively I can't think of any conventional reason not to use them as names. I'd definitely try and couple those names with their respective usage, for example; TaskFactory, WidgetComponent, ButtonFactory, etc.
Depends if we are talking about business or technical part.
In technical part: using common names is actually a way to let others know about the patterns used, Factory is a good example - when you see a class named like SomethingFactory, you can expect a Factory Pattern. It goes further to frameworks, libraries etc. - SomethingAutoConfiguration with Spring-Boot, SomethingEntity with JPA, I think with frontend frameworks (React, Angular) Component is a really common word. So ye, by all means, use them, as long as you use them correctly.
In business part: simple, if those words describe your business domain, then by all means use them. Don't try to invent some fancy names (or thesaurus!) just because the words seem common, it's your business domain - it's sacred.

Using strategy pattern with simple factory

I've been learning about design patterns and I think I'm a little bit stuck with an exercise where I do not posses any answer-pages to.
I already used the strategy pattern to create this:
http://i.imgur.com/5Lia4JD.png (minus the setBehavior functions in duck)
I need to improve this design with simple factory because at the moment, the 2 types of behaviors are instantiated via following code (shown via example):
public MallardDuck()
{
setQuackBehavior(new Quack());
setFlyBehavior(new FlyWithWings());
}
This is not correct because we need to program to an interface and not to an implementation.
What I thought to do is making 2 separate factories that each handle a specific behavior but when I made the design I started doubting my solution. Is it normal to do this sort of thing with simple factory?
Could anyone push me in the correct direction? :]
If you're programming Ducks, then it's a toy example anyway. Go ahead and do the two separate simple factories. The general rule is a simple factory per interface. You could put all the simple factories in one class to make it less complex.
The disadvantage of concrete classes instantiating other concrete classes is of course the risky coupling to implementations. If the implementation details change (yes, the new is trivial but the whole ducks example is trivial), your classes that know that information are also liable to change.
You're right that it's not programming to an interface. Classes that know less about implementation details are more insulated from changes in those details, which is the whole point of using interfaces.
If you want to avoid the strong coupling between concrete strategies and their host you may rely on a factory that knows how to instantiate a Duck with the proper strategies for a given type rater than having a concrete class per type.
The above design may be slightly more testable, but I do not think you should be too concerned about the coupling between concrete ducks and the concrete strategies they use.
This is not correct because we need to program to an interface and not to an implementation.
And you program to an interface since setQuackBehavior() takes as input an interface and that your quack class represents the quack behavior field as an interface and not an implementation.
At a time, in a code, using a implementation class is normal.
Using a factory with methods returning based interface instances is useful in many cases but in your case, I don't see the interest. Why your quack subclasses should not know which concrete behavior used ?
If it has no reason, so it seems ok :
setQuackBehavior(new Quack());
Using factory with not added value gives a complex code without reasons.

What does composition do?

I have been learning java for the past two days and i have gotten confused with composition. what exactly is the point in composition and what does it do?Please leave some examples as well.
I think it is already answered in so many links. Refer these links.
Implementation difference between Aggregation and Composition in Java,
Favor composition over inheritance
https://softwareengineering.stackexchange.com/questions/176049/what-is-the-use-of-association-aggregation-and-composition-encapsulation-in-c
Also read this link
http://www.journaldev.com/1325/what-is-composition-in-java-java-composition-example
I put what Chandra posted. This might be what you are looking for
I think this is one of the most discussed point in Object Oriented design. As suggested in the article, composition is always preferred over inheritance. That doesn't mean that you should never use inheritance. You should where it makes more sense (which can debatable).
There are many advantages of using composition, couple of them are :
You will have full control of your implementations. i.e., you can expose only the methods you intend to expose.
any changes in the super class can be shielded by modifying only in your class. Any clients classes which uses your classes, need not make modifications.
Allows you to control when you want to load the super class (lazy loading)

Comparing C#'s attributes and Java's marker interfaces

Yesterday I came across attributes in C#, the [Serializable] to be precise. As I understand it, they are used like metadata, to provide some information about your class.
Also, I learned that Java has "marker interfaces", the ones with no methods, that serve the purpose of explaining the class, i.e. marking some characteristic of the class, for example the Serializable interface.
I was wondering: can you make a parallel between the two? Are they similar, or even the same?
C# attributes are more like Java annotations. (I believe that's where Java got the idea.)
Marker interfaces are a Java 1.0 construct that are rarely used in new code, if ever. I don't find them to be useful. I would not recommend reviving the practice.
Java interfaces should be for separating declaration of method signatures ("what") from implementation ("how"). They should be like C++ pure virtual classes, not attributes or annotations.
several years ago , Java didn't support attributes. Therefore, to "tag" a class or an interface so that
they could be checked at runtime, you would use marker interfaces,
which is basically an empty interface but you can still check if an instance can be casted to this interface.
In .NET, marker interfaces should not be used except for special use cases (such as allowing the use of extension methods),
because attributes provide a better way to mark classes (and lots more) with metainformation. The same goes for Java 5 and newer,
where annotations were introduced and should be used instead.
Marker interfaces:
1) are a bit easier to check for using dynamic type checks (´obj is IMarker´);
2) allowed for functional and data extensibility in the future (i.e. turning a “marker” interface into a “full” interface that actually declares some members);
3) can be used in generic type constraints;
Attributes:
provide a clearer separation of metadata;
allow for specifying additional information via their constructors or properties;
allow for multiple application to an entity;
are general-purpose in terms of applicability to different kinds of entities, not just classes;
It heavily depends on the particular application's architecture and design whether it's appropriate to use a marker interface or an attribute in a particular case.

why are interfaces created instead of their implementations for every class

It seems to be the standard so I have been going along with it so far, but now I am building a new class from scratch instead of modifying the old ones and feel I should understand why I should follow the projects convention.
Almost every class has an interface to it which is called classnameable. In the code database.class would never appear even once but in place where I would want to use that class I see databaseable.class.
To my understanding an interface was a class that was never implemented but was inhereted from to keep standards. So why are the interfaces being used as if they were real classes?
To my understanding an interface was a class that was never
implemented but was inhereted from to keep standards. So why are the
interfaces being used as if they were real classes.
This is a bit confused. An interface defines an API, so that pieces of code from different authors, modules or projects can interact. For example, java.util.Collections.sort() can sort anything that implements the List interface and contains objects that implement the Comparable interface - even though the implementation classes may not have existed yet when the sorting code was written!
Now the situation in your project seems to reflect an unfortunately rather common antipattern: having an interface for everything, mostly with a single implementation class, even for internal classes.
This used to be strongly promoted by proponents of Test-Driven-Development (TDD) who see it as vital to be able to test every class in isolation with all its dependencies replaced by mock objects. Older mocking frameworks could only mock interfaces, so to be able to test every class in isolation, all inter-class dependencies had to be through interfaces.
Fortunately, newer mocking frameworks can mock concrete classes and don't require you to pollute your project with unnecessary interfaces. Some people will probably still argue that it should be done anyway to "reduce coupling", but IMO they're just rationalizing their desire not to change their practices.
And of course, if you don't do fundamentalist TDD, there never was a good reason to have an interface for everything - but very good reasons to have interfaces for some things.
If you've got an interface for pretty much every single class in your project even though there's no reason for it, that's not a good thing and in this day and age there's no great reason for it. It may be a legacy from days gone by when it was required by some external testing toolkit for instance - but these days that's not a requirement.
It may be of course that someone's heard that loose coupling is a good thing, that you should always couple to interfaces and not concrete classes, and taken this idea to an extreme.
On the other hand, it is good practice to define interfaces for some classes even if there's only one of them (at the moment.) When I'm writing a class I try to think along the lines of whether another (potentially useful) implementation could exist, and if so I'll put an interface in. If it's not used it's no problem, but if it is it saves time and hassle and refactoring later.
If you want a class for your interfaces then a common way is to create an AbstractFoo class to go with the Foo interface. You can provide simple implementation of the required methods, allowing derived classes to overwrite them as needed. See AbstractCollection for an example of such a class.
The advantage is that you don't have to implement all the small stuff, it is already done for you. The disadvantage is that you can't inherit from any other class. You pays your money and you takes your choice.
A good indication for bad design is when you have a ISomething or a SomethingImpl. The interface name should state how to use it (i.e. List), the class name should state how it works (i.e. ArrayList).
If you need pre- or suffixes because the names would be the same, this means there is only one way to implement it, and then there is probably no need for a separation. (If you think there will be more sophisticated implementations in the future, name your class DefaultSomething or SimpleSomething)

Categories