[java] How to implement a simple scenario the OO way

After starting to read a book on OO programming, I am attempting to make my android app more OO. However I am stumped on a simple scenario.

I have a Book object, which can have many say Chapter objects. I also have a search function which searches across multiple books, 97 of them. I end up with many Chapter objects from the Sqlite table.

I felt that it would be useful to the user to be able to see the title of the book on each result, otherwise it might be confusing if there are say two "chapter 5" results.

For that to happen, I need the book title. Should I make it part of my chapter object, like :


Which kind of does not seem right, as I have glued the book name onto a chapter... The alternative is to instantiate a book object for each chapter and somehow reference it, which has its own problems including in android with regards to not being able to pass a reference to an in-memory object to another activity.

Also a book may have many other chapters which were not results in the search, and it may seem like they would return if I was to just instantiate the book.

What is the correct OO solution to this seemingly simple issue? Is it just a matter of learning when not to be dogmatic about the whole OO thing?

More Info:

I am using FTS4 in Sqlite, which accounts for over half of my actual DB size of 80mb. What I am storing is text from 97 books, with chapters in 4 languages. So my FTS at the moment stores:

ChapterId, ChapterNo (withinBook), Lang1, Lang2, Lang3, Lang4, Tags, Notes 

The searching is very fast, I retrieve only 50 results. I match any column with a string term, and not one column in particular. So if I type "apple" it will search all the fields above.

Currently as part of my FTS query I am join a join onto Book, fetching the BookId, I later use that to get me the title of the book. However its all in a procedural like style, with no regard to where the information "belongs".

I need the title so I can display it in the results, just for user convenience.

It works well, however I am wanting similar performance or slightly less but with an OO approach as I think that will make more sense to me when I come back to this project after a long pause.

This question is related to java android oop design-patterns

The answer is

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:


  • id
  • book specific info
  • etc


  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with android tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8? "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' GoogleMaps API KEY for testing Can I use library that used android support with Androidx projects. How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Android Material and appcompat Manifest merger failed Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to format DateTime in Flutter , How to get current time in flutter? How to change package name in flutter? Failed to resolve: com.android.support:appcompat-v7:28.0 What is AndroidX? Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve FirebaseInstanceIdService is deprecated installation app blocked by play protect Handling back button in Android Navigation Component Android design support library for API 28 (P) not working Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Install Android App Bundle on device Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. How to develop Android app completely using python? Invoke-customs are only supported starting with android 0 --min-api 26 Flutter.io Android License Status Unknown How to open Android Device Monitor in latest Android Studio 3.1 Default interface methods are only supported starting with Android N How can I change the app display name build with Flutter? Error:(9, 5) error: resource android:attr/dialogCornerRadius not found error: resource android:attr/fontVariationSettings not found Flutter does not find android sdk Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0) Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior flutter run: No connected devices Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation' PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Questions with oop tag:

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>? What is the difference between dynamic and static polymorphism in Java? C# : assign data to properties via constructor vs. instantiating How should I have explained the difference between an Interface and an Abstract class? Classes vs. Functions JavaScript OOP in NodeJS: how? Constructors in Go What is difference between functional and imperative programming languages? How abstraction and encapsulation differ? When do I have to use interfaces instead of abstract classes? C# : Converting Base Class to Child Class Nested or Inner Class in PHP Simple way to understand Encapsulation and Abstraction C++ error 'Undefined reference to Class::Function()' fatal error LNK1169: one or more multiply defined symbols found in game programming Already defined in .obj - no double inclusions Pass arguments to Constructor in VBA JavaScript Extending Class Difference between Encapsulation and Abstraction best way to create object String Array object in Java What does 'low in coupling and high in cohesion' mean What are abstract classes and abstract methods? Can we instantiate an abstract class? PHP: Calling another class' method Clone Object without reference javascript Meaning of @classmethod and @staticmethod for beginner? Why do we assign a parent reference to the child object in Java? encapsulation vs abstraction real world example Abstraction vs Encapsulation in Java How to call a parent method from child class in javascript? Iterate over object attributes in python jQuery creating objects How to check if an object implements an interface? What is the difference between __init__ and __call__? Separating class code into a header and cpp file Encapsulation vs Abstraction? Can we cast a generic object to a custom object type in javascript? Private vs Protected - Visibility Good-Practice Concern calling a function from class in python - different way Class vs. static method in JavaScript

Questions with design-patterns tag:

How to implement a simple scenario the OO way Implementing Singleton with an Enum (in Java) What is difference between MVC, MVP & MVVM design pattern in terms of coding c# Best Practices for mapping one object to another REST API Login Pattern When should we use Observer and Observable? How to implement a FSM - Finite State Machine in Java Function in JavaScript that can be called only once Thread Safe C# Singleton Pattern Repository Pattern Step by Step Explanation ViewPager and fragments — what's the right way to store fragment's state? Java JSON serialization - best practice What are the differences between Abstract Factory and Factory design patterns? Android Button setOnClickListener Design What is the facade design pattern? How to implement the factory method pattern in C++ correctly When to use which design pattern? Builder Pattern in Effective Java Which Architecture patterns are used on Android? Business logic in MVC Singletons vs. Application Context in Android? tar: add all files and directories in current directory INCLUDING .svn and so on Design Patterns web based applications Facebook Architecture JavaScript pattern for multiple constructors MVC pattern on Android Why is IoC / DI not common in Python? What's an Aggregate Root? Naming Classes - How to avoid calling everything a "<WhatEver>Manager"? Examples of GoF Design Patterns in Java's core libraries Javascript: best Singleton pattern Simplest/cleanest way to implement a singleton in JavaScript Is there a Java equivalent or methodology for the typedef keyword in C++? C++ Singleton design pattern What is the basic difference between the Factory and Abstract Factory Design Patterns? What are static factory methods? What is a wrapper class? What is the difference between Builder Design pattern and Factory Design pattern? What design patterns are used in Spring framework? Why is __init__() always called after __new__()? What is the difference between MVC and MVVM? Dependency Injection vs Factory Pattern Difference between static class and singleton pattern? Modelling an elevator using Object-Oriented Analysis and Design Is it possible to create static classes in PHP (like in C#)? Handling Dialogs in WPF with MVVM When would you use the Builder Pattern? Does functional programming replace GoF design patterns? How to study design patterns? When should I use the Visitor Design Pattern?