Home > Software engineering >  Get list from object, modify and set in one line
Get list from object, modify and set in one line

Time:05-12

I need to get List<Example> from the object, add an element to it, and attach the modified list to the object. Is there a wise way to do it in one line? Right now it looks like the following:

List<Example> examples = user.getExamples();
examples.add(example);
user.setExamples(examples);

I thought about smth like this:

user.setExamples(user.getExamples().add(example));

but it does not work due to that add returns true

CodePudding user response:

If you really want to use it in one line, then this is one of approach which might suits your requirement.:

 user.getExamples().add(example);

CodePudding user response:

In object-oriented programming, you should think in terms of asking an object to "do its thing" rather than you trying to manipulate its innards from outside.

So rather than extract, manipulate, and re-inject, simply ask that object to add an item. You don't even know if there is a list inside that object. Let the object take care of tracking items as it sees fit.

user.addExample( myExample ) ;

In other words, having getters and setters is often a sign of poor object-oriented design.

If you insist on external modifications:

  • If you know for certain the list returned by the getter is (a) the same list maintained within the object (generally a poor design) and is (b) modifiable, then you can use the approach seen in the Answer by Patil where you call List#add on the object returned by the getter. I would add an if test to verify you got back true, as a false means the addition failed.
  • If you want to pass the modified list to a setter method, then as you have seen, you cannot do so in a single line because the method return boolean. For a fluent-style syntax, you would need an addition method that returned a reference to the list itself.

To use the setter, you must make multiple statements.

List< Example > list = user.getExamples() ;
if( list.add( myExample ) ) 
{
    user.setExamples( list ) ;
} else 
{
    … handle failure …
}

If that returned list is not modifiable, you'll need to make a new one. Pass the unmodifiable list to the constructor.

List< Example > list = new ArrayList<>( user.getExamples() ) ;
if( list.add( myExample ) ) 
{
    user.setExamples( list ) ;
} else 
{
    … handle failure …
}
  • Related