I've asked yesterday about the instance generation of java object like Entity as the instance variable. https://stackoverflow.com/questions/42239761/declare-entity-in-java-as-private
I am not satisfied for the answers I get and now I want to more clarify what my question is:
I have Entity called User.java:
#Entity(naming = NamingType.SNAKE_LOWER_CASE)
public class User{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And I have a class called UserImpl.java what I did is:
public class UserImpl implements UserLogic {
private User userEntity = new User(); ------> // Bad practice
/** Methods **/
}
As you can see I declared an instance for User entity in UserImpl class. Is that a bad practice at all?
Any answers will be much appreciated.
The simple act of creating a private instance of a class in another class is not a bad practice at all. In fact, it is very common and Java would really be pointless if you couldn't do this.
I feel like there is still some missing information here. Depending on the function of the "UserImpl" class, this might be a bad practice. But this would entirely depend on how you go about implementing the "UserImpl" class.
For example, if you were planning on creating a variety of methods in the "UserImpl" class that would all center around changing "userEntity," then that might be a bad idea because all of those methods could instead go into the "User" class itself, which would be much simpler and more intuitive.
tldr: This isn't bad practice as it is right now, but depending on the purpose of your "UserImpl" class, it could turn out to be.
Related
I'm coding a Spring Web Service, using Jackson by default. I'm using #JsonView to indicate which property I need to be parsed to my JSON object. So, the problem is: Many objects are used in different classes, but not exactly all its properties, for example:
class Professor {
#JsonView({Views.Public.class, Views.Internal.class})
private int id;
#JsonView(Views.Internal.class)
private String name;
...
}
class Classroom {
#JsonView({Views.Public.class, Views.Internal.class})
private int id;
#JsonView(Views.Internal.class)
private String name;
...
}
class Lecture {
#JsonView(Views.Public.class)
private Professor professor;
#JsonView(Views.Public.class)
private Classroom classroom;
...
}
What if I need more than two 'perspectives', I'd have to create more interfaces/classes to do that? (like Views.Professor, Views.Principal, ...) Is this a real good practice?
I'd like to hear some suggestions or alternatives to solve that. I'm a little bit confused about being on the right track.
Generic names
You always can define more views if you need more perspectives, that's the idea behind the Jackson JSON views and that's what makes it flexible.
If you use generic names in your views classes, such as Basic, Extended, Public, Private and so on, you'll find it easier to reuse them across multiple beans.
Inheritance
You always can rely on inheritance with #JsonView. Consider the following example where Views.Private extends Views.Public:
public class Views {
interface Public {}
interface Private extends Public {}
}
Serialization of properties annotated with #JsonView(Views.Private.class) will also include properties annotated with #JsonView(Views.Public.class).
Realm on Android doesn't support model inheritance/polymorphism.
So is there any way to share fields on Android? We have 5 models that all share the same synchronization-related fields and code. We use inheritance in our current SQLite models; if we switch to Realm, is our only choice to duplicate the sync fields across each of the 5 model classes?
As a workaround, I'm thinking about having those classes implement a Syncable interface with getters and setters for the shared fields, which at least let me share sync functionality. Is there a better way?
To share sync functionality, my best guess is to make a static Synchronizer class and pass it Syncable model objects. Synchronizer methods will use the Syncable interface to operate directly on model objects' shared, sync-related fields and delegate operations on type-specific fields. Alternatively, I could provide each model object its own Synchronizer instance...
Trying to find the right way to work around the inheritance limitation is really stretching my OOP skills... help is appreciated!
I had the same issue when I found out that realmObjects should inherit directly form RealmObject class (no support for inheritance).
In order to get back the benefits of polymorphism, I considered a similar solution to yours combined with some composition tricks that would avoid me attribute duplication.
"Talk is cheap show me the code."
Code examples
interface IPerson {
String getName();
}
class Person extends RealmObject implements IPerson {
String name;
#Override
public String getName() {
return name;
}
}
interface IWorker extends IPerson {
int getSalary();
}
class Worker extends RealmObject implements IWorker {
Person person;
int salary;
#Override
public String getName() {
return person.getName();
}
#Override
public int getSalary() {
return salary;
}
}
Some benefits
You won't have to duplicate your attributes in each extending class.
Polymorphism is back! For example, now you can simulate a cast (with getPerson() in this example).
Some limits
When using a serialization library that uses reflection (suppose it's Gson), your serialized models will have their parents attributes embedded. Not something that you would have had if you were using classic inheritance.
Example with JSON
Let's suppose John Doe is making 500$ a month. (He's a Worker and a Person right?).
With classic inheritance, John Doe would look like this:
{
"name":"John Doe",
"salary": 500
}
But with this inheritance workaround ... :
{
"person" : {
"name":"John Doe"
},
"salary": 500
}
Hope this helps!
Note
PrimaryKeys unfortunately have to be duplicated.
Bonus
You might want to check RealmFieldNamesHelper, a library made by Christian Melchior "to make Realm queries more type safe".
If you use Kotlin, sharing the fields via an interface becomes even more trivial:
interface PersonBase {
var name: String?
var salary: Int
}
Then
class Person: RealmObject(), PersonBase {
}
Is there some way of using magic methods in Java like there is in PHP with __call?
For instance:
class foo {
#Setter #Getter
int id;
#Getter
Map <String, ClassInFoo> myMap;
protected class ClassInFoo {
#Setter #Getter
String name;
}
#Setter
String defaultKey;
}
I'm using Project Lombok annotations for getter and setter methods to simplify the code.
Let's consider that that my map contains several items mapped by String and the defaultKey defines the default one.
What I would like is to be able to call foo.getName() which would return the default name as foo.myMap.get(defaultKey).getName().
The reason I can't just write all the getters manually is that the Foo class is in fact inherited with generics and the the inner class might be different.
I sort of need something like:
function Object __call(method) {
if (exist_method(this.method)
return this.method();
else
return this.myMap.get(defaultKey).method();
}
Is this somehow possible in Java?
EDIT:
I made a more precise example of what I am trying to achieve here: https://gist.github.com/1864457
The only reason of doing this is to "shorthand" the methods in the inner class.
You absolutely can through reflection by using its features like
public Method getMethod(String name, Class<?>... parameterTypes)
that can be used to see if a class has some methods defined but I don't see how your problem couldn't be solved with a proper use of interfaces, inheritance and overriding of methods
Features like reflection are provided to manage certain, otherwise unsolvable, issues but Java is not PHP so you should try to avoid using it when possible, since it's not in the philosophy of the language.
Isn't it the whole point of inheritance and overriding?
Base class:
public Object foo() {
return this.myMap.get(defaultKey).method();
}
Subclass:
#Overrides
public Object foo() {
return whateverIWant;
}
I've been converting some code from java to scala lately trying to teach myself the language.
Suppose we have this scala class:
class Person() {
var name:String = "joebob"
}
Now I want to access it from java so I can't use dot-notation like I would if I was in scala.
So I can get my var's contents by issuing:
person = Person.new();
System.out.println(person.name());
and set it via:
person = Person.new();
person.name_$eq("sallysue");
System.out.println(person.name());
This holds true cause our Person Class looks like this in javap:
Compiled from "Person.scala"
public class Person extends java.lang.Object implements scala.ScalaObject{
public Person();
public void name_$eq(java.lang.String);
public java.lang.String name();
}
Yes, I could write my own getters/setters but I hate filling classes up with that and it doesn't make a ton of sense considering I already have them -- I just want to alias the _$eq method better. (This actually gets worse when you are dealing with stuff like antlr because then you have to escape it and it ends up looking like person.name_\$eq("newname");
Note: I'd much rather have to put up with this rather than fill my classes with more setter methods.
So what would you do in this situation?
You can use Scala's bean property annotation:
class Person() {
#scala.reflect.BeanProperty
var name:String = "joebob"
}
That will generate getName and setName for you (useful if you need to interact with Java libraries that expect javabeans)
My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.
A private static inner class is exactly what you want. Nothing dumb about it.
public class Creator {
private static class Created {
}
}
Otherwise you can only protect instantiation on the package level.
public class Created {
Created() {
}
}
Which gives only classes from the same package access to the constructor.
Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy.
public class AllowedAccess
{
private SecureClass secure;
public setSecureClass( SecureClass secure )
{
this.secure = secure;
}
...
}
public class SecureClass
{
private SecureClass() {}
public static void Create( AllowedAccess allowed )
{
allowed.setSecureClass( new SecureClass() );
}
...
}
BTW, I'm suspicious of this design. Seems too highly coupled to me.
You could make the class that is to be protected from instantiation package private.
I agree with tvanfosson's answer and also with his comment about too high coupling. Why don't you retain more control of you class creation process by adopting an Inversion of Control framework like Spring or Guice?
IMHO creating classes with the "new" statement is to be considered a bit... obsolete, factories are to be preferred and IoC frameworks even more.
Regards