When reading the Java source
User user = new User();
Anyone can see the description. Yes, instance creation.
I came to understand this, but when I actually touched the program, I was confused by the following description.
check.java
public boolean userExists(String userId) {
//Use User type variable
User user = select.selectOne(userId);
if (user == null) {
return false;
}
return true;
}
It was suddenly described as ʻUser user` without new. For me, who had vaguely thought, "When I use another class, I'm new," I don't understand why.
But that was simply my misunderstanding.
Looking at the contents of the above method select.selectOne (userId);
select.java
public User selectOne(String userId) {
//Get 1 data
Map<String, Object> map = jdbc.queryForMap("SELECT * FROM m_user "
+ "WHERE user_id = ?"
, userId);
//Variable for returning results
User user = new User();
//Set the acquired data in user
user.setUserId((String) map.get("user_id")); //User ID
user.setUserName((String) map.get("user_name")); //User name
//Return user instance
return user;
}
It has become. Yes, I firmly do ʻUser user = new User ();` and new, and return that user instance as the return value. In other words, since the User instance has already been created, there was no need to create a new one in the first check.java class.
If you ask me, I wouldn't know if I created a new instance each time. ..
That's why I got a little deeper understanding of the phrase, "The timing to new is (only) when you use it." maybe.
In the Command pattern, create a command in advance and execute the created command when needed. Just like installing (preparing) commands in advance on Linux etc. and executing commands when needed.
Thank you for pointing out. Java is still deep, isn't it? I had never heard of the Command pattern, so I looked it up, but I couldn't figure it out just by looking at it. I will study design patterns in the future. Thank you very much for your good opportunity.
Recommended Posts