Java how to good practice : Map in Utility Class [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Can I use a utility class like this?
public final class ProfessorDirectory {
private static Map<String, Professor> directory = new HashMap<>();
private ProfessorDirectory() {
throw new IllegalStateException("Utility Class");
}
static void addProfessorsFromDescription(String description) {
String regex = "(?<=\\n).* .*(?=\\n)";
Matcher m = Pattern.compile(regex).matcher(description);
while (m.find()) {
String professorName = Professor.formater(m.group(0));
directory.put(professorName, new Professor(professorName));
}
}
public static Professor get(String firstName, String lastName) {
return directory.get(Professor.formater(firstName, lastName));
}
}
I used this to create a library in which you can retrieve a teacher's planning.
Exemple of utilisation:
Planning professorPlanning = schedules.getPlanningOf(ProfessorDirectory.get("Jack", "Sticky"));
The ProfessorDirectory is initialized internally, and should never be initialized by the user.

There are a few disadvantages to this approach, that is, the approach of having static data and methods.
You can never have more than one ProfessorDirectory, even if you find it would be useful to have several.
It is difficult to test clients of ProfessorDirectory, because they must use the real code instead of being able to mock an interface.
You rule out using some useful patterns. For instance, you can't write a caching proxy that implements a ProfessorDirectory interface and wraps an arbitrary implementation of that interface.
Overall this is a bad approach.

Related

Is it good to create new object if pointer is null just to get its fields or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Is it good to write like this?
UserInfo myMethod(User user) {
user = Optional.ofNullable(user).orElse(new User())?
String name = user.getName()
String type = user.getType();
return new UserInfo(name, type);
}
Or better use standard way:
UserInfo myMethod(User user) {
if(user == null) { return null }
String name = user.getName()
String type = user.getType();
return new UserInfo(name, type);
}
Could also someone help with good null safety best practice links?
The first version looks pretty much a code smell: you return a UserInfo object corresponding to a null User. This seems like a counter-intuitive approach, and can lead to all sorts of validation problems if the fields name and type are unspecified. The second version is better because it just returns null if the user is null. Another approach is to enforce the caller to pass a non-null argument using:
UserInfo myMethod(User user) {
Objects.requireNonNull(user);
...
}

How to create a new List<A> from an existing List<B> using lambda without function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an existing List of type "A". I want to create a new list of type "B" from this list. Class "B" shares some common fields with Class "A" as shown in the example below. preferably, I like to avoid using any function calls from the lambda.
public class A{
int quantity;
String description;
int refNumber;
Date timeStamp;
}
public class B{
int quantity;
String description;
}
Thanks
I have two solution for you without using stream.map but both of them look ugly and I would recommend a proper and clean solution with a map function.
List<BObject> listB = list.stream().collect(Collectors.mapping(a -> new BObject(a.quantity, a.description), Collectors.toList()));
or
List<BObject> listB = list.stream().collect(ArrayList::new, (listBa, a) -> listBa.add(new BObject(a.quantity, a.description)), ArrayList::addAll);
Now let's compare solutions above to this:
List<BObject> listB = list.stream().map(BObject::new).collect(Collectors.toList());
or this
List<BObject> listB = list.stream().map(a -> new BObject(a.quantity, a.description)).collect(Collectors.toList());
I think the last two versions look much better but require additional constructors in BObject class

Setters on objects Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hello so I'm having a bit of difficulties with a setter method on objects.
public class Company {
private String companyName;
public static int numberOfEmployees;
public Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
Employees employee1 = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());
employees[numberOfEmployees] = employee1;
numberOfEmployees++;
}
So basicly this is a method defined in the 'company class' while making an Employees object who's using the parameters for making a 'Programmer'.
But that's not the deal, what I want tot do is by calling this setter method, automaticly create an object. So each time it's used, kind of increment the name of the object it's going to make.
So for example the first time I use it it makes an object called Employee1 and stores it in Employee[0].. second time I want it to store Employee2 into Employee[1].
Maybe I'm making this way too difficult but I'm just trying things out, and can't seem to find a way to make this work.
I suppose that Programmer object is subclass of Employees, or else it will not work. More or less it should look like the following:
public class Company {
private String companyName;
public static int numberOfEmployees;
public static Employees employees[];
public void setEmployees( String name, String heritage, String [] programmingLanguages, Salary d) {
numberOfEmployees++;
employees[numberOfEmployees] = new Programmer(name, heritage,programmingLanguages, d,d.getBasicBrutoSalary());;
}

What is the easiest way to fetch the entity value in java giving other attributes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
What would be the easiest way to fetch the value given from, to as arguments. Should I iterate and find or is there a more elegant way?
FOO.java (from, to, value)
public static FOO ONE = new FOO(6000000, 7000000, "60 - 70");
public static FOO TWO = new FOO(7000000, 8000000, "70 - 80");
public static FOO THREE = new FOO(8000000, 9000000, "80 - 90");
private static List<FOO> VALID_FOOS = new ArrayList<FOO>();
VALID_FOOS.add(ONE);
VALID_FOOS.add(TWO);
VALID_FOOS.add(THREE);
Nowadays one would use streams, I'd say (though this would be more suitable if from and to define a range and you search by a single value within the range):
List<String> wanted = VALID_FOOS.stream()
.filter(foo -> foo.from == from & foo.to == to)
.map(foo -> foo.value)
.collect(Collectors.toList())
If you want to use the map-approach you'd need to have a structure somewhat on that line (you can find more on Tuples here):
public class FOO {
public final Tuple<Integer, Integer> range;
public final String value;
}
Map<FOO, String> VALID_FOOS ...
and retrieve your wanted foo by
VALID_FOOS.get(new Tuple(from, to));

Java - refering to an object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm new in Java and I'm trying to create a social network. I have a array of objects "People" which their names, e-mails and so on. I would like to create relations between them (like 'friends') so that program would connect two object.
I though about doing another array inside of every "Person" object, so each person would have a name, e-mail and friend array with all friends inside of it. I don't know how to refer to an other object of type People inside of object of this type.
I don't know if it's clear..
Hope it is!
Thank You in advance!
Here's one way:
public class Person {
private String name;
private String email;
private List<Person> friends;
// Leave the rest for you.
public void addFriend(Person p) {
if (p != null) {
this.friends.add(p);
}
}
public void removeFriend(Person p) {
this.friends.remove(p);
}
public boolean isFriend(Person p) {
return this.friends.contains(p);
}
}
You'll want constructors and a way to add and remove Person from your friend List.

Categories

Resources