Certainly! Below is the refactored version of your Elixir/Phoenix LiveView application, adhering to the SOLID principles, DRY (Don't Repeat Yourself), and functional programming paradigms. The refactoring focuses on enhancing performance, concurrency, resiliency, and efficiency by eliminating redundancies and optimizing the code structure.
Overview of Changes
- Alignment of Event Names: Ensured consistency between the event names in the template and the LiveView handlers.
- Optimized Search Module: Consolidated search functions, added type information to search results, and improved the
find_selected_option/1 function for efficiency.
- Enhanced LiveView Module: Streamlined event handling, reduced redundancy, and improved clarity.
- Template Adjustments: Corrected event bindings and utilized form helpers for better clarity and functionality.
1. Refactored Search Module
The Moldb.Search module is optimized to provide unified search capabilities across Compound and Substance entities. It now includes type information in the search results, which can be beneficial for the UI to distinguish between different types of search results.
defmodule Moldb.Search do
@moduledoc """
The Search context, providing functionalities to search compounds and substances.
"""
import Ecto.Query, only: [from: 2, union_all: 2]
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
@doc """
Searches compounds and substances by their respective names based on the query.
## Parameters
- query: The search string.
## Returns
- A sorted list of maps containing `:name`, `:id`, and `:type`.
"""
def search_options(query) do
search_query(query)
|> Repo.all()
|> Enum.sort_by(& &1.name)
end
@doc """
Finds a selected option by its ID.
## Parameters
- id: The ID of the selected option.
## Returns
- A map containing `:name`, `:id`, and `:type` if found, else `nil`.
"""
def find_selected_option(id) do
id = parse_id(id)
cond do
compound = Repo.get(Compound, id) ->
%{name: compound.iupac_name, id: compound.id, type: "compound"}
substance = Repo.get(Substance, id) ->
%{name: substance.substance_name, id: substance.id, type: "substance"}
true ->
nil
end
end
# Private helper to parse ID
defp parse_id(id) when is_integer(id), do: id
defp parse_id(id) when is_binary(id), do:
case Integer.parse(id) do
{int, ""} -> int
_ -> nil
end
# Constructs the search query combining compounds and substances
defp search_query(query) do
union_all(compound_query(query), substance_query(query))
end
# Query for searching compounds
defp compound_query(query) do
from(c in Compound,
where: ilike(c.iupac_name, ^"%#{query}%"),
select: %{name: c.iupac_name, id: c.id, type: "compound"}
)
end
# Query for searching substances
defp substance_query(query) do
from(s in Substance,
where: ilike(s.substance_name, ^"%#{query}%"),
select: %{name: s.substance_name, id: s.id, type: "substance"}
)
end
end
Key Improvements:
- Unified Search Results: Both
Compound and Substance search results include a :type field, allowing the UI to differentiate between them.
- Efficient
find_selected_option/1: Instead of querying all items and filtering by ID, it directly checks each table, reducing database load.
- Elimination of Redundancies: Removed unused functions like
search_compounds/1 and search_items/1 to streamline the module.
2. Refactored HomeLive LiveView Module
The MoldbWeb.HomeLive module has been refactored to handle events more efficiently, reduce redundancy, and improve clarity. It now aligns event names with the template and optimizes state management.
defmodule MoldbWeb.HomeLive do
use MoldbWeb, :live_view
alias Moldb.Search
alias LiveSelect.Component, as: LiveSelectComponent
@impl true
def mount(_params, _session, socket) do
options = Search.search_options("")
{:ok, assign(socket, form: to_form(%{}), options: options, selected_text: nil)}
end
@impl true
def handle_event("live_select_change", %{"id" => id, "text" => text}, socket) do
options = Search.search_options(text)
send_update(LiveSelectComponent, id: id, options: options)
{:noreply, assign(socket, options: options, selected_text: text)}
end
def handle_event("clear", %{"id" => id}, socket) do
options = Search.search_options("")
send_update(LiveSelectComponent, id: id, options: options)
{:noreply, assign(socket, options: options, selected_text: nil)}
end
end
Key Improvements:
- Event Alignment: Ensured that the event names (
"live_select_change" and "clear") match those emitted by the template.
- Reduced Redundancy: Streamlined the
handle_event/3 functions to eliminate repetitive code.
- State Management: Managed the
selected_text state more effectively, setting it to nil when cleared.
- Clarity and Readability: Improved function naming and structure for better maintainability.
3. Refactored home_live.html.heex Template
The template has been updated to align event names with the LiveView handlers and utilize form helpers for better structure.
<.form for={@form} phx-change="live_select_change">
<.live_select
field={@form[:compound]}
update_min_len={1}
phx-focus="clear"
allow_clear
options={@options}
label="Compound"
placeholder="Search for compounds"
/>
</.form>
Key Improvements:
- Event Alignment: Changed
phx-change="change" to phx-change="live_select_change" to match the LiveView event handler.
- Simplified Form Usage: Utilized the
for attribute with @form for better form handling.
- Consistent Naming: Ensured that the
live_select component uses consistent and descriptive attributes.
4. Additional Recommendations
To further enhance the performance, concurrency, resiliency, and efficiency of your application, consider the following:
-
Database Optimization:
- Indexes: Ensure that there are indexes on the
iupac_name and substance_name fields to speed up ILIKE searches.
- Full-Text Search: Implement PostgreSQL's full-text search capabilities for more efficient and flexible search queries.
-
Caching:
- In-Memory Caching: Utilize caching mechanisms like ETS or Cachex to store frequently accessed search results, reducing database load.
- Fragment Caching: Cache components or parts of the LiveView that do not change frequently to improve rendering performance.
-
Concurrency:
- Asynchronous Operations: If search operations are intensive, consider handling them asynchronously to prevent blocking the LiveView process.
-
Error Handling:
- Graceful Failures: Implement comprehensive error handling to manage scenarios where database queries fail or return unexpected results.
-
Testing:
- Comprehensive Tests: Write unit and integration tests for both the
Search module and the LiveView to ensure reliability and catch potential issues early.
-
Documentation:
- Code Documentation: Maintain thorough documentation for modules and functions to aid future maintenance and onboarding of new developers.
By implementing these refactorings and recommendations, your application will be more maintainable, efficient, and scalable, adhering to best practices in software engineering.