0

Let's say I have a class named Program which is made of an arraylist of Expression(s) + a name attribute like so:

public class Program extends Expression {

  private String _name;
  /*Storage for expressions.*/
  List<Expression> _expressions = null;

  /*Program constructor*/
  public Program(String name) {
        _name = name;
        _expressions = new ArrayList<Expression>();
      }

Then I have a class named interpreter that is supposed to convert the input into objects of the class Program and is also supposed to store these objects associating a name with them.

public class Interpreter implements Serializable {
  Program _program;

  public Interpreter(){
  }

  public void createProgram(String program_name){
    Program program = new Program(program_name);
    _program = program;
  }

My question is if it's bad practise or even viable to store the objects like I did above if the Program class already has the name attribute I need, and just reference the object by its name when I need it or if I should create an array list of Program type in the interpreter class to store these.

I'm having a bit of trouble wrapping my head around some of the concepts of OOP and I was wondering if I just keep creating objects of the Program type through the interpreter and don't reference them anywhere later, they will eventually disappear right?

I should also be able for example to get a program from the interpreter through a method like this for example.

  public Program readProgram(String filename){
       return getProgram(filename);
}
spacing
  • 730
  • 2
  • 10
  • 41

1 Answers1

0

It depends on the application design. E.g. to check whether Expression can be a part of program, you need to consider the following:

  • Can an Expression exist independently?
  • Can an Expression be linked to more than one program?

If answer of any of the above questions is yes then we need to have independent entity of Expression and we can store mappings between Expression and Program.

Now, for the question of storing the 'name' attribute in Program, I would recommend having a look at this SO answer and this article which basically explain the difference between Composition (i.e. the one which you have tried) and Inheritance (another approach).

If all the entities share same properties (e.g. name, created date etc) then it's recommended to create an Abstract class and make these classes extend that class.

Community
  • 1
  • 1
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102