Tuple vs Class in Java - java

Are there any advantages of using Tuples instead of creating a new class in Java?
I've seen something like this a few times
return Pair.of (username, password);. And I've always wondered what kind of advantages it has in relation to something like this return new Credentials (username, password).

Java doesn't have a (first class) notion of tuples. Some projects and libraries introduce types like Pair or Tuple2/Tuple3/Tuple4/... to make up for it, but this is often considered poor style in Java.
By contrast returning a clearly-defined type like Credentials that provides not just structure but also type safety and meaningful getters for your data you make your code clearer, safer, and easier to work with. The Auto/Value project in particular makes it quick and painless to create value-types, making tuple-esque types all but unnecessary.

A Pair (Apache) is immutable, for one. You cannot change it’s values after creation. Many people do in fact choose to create their own class and add methods as necessary.
In general it’s considered better practise to make your own class. You can validate parameters and so on and have the ability to add additional functionality if the need arises.

As dimo414 says, the Pair class is often encountered in 3rd party libs; it has two advantages:
it makes defining a separate class for each key/value pairing unnecessary; so you don't need to define a Credential class. Of course, this should only be used to temporarily store data, not to be used within your implementation model.
Even if you do have a Credential class already, usually Pair is immutable, while the Credential class may not be. That means that it may provide setUsername() and setPassword() methods which you don't always want; using a Pair class makes sure both key and value remain unchanged.

Related

When to use Enum class in java?

It may be very obvious questions, but is it good to use Enum class if you know that the list of values will keep increasing?
Let's say you define an Event Enum first it contains only [Poo, Too] then as we know we always have some new requirement it becomes [Poo, Too, App, Laa] and that keep changing again and again,
So what is the best approach in this case?
tl;dr
If the entire set of possible values is known at compile-time, use enum.
If values can be added or dropped while your system is in use (at runtime), then you cannot use an enum. Use a Set, List, or Map instead.
Known at compile-time
An enum is appropriate when the domain (set of all possible values) is known at compile-time.
If this year your company is offering two products ( Poo & Too ), then make an enum for those two elements.
public enum Product { POO , TOO }
Next year, your company decides to grow their product offerings by adding App & Laa. As part of a planned deployment, add two more objects to your enum.
public enum Product { POO , TOO , APP , LAA }
By the way, notice the naming conventions. The enum has a regular class name (initial cap). The objects being automatically instantiated are constants, and so are named in all-uppercase.
Also, be aware that the enum facility in Java is quite flexible and powerful, much more so than the usual naming-a-number enum scheme seen in most languages. You can have member variables and methods and constructors on a Java enum. For example, you can add a getDisplayName method to provide text more appropriate to a user-interface than the all-caps object name, as seen in DayOfWeek::getDisplayName. You can add quite a bit of functionality, such as ChronoUnit.between.
What you cannot do at runtime with an enum in Java is add or remove objects. Thus the requirement that you know your domain at compile-time. However, when working with a group of enum objects, you can use the highly-optimized EnumSet and EnumMap classes.
Known at runtime
If you cannot determine the domain at compile-time, if users can add or remove elements at runtime, then use a collection such as a List, Set, or Map rather than an enum.
Singleton
Though not originally intended as a purpose of Enum in Java, an enum happens to be the safest (and simplest) way to implement the Singleton design pattern.
This approach to a singleton is explained in the famous book Effective Java by Dr. Joshua Bloch, et al. Using an enum solves multiple obscure technical problems with other approaches to a singleton.
Your question is pretty generic and I'm pretty sure there is no single right answer. But judging based on spring* tags, I suppose you might be asking about enums in DTOs that being sent over your system in serialized form. If that's the case, I would recommend to choose String in DTO, while inside single app it's ok to use enum. Then you would just care about deserialization/conversion in a factory manner, having ability to handle unknown/missing constant gracefully by logging/providing fallback or meaningful error.
It depends on a case-by-case situation and your question doesn't have much context. However, I do recommend using ENUMs for many cases, including if you expect the list of ENUMs to increase.
Some reasons to use them are:
It creates a definite guide of ENUM elements that can be used throughout your code. It eliminates uncertainty over what something is named or what it is. For example ENUM that contains list of animals, or enum of "something".
Its easy to refactor later if you need to change anything.
I'm sure there are many more reasons, I find it like a table of contents sometimes. For many cases, you can completely avoid it and be fine but I think its better to use it in general if you're on the fence.

Is it possible to have a POJO as ESuperType in EMF?

Question/Problem
Given a plain Java class coming from a non-EMF-aware API such as
public class BankAccount {
String ownerName;
int accountNumber;
// ...
}
and also let's assume that I am not allowed to change or recompile this class (because it is from an API).
Is there any simple way to use this class as an ESuperType for an EClass in EMF? (And, of course, the single class is just an example. I'd need to wrap an API consisting of 30-50 classes ...).
Own thoughts
Personally, I think it is not possible out of the box.
I could only think of two ways, both with quite some effort and not easy to realize.
Create an Ecore model which reflects the original class (EBankAccount, having ownerName and accountNumber as EAttributes) and a utility method/mechanism that wraps the original object by copying its fields into the corresponding EStructuralFeatures and adds EAdapters which are responsible to synchonize both objects.
Hook into EMF.CodeGen and do some magic there which makes it possible to have the original class as super class in the generated code which at the same time still fulfilling the EMF contract (= implement the EObject interface etc.).
But maybe there's some hidden feature of EMF (or an existing extension) which does something along these lines, and I am not aware of it?
It's not clear to me what you real want, but I will try to describe the several options.
If you want just to extend the POJO (which is what the question text suggests), the answer is YES, you can simply add a new EClass to your model and refer to the POJO qualified name in the "Instance Type Name" attribute. Then you can create other classes that extend from this one, but its state won't be managed by EMF.
But if you want EMF to track that POJO state as if it was a real EMF object (so those properties are also EStructuralFeature), then I don't see another solution, you really need to model it completely in EMF.
In this second case, both options you described seem possible.
The first option you described (and I assume you mean you want to synchronize the 2 objects, and not the 2 classes) seems the easiest one, and I don't think it would take so much effort if you use some generic method via reflection.
This might be a good solution if you get the objects in very concrete locations, so you only need to wrap and unwrap in specific places. Otherwise you will need to convert be converting (wraping/unwrapping) the object all the time.
It may be also possible but it requires more effort for sure, since it's not easy to extend the Java JET templates
I'm not aware of any extension for this.

Best Practice - HashMap instead of list of parameters, good idea ?

Hi Stackoverflow community,
I am working on some code where a list of optional criterias criterias is submitted to my dao.
Method signature contains the list of +/- 10 parameters, which I really don't like and want to reformat.
Plus I would like to avoid having to refactor all method signatures from different layers just because I add/remove a criteria
List searchParams(String name, Long countryCode, ...){
...
}
would become
List searchParams(HashMap<String,Object> map) {
BeanUtils.populate(this,map);
...
}
I am a bit worried that this happen to because kind of a bad practice, because I give up control of what is passed in the map to give me that flexibility ? So my question is if I am on the right path proceeding that way?
When I encounter situations like this, I tend to create a Params class, and pass that around. The benefits are that:
unlike when using a Map, you can have meaningful getters/settings, proper validation etc;
it's type-safe and self-describing (meaning it's easy to find out the available parameters and their types).
you can add new parameters without having to refactor any intermediate layers.
You could define a new class to hold/handle your set of parameters, so you get a bit more control than a HashMap would give you. Annoying to write, or at least tedious, but seems like a better balance between flexibility & control.
You could look at your parameters and see if you can wrap them as a logical group into an object. For example a name an a country code could be a person object
public Person {
private String name;
private String countryCode;
}
Then you will just be passing this object down and can use getters to get the data out which should be easier to read and maintain than needing to know all the keys for the HashMap on multiple layers.
The only case where using a map is appropriate is when you are designing a factory, and you need to pass different kinds of parameters to different classes being created. In all other cases, a solution with a specialized parameter info class would be preferred.
For an example of where passing a map is appropriate, look at the DriverManager.getConnection method: this method needs to pass parameters to constructors of driver-specific implementations of the Connection being created, so it wraps a map into Properties, and lets the user pass it through to the driver-specific connection. Note that DriverManager does not have another solution that would be future-proof.
I would strongly discourage using a map in all other cases: the added flexibility shifts error detection from compile-time to run-time, which has a strong potential of multiplying your headache beyond belief.

Object Conversion Pattern

I have several different classes coming from external sources (unmodifiable) that represent the same concept. For example Address. I have com.namespace1.Address (with fields houseNum, street, city), com.namespace2.Address (with fields h, s, c), namespace3.com.CoolAddress (with fields house_num, street, city).
The problem is that certain web services I use require certain Address object types so I am required to create a com.namespace1.Address given a namespace3.com.CoolAddress. The fields are easy enough to map but I'm looking for a pattern on how to do it.
From my point of view, an instance object AddressConverter doesn't make sense as there is no state (only behaviour) and when classes only have behaviour it boils down to static methods in a utility class. In the long term, anytime I need to map new objects to one another, I have one place to add/modify/remove methods. How it's done might change, but I know where the code sits (in once place) and can change the mapping when I need to.
Thoughts?
I think what you're looking for is a factory class. The factory pattern is used when you need to be able to instantiate one of several related classes, to be determined by the factory, not the developer.
See http://en.wikipedia.org/wiki/Factory_method_pattern
You're right to try to keep all this business logic in one place instead of doing ClassOne.toClassTwo(), ClassOne.toClassThree(),...
The most flexible way I can think of implementing this (but not the easiest by far) would be to have the factory start with a simple class with only basic common methods in it, and add handlers to a Hashtable or other container. That way you don't need concrete implementations of every possible combinations of features.
Of course it would be quicker to have a concrete implementation for each possible address variant, but there would be a fair amount of duplicated code, and it would be a little harder to add new address class types.
Since you can't modify the classes themselves, I'd suggest an implementation of the Adapter pattern for each direction. As you said, the adapter methods themselves can be static, but you can group both directions inside a single class so that the logic is all in one place.
At the end of the day you're going to be performing the same task no matter what you call it, or where you put the code. I'd suggest that both directions live in the same file, as they'll often both need updating when either direction changes.
If you are always converting to the same Class I would keep it simple and put all you conversion code in that Class and not worry about factories and the like, especially if you are only dealing with a couple of different classes. Why does there always have to be a complicated pattern for these things?!
public class A {
...
public static A convertB(B b) {
...
}
}
Are the classes you need to output final? If not, you could subclass them to create proper Adapters. Otherwise I'd go with dj_segfault's suggestion of a Factory with a table of handlers.
Or, wait -- is it just a web service you need to talk to? If so, there should be no reason your implementations of its datatypes can't be Adapters wrapping the input datatypes, or some intermediate object of your own.

Why is using a class as a struct bad practice in Java?

We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . Why is that ?
There's an argument that classes should either be "data structures" (i.e., focus on storing data with no functionality) or "functionality oriented" (i.e., focus on performing certain actions while storing minimal state). If you follow that argument (which makes sense but isn't always easy to do) then there is nothing necessarily wrong with that.
In fact, one would argue that beans and entity beans are essentially that - data containers with getters and setters.
I have seen certain sources (e.g., the book "clean code") arguing that one should avoid methods with multiple parameters and instead pass them as a single object with getters and setters. This is also closer to the "smalltalk model" of named parameters where order does not matter.
So I think that when used appropriately, your design makes sense.
Note that there are two separate issues here.
Is a "struct-like" class sensible?
Is creating a class to return multiple values from a method sensible?
Struct-like classes
An object class should -- for the most part -- represent a class of real-world objects. A passive, struct-like java bean (all getters and setters) may represent a real-world thing.
However, most real-world things have rules, constraints, behaviors, and basic verbs in which they engage. A struct-like class is rarely a good match for a real-world thing, it's usually some technical thing. That makes it less than ideal OO design.
Multiple returns from a method
While Python has this, Java doesn't. Multiple return values isn't an OO question, per se. It's a question of working through the language limitations.
Multiple return values may mean that an object has changed state. Perhaps one method changes the state and some group of getters return the values stemming from this state change.
To be honest, it sounds fine to me. What alternative did the reviewer suggest?
Following OOP "best practices" and all is fine, but you've got to be pragmatic and actually get the job done.
Using Value Objects like this (OO speak for 'struct') is a perfectly legitimate approach in some cases.
In general, you'll want to isolate the knowledge needed to operate upon a class into the class itself. If you have a class like this, either it is used in multiple places, and thus can take on some of the functionality in both of those places, or it is in a single place, and should be an inner class. If it is used in multiple ways, but in completely different ways, such that there is no shared functionality, having it be a single class is misleading, indicating a shared functionality where there is none.
However, there are often specific reasons for where these general rules may or may not apply, so it depends on what your class was supposed to represent.
I think he might be confusing "not very OOP" for bad practice. I think he expected you to provide several methods that would each return 1 value that was needed (as you will have to use them in your new class anyway that isn't too bad).
Note that in this case you probably shouldn't use getters/setters, just make the data public. No this is "not very OOP" but is the right way to do it.
Maybe Josh Bloch offers some insight into this here.

Categories