2

I have a base class: "Working Items". Witch is extended by 3 subclasses: "Bug", "Story", "Feedback". I receive a command from the console (String), to list all types of Working Items, or one specific type (Bug, Story, Feedback). I have a collection of type WorkingItems, which contains all of the 3 above mention subclasses. How can I validate while looping the collection if the current object is Bug, Story or Feedback (I can't use instanceof)?

I don't want to divide the collection of Working Items into 3 smaller collections of Bugs, Stories, Feedbacks.

private String listAllWorkingItems(StringBuilder result) {
        WIMRepository.getWorkItemList().forEach(workItem -> result.append(workItem.toString()));
        return result.toString();
    }

    private String listAllStories(StringBuilder result) {
        WIMRepository.getWorkItemList(); //TODO
        return result.toString();
    }

    private String listAllBugs(StringBuilder result) {
        WIMRepository.getWorkItemList() //TODO
        return result.toString();
    }

    private String listAllFeedbacks(StringBuilder result) {
        WIMRepository.getWorkItemList() //TODO
        return result.toString();
    }

The result should be like this:

Command: show all Result: "printing working items collection"

Command: show bugs Result: "printing only the bugs from working items collection"

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Tropicano
  • 281
  • 2
  • 15

1 Answers1

0

Correct me if I am wrong, but I don't see any point in having 3 subclasses.

enum WorkingItemType {
    BUG, STORY, FEEDBACK;
}
class WorkingItem {
    private WorkingItemType type;

    public WorkingItemType getType() {
        return type;
    }
}

You didn't show why you've chosen that way, and I am assuming that two classes (WorkingItem and WorkingItemType) would be enough, which would make the method listAllBugs as simple as

WIMRepository.getWorkItemList().stream()
        .filter(i -> WorkingItemType.BUG.equals(i.getType()))
        .forEach(i -> result.append(i.toString()));

Moreover, one general method would be enough.

WIMRepository.getWorkItemList().stream()
        .filter(i -> WorkingItemType.valueOf(input.toUpperCase()).equals(i.getType()))
        .forEach(i -> result.append(i.toString()));

instanceof is rarely a good choice, so it's nice that the requirements prohibit it.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • The different subclasses (Bug, Story, Feedback) have additional fields that are different, as well as different methods. – Tropicano Oct 12 '19 at 12:24
  • @SAndreev it keeps my answer valid if you add a type field in their base class and will be checking it instead of `instanceof` – Andrew Tobilko Oct 12 '19 at 12:26