DEV Community

Singleton, LINQ, and the bugs I found later in my C# library system

This is the third project I have written up from my GitHub, and it is the one where the design decisions are easiest to defend in a README and hardest to defend in the code.

A library management console app sounds like a beginner exercise, but it forces you to answer real questions: who owns the book list, how do two roles share one data store, and what happens to a book when someone borrows it.

The repository is here: https://github.com/AGA7474/Library-Management-System-Advanced-OOP

The shape of the model

Two roles, one base class:

internal class User { public string Name { get ; set ; } public void Display ( ) { Library lib = Library . GetObject ( ) ; lib . Display ( ) ; } }
internal class Librarian : User { /* Add, Remove */ }
internal class LibraryUser : User { /* BorrowBook, DisplayBorrowedBooks */ }

A book is a plain data holder with one interesting detail, the ID:

internal class Book { private static int StaticID { get ; set ; } public int Id { get ; private set ; } public string Title { get ; set ; } public string Author { get ; set ; } public double Price { get ; set ; } public int Year { get ; set ; } public bool IsBorrowed { get ; set ; } public Book ( ) { Id = ++ StaticID ; } }

Id has a private setter and is assigned in the constructor from a static counter, so nobody outside the class can invent an ID. That part I still like.

It also means IDs are never reused: remove book 3, add another book, and the new one is 4. For a console app that is fine. For anything that prints receipts it is actually the behaviour you want.

The singleton, and what it cost me

The whole system shares one Library instance:

internal class Library { List < Book > Books = new List < Book > ( ) ; List < Book > BorrowedBooks = new List < Book > ( ) ; static private Library lib = new Library ( ) ; private Library ( ) { } public static Library GetObject ( ) { return lib ; } }

The private constructor plus the static field means there is exactly one book list in the process, and both the librarian menu and the user menu are looking at it. That solved the actual problem I had, which was two menus each building their own list and losing each other's changes.

What it cost me is visible in the derived classes:

internal class LibraryUser : User { public LibraryCard Card ; public List < Book > UserBorrowedBooks = new List < Book > ( ) ; Library lib = Library . GetObject ( ) ;

Every class that needs the library reaches out and grabs the global at field-initialisation time. Nothing in the constructor signature says "this class needs a library". If I wanted to test LibraryUser on its own, I could not hand it a fake library, because the dependency is baked into the field.

Today I would pass Library into the constructor and keep one instance alive in Main instead. Same single instance, no global.

The other cost is state. The list lives as long as the process, so there is no clean way to start a second session with an empty library, and no way to save it to disk. The README calls this "state persistence", which is generous: it persists while the console window is open and not one second longer.

Overloading instead of polymorphism

Removing a book works by ID or by title, and I implemented that as two overloads on Library:

public void Remove ( int id ) { if ( id <= 0 ) { Console . WriteLine ( "Invalid ID" ) ; return ; } Book book = Books . FirstOrDefault ( x => x . Id == id ) ; if ( book != null ) { Books . Remove ( book ) ; Console . WriteLine ( "The book Removed successfully " ) ; } else { Console . WriteLine ( "The Book is not in the Library." ) ; } }
public void Remove ( string title ) { Book book = Books . FirstOrDefault ( b => b . Title . Equals ( title , StringComparison . OrdinalIgnoreCase ) ) ; . . . }

Two things I would keep and one I would change. Keep: the title comparison uses StringComparison.OrdinalIgnoreCase rather than lowercasing both sides, which is the right call because ToLower() allocates a string per comparison and behaves differently under some cultures. (I had the ToLower() version first, and it is still sitting in the file as a comment.) Keep: id <= 0 is rejected before the lookup.

Change: the overloads are not polymorphism. Overloading is the compiler picking a method by argument type; polymorphism is one call site behaving differently per object. The README lists this under "Polymorphism", and that is the kind of sentence a reviewer notices, so I am calling it out myself. The real polymorphism in this project is Librarian and LibraryUser sharing the User base.

The display bug

Here is Display, the method both roles call:

public void Display ( ) { if ( ! Books . Any ( ) ) { Console . WriteLine ( "Library is empty." ) ; return ; } var availableBooks = Books . Where ( b => ! b . IsBorrowed ) . ToList ( ) ; foreach ( var book in availableBooks ) { Console . WriteLine ( $ "ID: {book.Id} | Title: {book.Title} | Author: {book.Author}" ) ; } }

The empty check looks at all books. The loop prints only the ones that are not borrowed. So once every book is out on loan, the librarian sees a blank screen with no message at all, because the library is not empty, it is just fully lent. That is a small bug with a big lesson: the guard and the query have to be about the same set.

Borrowing, and the missing half

LendingBooks does four jobs at once:

public Book LendingBooks ( ) { if ( ! Books . Any ( b => ! b . IsBorrowed ) ) { Console . WriteLine ( "Sorry, no books available for borrowing right now." ) ; return null ; } lib . Display ( ) ; Console . WriteLine ( "Please enter the ID of the book you want to borrowe" ) ; int . TryParse ( Console . ReadLine ( ) , out int id ) ; Book book = lib . Search ( id ) ; if ( book != null && ! book . IsBorrowed ) { BorrowedBooks . Add ( book ) ; book . IsBorrowed = true ; return book ; } else { Console . WriteLine ( "Invalid ID ! " ) ; return null ; } }

The check for "is there anything to lend at all" comes first, so a fully borrowed library says so instead of asking for an ID and failing. IsBorrowed flips, the book moves into BorrowedBooks, and the user's own UserBorrowedBooks list gets it too.

The half that is missing is the return. There is no ReturnBook, so IsBorrowed is never set back to false, and the only way a book becomes available again is a restart. It is the first thing I would add: a return method that removes the book from both lists, clears the flag, and (in a real system) records a due date.

The loop that never ends

The menu in Program.cs reads the role with a parse that cannot fail loudly:

int . TryParse ( Console . ReadLine ( ) , out int userType ) ;

If the user types letters, TryParse returns false and userType stays 0. The outer loop then enters the inner loop, neither userType == 1 nor userType == 2 matches, so the else prints "Invalid choice" and the inner while (true) runs again, forever, with no break reachable from that state.

TryParse did its job: no exception. It just moved the failure from a crash to a hang, which is worse. The fix is boring and correct: check the return value and loop back to the role prompt when it is false. I used TryParse in every input in this project for exactly this reason, and this is the one place where I used it and ignored the boolean it returns.

What I would change now

  • Inject Library through the constructor instead of calling Library.GetObject() from fields.
  • Move Console.ReadLine() out of Library into the menu layer. A data class that asks the user a question cannot be tested or reused.
  • Add ReturnBook and a loan record per user, with dates.
  • Make Display print borrowed books too, or say "all books are currently borrowed".
  • Keep the private-setter ID and the OrdinalIgnoreCase comparison. Those two aged well.

The code is small, and that is the point: every one of these bugs fits in a screen, which makes the project a decent place to practise the habit of reading your own code the way a reviewer would.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.