Java class storing static data - java

I have a large amount of static data that I want to store in my code, and I'm not sure the best way to do this. As an example, I want to store some fields like first name, last name, address, and phone number. I want to store this for several different users.
My initial thoughts were that I'd create a class with the fields I want, and then I'd make that class a nested class. I would make the outer class singleton and have an ArrayList of the inner class. I'd then instantiate several copies of the inner class. I feel like this is going to be awful though, because I don't want to instantiate several copies of a class. I want to just have one class with all the information.
Anyone know how I should go about this?

I hope I got you right. It seems that you want to have a set of constant (immutable) Person objects. If it is true, enumeration is the thing you are looking for. You can have something like:
enum Person {
Kent("myLast","Kfirst","kfoo"),
Someone("sLast", "sFirst", "sfoo");
private String lastname;
private String firstname;
private String foo;
Person(String lastname, String firstname, String foo) {
this.lastname = lastname;
this.firstname = firstname;
this.foo = foo;
}
public String getLastname() {
return lastname;
}
public String getFirstname() {
return firstname;
}
public String getFoo() {
return foo;
}
}
you can get field value by:
Person.Kent.getFirstname();
I am not sure if I understand you right.

What you are looking for is inheritance. You can have a class called Person which contains all the fields you want (along with appropriate methods). Then you can have other specialized persons like a Manager or what not by extending that class (If you want to, that is. Or else, you can just instantiate a Person).
You use static when your data is to be shared among objects of the class. If you have the name and age, say, as static then you will be in hot water. You need them to be non-statics. That way every object will have their own copy of the fields.
Have a look : http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

What about making an interface with all needed constants?
Then every class you want to contain those static values will implement that interface?

Related

Merge two objects that contains the same ID and return one object with the properties

class Item{
Integer ID;
String name;
Double price;
}
class Item discount{
Integer Id;
Double discount
}
I have these two classes with a list of items on both and I am trying to return a new object "ItemWithDiscount" that has the attributes of both classes, this in a service/controller requisition. I tried mapping them with stream but wasn't able to do so. Can anyone give me a light of some way to do it?
Well, I'm not sure what you mean by 'mapping them with stream'...
You need to have some sort of combined object which can store all of the relevant properties. In pure object model design I would first think of a composite pattern, something like:
class ItemWithDiscount {
public Item;
public Discount;
}
Although you might want to consider immutability, etc. Now, if you are going to serialize this to JSON, for example, it might be easier to simply implement it as a class containing all the fields of the sub-objects in a flat form:
class ItemWithDiscount {
public Integer itemId;
public String name;
public Integer price;
public Integer discount;
}
and now you can create a constructor which does the flattening. This second design is a bit clunkier in some respects, but for most purposes it will work OK.
NOW you could potentially use stream syntax to build these composites, etc.

How to properly name java class?

I have two Activity in android, which has respective view to add and edit.
Activity which add user information, I have named this class to AddUserInformation
Another Activity which edit user information, I have named EditUserInformation
As a class naming convention, class name should start with noun. In my case it seems like method name.
How to name properly these classes.So that other developer can easily identify class purpose?
You haven't really grokked the object oriented paradigm it seems. The natural OO design for this would be a User class with member variables representing the "information", e.g. firstname, lastname, etc. Getter and setter methods for the various "information" fields would be used to access and add/update a user's information. Something like this:
public class User {
// these fields represent the user's information
private String firstname;
private String lastname;
// constructor
public User() {
}
// getters are used for accessing information
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
// setters are used for updating information
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
You could use the User class to add and update information like this:
// create a user
User user = new User();
// add some information
user.setFirstname("John");
user.setLastname("Coltrane");
// update some information
user.setLastname("Trane");
// access the user's information:
System.out.println("Hello Mr. " + user.getLastname());
This name denotes method name. User is class as per OOPs concept. As par naming rule class name is defined using Camel case. So UserInformationAdder and UserInformationEditor are proper name.
You should create classes according to object itself, not for business logic level. I can assume you will need a class like DeleteUserInfo later.
Try this: a class named UserInfo, addUserInfo or editUserInfo is just the method name.

public static boolean Equals Method

I have to objects.
Student and Course (both of which have this static equals method)
I also have the driver which my professor wrote and I have been told not to touch.
My goal is to make two arraylists of courses taken by the student, and current courses the student is taking.
My professor gave me all of the methods, I am supposed to fill in the bodies.
I double checked, and the equals method is copied exactly as he wants it to be.
This is a homework problem.
I need to fill in the body of this equals method.
I have tried things like if(this.id == other.getID()) but I keep on receiving this error:
error: non-static variable id cannot be referenced from a static context
I have tried using this.getID() instead but to no avail. I think this probably has something to do with this being static. (I am not allowed to change that.)
What is the correct way to go about writing this? I am not going to include all of the getters and setters in the below code.
public class Student {
private String id;
private String firstName;
private String lastName;
private String major;
private String minor;
private ArrayList<Course> coursesTaken;
private ArrayList<Course> currentSemesterCourses;
private double gpa;
/**
Course constructor
*/
public Student(String id, String firstName, String lastName, String major, String minor, ArrayList<Course> coursesTaken, ArrayList<Course> currentSemesterCourses) {
/*Your code goes here */
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
this.minor = minor;
this.coursesTaken = coursesTaken;
this.currentSemesterCourses = currentSemesterCourses;
}
public static boolean Equals(Object obj) {
//Your code goes here
//base it on id firstName, lastName, major, minor and gpa
}
I think this probably has something to do with this being static. (I am not allowed to change that.)
Then your assignment makes no sense whatsoever and there is no way to solve it.
If you are writing a static equals(Object) method, then you have no Student. There is only one object that got passed in, and it could be any type. "Equals" is a question you ask about two things, and you don't even have two things to compare, you have only one thing that might not even be a Student.
The method you've been asked to write is like asking "Is this object equals?" It makes exactly as little sense as that sentence.

Preferred way of declaring methods in a class

I am having a doubt with method creations in a class for setting information.
creating separate methods for setting each attribute
class Address{
private String name;
private String city;
public setName(String name) { ... }
public setCity(String name) { ... }
}
creating single method for setting all attributes
class Address{
private String name;
private String city;
public setAddress(String name,String city) { ... }
}
from above two ways which is preferable in memory point of view?
Common practice is to use JavaBean style
class Address {
private String name;
private String city;
public setName(String name){
this.name = name;
}
public String getName() {
return name;
}
public setCity(String city){
this.city = city;
}
public getCity() {
return city;
}
}
Another common practise, which is quite similar to you second approach is to create immutable object. Parameters are passed to constructor instead of big setter method.
class Address {
private final String name;
private final String city;
public Address(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public getCity() {
return city;
}
}
From memory point of view, difference would be that second example is setting all attributes in constructor and all those attributes are immutable. In general, object constructed this way are safer when used by multiple threads.
In second example, there is no need for synchronization. You'd need to handle synchronization/memory issues when multiple threads using standard JavaBean object.
I can't see how the two approaches would be any different memory-wise.
Choose the approach that makes most sense to have in the interface of the class.
I would recommend to go with approach 2 only if both properties are logically strongly related, or if there is some class invariant that you don't want to temporarily break (even temporarily).
In your Address example, I would definitely go with two setter methods, since when talking about addresses, the name and city are quite unrelated.
For methods in general I'd say that whether or not you split a method up in two has little effect on memory consumption. Each object doesn't get its own set of methods allocated. The memory containing the methods is shared between all instances of a class.
Rule of thumb: Strive to make the interface of your class clean and logical.
Why not to use method #2
Your second example is not recommended because if you added a new field to the Address class, then do you add it into the existing setter method or do you create a new setter method? If you add it into the existing setter method, then any classes that called that method would be broken. And if you created a new setter method, then it is confusing for anyone who wants to use that class why certain fields are grouped together that way while others are not.
Using a separate setter method for each field that you wish to expose
The common practice is to have a single setter method for each field in your class that you wish to expose (i.e. your first example). Whether or not this is a good practice is debatable because it forces a class to be mutable. It is best to make an object immutable, if possible, for a number of reasons.
Initializing your fields using a constructor
One way to make a class immutable is by getting rid of the setter methods and instead making your fields settable via your class constructor, as below. The downside to implementing it this way is that if your class has a lot of fields, it may potentially lead to large, unreadable constructor calls.
public class Address {
public String name;
public String city;
private Address(String name, String city) {
this.name = name;
this.city = city;
}
}
Initializing your fields using the Builder pattern
Below is a completely alternative implementation (inspired by this article) that is a variation of the Builder pattern. It simulates object mutability without sacrificing readability.
public class Address {
public String name;
public String city;
private Address() {}
private void setName(String name) {
this.name = name;
}
private void setCity(String city) {
this.city = city;
}
static class Builder {
private Address address = new Address();
public Builder name(String name) {
address.setName(name);
return this;
}
public Builder city(String city) {
address.setCity(city);
return this;
}
public Address build() {
return address;
}
}
}
With the above class, you could create an immutable instance of the Address class as follows:
Address address = new Address.Builder()
.name("Mansoor's address")
.city("Toronto")
.build();
Which approach uses more memory?
From a memory point of view, there shouldn't be any difference since the size of a class in memory is dependent on the fields in the class. Since all three implementations have the same fields, they should take the same amount of space in memory, regardless of which approach you use.
This is not a clear question. Do you mean, would you rather have two methods like setFoo(String) and setBar(int), or one method like setFooBar(String, int)? It really depends on whether these are logically different properties, in which case you want individual methods, or whether it often (or only) makes sense to set them together. You could provide both.
Neither has any impact on memory, no.
The JavaBean standard is to have getters and setters for each property: http://en.wikibooks.org/wiki/Java_Programming/Java_Beans. If you don't want to follow that standard convention, its what makes the most sense for your shop. As per other answers on this thread, there probably is a minimal memory delta, if any.
Nb.1 without a doubt.
And you don't write that code by hand, only declare your fields.
Then you let Eclipse do the rest for you.
In Eclipse use Source --> generate getters and setters.
A very similar construct as #2 is done in the objects constructor.
The updated question with regards to memory. Don't worry one second in production code for the memory difference between those two ways.
You generally write a setter and a getter method for each attribute.
I don't really see the case when one method is enough for setting all the attributes. In this case, all attributes should have the same value? Or you always would have to pass parameters for all attributes. Both cases are not really what you want. So you should clearly prefer your first approach.

What's the most object-oriented way to design an address book?

I am asking myself how to design an object-oriented address book in Java.
Let's say a contact can have several contact details, like addresses, phone numbers and e-mail addresses.
One way to implement this would be to give every contact an ArrayList for every type. But there must be a better and more object-oriented solution. What is it?
The most OOP suggestion I can give you is to create a class for every item/piece of information. For example:
public abstract class ContactInfo { /* ... */ }
public class Address extends ContactInfo { /* ... */ }
public class PhoneNumber extends ContactInfo { /* ... */ }
public class EmailAddress extends ContactInfo { /* ... */ }
public class Contact {
private String name;
private Set<ContactInfo> info;
// ...
}
and finally,
public class AddressBook {
List<Contact> contacts;
// ...
}
This may or may not be overkill for your specific case, but as a thought experiment, it's the way to go. It obviously takes care of the literal part of OOP — using objects — but also lays groundwork for encapsulation, abstraction and inheritance, which are closely related principles.
You're on the right track. The only thing I would do differently would be to use a List interface instead of an ArrayList collection to reference the contacts' attribute collections. This is advice based on the code-to-interfaces rule-of-thumb as described in this article and many others.
I don't think that's particularly un-object oriented. If your domain is such that a Person can have zero or more EmailAddresses, then you've almost exactly described the situation to use a list.
The only alternative approach I can think of would be to have fields such as
WorkEmail
PersonalEmail
OtherEmail1
OtherEmail2
OtherEmail3
but in my opinion that's worse, because:
You simply cannot support more than five email addresses (well, you could add more fields, but that increases the pain of the latter points and still imposes some finite limit.)
You're implying some extra semantics than may be present (what if the same address is used for work and personal? What if neither applies, can you just fill the Other ones? What if you don't know the purpose?)
You now have to test each field manually to see which is null, which is going to involve a non-trivial amount of duplication in Java. You can't use nice features like the enhanced-for loop to apply the same block to every email address, and you can't trivially count how many addresses there are
The list of properties that a Person has is now much less clean. I suppose you could package these properties into an EmailContactDetails class or something, but now you've got an extra level of indirection (more conceptual complexity) for no real gain.
So, if a person has a possibly-empty, unbounded list of email addresses, what's wrong with representing that as a list?
You can also use a Map, and then get specific values e.g. via myMap.get("emailAdress1") or iterate over the whole map like you would do with a list via myMap.entrySet().
One simple way to handle most of the use cases can be like this
public class AddressBook {
private Map<String, Contact> contacts;
AddressBook(){
contacts = new HashMap<String, Contact>();
}
public boolean addContact(Contact contact) {
if(contacts.containsKey(contact.getName())) {
System.out.println("Already exists");
return false;
}
contacts.put(contact.getName(), contact);
return true;
}
public boolean updateContact(Contact contact) {
contacts.put(contact.getName(), contact);
return true;
}
}
class Contact{
private String name;
private String email;
private String phone;
private Address address;
public Contact(String name) {
this.name = name;
}
public Contact(String name, String email, String phone, Address address) {
this.name = name;
this.email = email;
this.phone = phone;
this.address = address;
}
// getters and setters
#Override
public String toString() {
return "name is "+name+" and address is "+address;
}
}
class Address{
private String street1;
private String street2;
private String city;
private int zipcode;
public Address() {}
// getters and setters
#Override
public String toString() {
return "street1 is "+street1+" and zipcode is "+zipcode;
}
}

Categories