Why should I create function Add? [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 5 years ago.
Improve this question
Most of expert programmer here have down voted my answer as bad answer
How to add a field to an ArrayList from a different class?
So, I wonder why do I need to create another function Add to add items to my list. While most of programming language such as Java C# and VB.NET allow us a very simple way by using Getter as a List or ArrayList that we be able to add and use many function that this class has directly as sample as bellow
C#
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee();
emp.lst.Add("Hello");
}
}
class Employee
{
private List<string> _lst = new List<string>();
public List<string> lst
{
get { return _lst; }
}
//public void add(String item) {
// _lst.Add(item);
//}
}
Java
public class MainApp {
public static void main(String[] args){
Employee emp = new Employee();
emp.getLst().add("My String");
}
}
class Employee{
private List<String> lst = new ArrayList<String>();
public List<String> getLst() {
return lst;
}
public void setLst(List<String> lst) {
this.lst = lst;
}
}
Most of languages are allow us to do this ways. So, what is the reason I need to create function Add for on Employee?

Practical reason: getList() may return either internal list or copy of that list. There is no way for consumer of the class to know what is the behavior of the method without knowing implementation of getList() (or less likely find and read documentation on that particular method of particular class). So adding to or modifying result of getList() call in any other way may never change the original object and proving correctness will require reading all the code including (frequently private) implementation of getList().
Whether it is useful to expose separate methods to add to the list or not is personal choice based on particular code. Generally it is better to provide specific methods for all operations on the object as one can guarantee consistency of the state of the object.
For example if object is plain data transfer object having raw lists is fine there, but if it is Student exposing modifiable list of classes may easily lead to inconsistent state if for example total score class is stored independently.

Related

Understanding Java 8 Lambda Expressions [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 2 years ago.
Improve this question
I was reading this article on Java 8 and had the following questions/comments I would appreciate some feedback/response.
1) Is the #FunctionalInterface declaration necessary for the following code? Or could this same code be executed without it and it is for documentation purposes? It is unclear from whether it is necessary from the article.
#FunctionalInterface
private interface DTOSender {
void send(String accountId, DTO dto);
}
void sendDTO(BisnessModel object, DTOSender dtoSender) {
//some logic for sending...
...
dtoSender.send(id, dto);
...
}
2) In general, can a function be passed as an argument to another function in Java 8? My understanding is only data types can be passed as arguments to functions, so I suppose it is not possible as a function is not a data type.
3) Do I need to do anything special to accomplish #2 above or can I just write my definitions of the 2 methods and just pass the one method as a parameter to the other method?
4) Can objects be passed as arguments to another function in Java 8? Do I need to do anything special to accomplish this or can I just write my definitions of the object and method and just pass the object as a parameter to the method?
#Functional Interface is just a hint, so that you don't put more methods into your interface.
It can. Many methods on Stream take functions as parameter: Stream.of(1, 2, 3).forEach(System.out::println).
Lambda is a function instance: Function<Integer, Integer> f = a -> a + 1. Edit: you can pass a function by name using method reference (see 2., println is a regular method).
I don't fully get the question. If the method consumes any argument, that is not primitive, it takes an object (everything in java except for primitives is an object).
The annotation #FunctionalInterface is not mandadory as the doc states.
In order to pass a function to your method, there has to be a matching functional interface.
interface ListFilter<T> {
boolean test(T item);
}
public static <T extends Comparable<T>> List<T> filter(List<T> list, ListFilter<T> filter) {
List<T> filteredList = new ArrayList<>();
for (T t : list) {
if (filter.test(t)) {
filteredList.add(t);
}
}
return filteredList;
}
public static boolean isNumberGreaterThan2(Integer integer){
return integer > 2;
}
public static void main(String[] args) {
List<Integer> list = List.of(1, 2, 3, 4);
filter(list, new ListFilter<Integer>() {
#Override
public boolean test(Integer item) {
return item > 2;
}
});
// or
filter(list, item -> item > 2);
// or
filter(list, Main::isNumberGreaterThan2);
}

Best factory implementation [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 6 years ago.
Improve this question
So because I'm currently reading into design patters I have a "newbie" and at least for me interesting question to ask.
What Factory implementation is the best? I've seen factories where the create method is hardcoded and if a new subtype is added I'll need to edit the method. For example:
public class ProductFactory{
public Product createProduct(String ProductID){
if (id==ID1)
return new OneProduct();
if (id==ID2) return
return new AnotherProduct();
... // so on for the other Ids
return null; //if the id doesn't have any of the expected values
}
...
}
This seems to be the implementation that takes the lowest amount of resources. But furthemore I've seen implementations that use reflection:
class ProductFactory
{
private HashMap<String, Class> m_RegisteredProducts = new HashMap<>();
public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}
public Product createProduct(String productID)
{
Class productClass = (Class)m_RegisteredProducts.get(productID);
Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] { });
}
}
Which seems to be the slowest one because it is using reflection to work. And the last implementation seems to take the most RAM because it has an extra instance of a specific class stored.
class ProductFactory
{
private HashMap<String, Product> m_RegisteredProducts = new HashMap<>();
public void registerProduct(String productID, Product p) {
m_RegisteredProducts.put(productID, p);
}
public Product createProduct(String productID){
((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}
Product classes for the last factory:
abstract class Product
{
public abstract Product createProduct();
...
}
class OneProduct extends Product
{
...
static
{
ProductFactory.instance().registerProduct("ID1", new OneProduct());
}
public OneProduct createProduct()
{
return new OneProduct();
}
...
}
Both the second last and last implementation allow to register new products without modifying the factory class in for example a static block in the to be registered product extending/implementing class. Is this better? And if so, which of those two implementation is the better one? Or is the hard coded implementation better because it seems to require less resources.
Approach 1) Parametrized Factory implementation. Overtime we create a new Product object we have to modify the Factory.
Approach 2) We dont need to modify the Factory in order to add a new implementation. In addition the factory needs to know in advance all the available classes in order to begin instantiating them. Performance is not a factor here because on a modern JVM the performance loss from reflection will be negligible.
Approach 3)If I understand correctly the Product is exposing a factory method. Each implementation of Product through Polymorphism is responsible for providing logic for instance creation. Although I dont get it how you will use exactly a non static method. And if you use static you loose your Polymorphism. Approach 3 is not very clear to me. Is the Product actually a Wrapper around the real Product ?
Approach number 1 is least flexible

instantiation of objects of other classes in java [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 8 years ago.
Improve this question
i have this situation:
public class Number {
int num;
private TakeNumber take = null;
public Number() {
num = 5;
}
public void print() {
take.doSomething();
}
public int getNumber() {
return num;
}
public static void main(String[] args) {
new Number();
}
}
public class TakeNumber {
private Number number = new Number();
public void doSomething() {
System.out.println(number.getNumber());
}
}
Now, can someone explain me these situations:
I want to know what the compiler interprets here : private Number number = new Number();
Initialize the object in question and passing the required methods
Is correct initialize one object to null and then call a function on that object, as shown
in brief
I would like to know if you can call a method of a class of another class:
without the required function to be static
IMPORTANT do not inherit the classes because I want to use methods of these classes, for example:
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
I would like to know if you can call a method of a class of another class:
without the required function to be static
If the methods are not static, then you will need an instance of that object to call it.
Object o = new Object();
o.doSomething();
Is how you access an instance method.
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
This is fine. This is called composition. Composition is a has a relationship between classes. A class Man has a class Car, but Is a class Person. And it is perfectly valid to write code as you have shown. This is how you use composition to expose only the interface of a composite object that you want. For example..
public class MyClass extends MyOtherClass
Now you've just exposed the whole interface of MyOtherClass. This might not be desired.
public class MyClass {
MyOtherClass otherClass;
public void doSomething() {
otherClass.doSomething();
}
}
Now, you've only exposed the doSomething() method. This is useful when, as you said, your objects are conceptually different, but require some shared functionality. It is a perfectly valid code practise.
NOTE: Given the confusing nature of your question, I imagine I've missed some stuff out so please comment with desired edits.

Java - Best way to return multiple object types from a method [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 6 years ago.
Improve this question
In my DAO i have a method where i build 2 different objects and I want to return both of those objects, but i'm not sure what the best way is to do it. I've looked at using ? extends myObject, creating another class that holds both of my objects that i want to return, and just using List<Object>.
Long story short on why i need these similar objects is to display 1 on the screen and the other to use with primefaces dataexporter which doesn't handle lists in an object as far as i'm aware.
Class Person
public class Person() {
firstName = null;
lastName = null;
List<Programs> programs = new ArrayList<Programs>();
// Getters and setters
}
Class DataExporterPerson
public class DataExporterPerson() {
firstName = null;
lastName = null;
String program = null;
// Getters and setters
}
DAO method:
public List<SOMETHING> getPeople() {
// query db for people
// build both objects
return ?????
}
Now i understand i can very easily create another object like the one below, but that seems like an inefficient way to do things because i'm basically creating an object just to return from 1 method.
public class PersonTransporter() {
Person person = null;
DataExporterPerson = null;
}
What is the best way to handle this scenario?
EDIT
The reason that i'm trying to return 2 objects in 1 method is because this is a DAO method that queries the database and builds 2 objects based on the data in the query. I don't want to break it up into 2 methods because i don't want to query the db twice if i don't need to.
You can either handle this through inheritance, or containment.
You can have Person and DataExporterPerson extend something like AbstractPerson. However, since you have not already done so, then it is probably inappropriate to do inheritance.
I think it was Effective C++ that talked about how containment is better than inheritance. IIRC the reason stated is that containment is more loosely coupled than inheritance.
Here you would have a object that contains both Person and DataExporterPerson. Your method would populate one of those for this union type object, and by seeing which one is null you would know which one you actually have.
public class DBPersonUnion {
private Person person = null;
private DataExporterPerson dataExporterPerson = null;
//getters and setters.
}
If your method need to return two different types this is a hint that there is something wrong with your architecture or method logic.
What you can do ?
Create a class that will logically join the elements,
Introduce common interface that, both class will implement,
Implement two methods fist return with object, that second use a parameter and return the second object.
The example for last point
class Foo {
String f;
}
class Bar {
String b;
}
Then problem how to return object Foo and Bar ?
public Object theProblemMethod() {
Foo a = new Foo();
a.foo = "Test";
Bar b = new Bar();
b.bar = a.foo; //The logic where class Foo meet class Bar.
return ???
}
The valid implementation
public Foo createFoo(){
Foo a = new Foo();
a.foo = "Test";
return a;
}
public Bar createBar(Foo f) {
Bar b = new Bar();
b.bar = f.foo;
reutrn b;
}
Usage
public void action() {
//theProblemMethod(); //This we can not do
Foo a = createFoo();
Bar b = createBar(a);
}
Your actual issue here is one of design. No method should be doing more than one thing: therefore a method that returns two unlike objects is probably bad design. To actually solve this problem, you should break your method into two, separate methods to handle the two different concerns.
However, let us assume you cannot do this. Based on your notes it seems most of your state in the two objects is repeated. You can combine these two by having them inherit from a similar source - but this only solves half your problem. Instead, you can decorate the one with the other:
public class DataExporterPerson {
private Person person;
private String program = null; //or any other
//other getters/setters, esp to get the core 'person' object.
//note that getters/setters for repeated state should just
// pass through to the underlying object:
public String getName() { person.getName(); } //for example
}
If you absolutely must return two objects, you may do this, but it's hard to test and violates the 'no side effect' principle:
public boolean buildThings(ThingA a, ThingB b) {
a = <whatever>;
b = <whatever else>;
return true;//success!
}
//...
//somewhere else in code
ThingA a = null;
ThingB b = null;
boolean result = buildThings(a, b);
//use a and b here
You could do two different things.
The first have the method signature be public List<Object> getPeople(). This will allow you to do instanceof and figure out which is which.
OR
you could have DataExporterPerson extend Person (or make a new class/interface that both DataExporterPerson and Person extend/implements and use that as the type).

why java does not support dynamic variable dispatch [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 9 years ago.
Improve this question
Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass.
following is the code that raised the doubt
class Test {
public int a = 10;
}
class TestChild1 extends Test {
public int a = 20;
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.a); // results in 10
}
}
Please give me the reasons for this behavior. Thanks in advance....
Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.
When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.
When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.
OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.
The class TestChild1 has two variables with the same name. If you access them through Test you get the first one, from TestChild1 you get the second one.
To get your expected result, you should not declare a in the derived class. Instead you should initialize it in the costructor of the derived class.
You declared your object as Test, not the subclass. At compile time that means you refer to the base class which has 10.
Because behavior is associated with methods and not with fields.
So, fields have static binding (in this case this, since test is of type Test, value of a is assigned with value 10). Whereas methods have dynamic binding.
Since, the variable a doesn't define the behavior of Test class, it is assigned the value as per its type and not as per its instance.
JB Nizet have already said everything, but I will add this code for more understanding:
class Test {
private int a = 10;
public int getA() {
return a;
}
}
class TestChild1 extends Test {
private int a = 20;
public int getA() {
return a;
}
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.getA()); // results in 20
}
}
So if you would encapsulate your fields, you would have expected behaviour.

Categories

Resources