21 lines
1.6 KiB
Markdown
21 lines
1.6 KiB
Markdown
---
|
|
title: >
|
|
The single responsibility principle
|
|
pubDate: 2023-05-09
|
|
permalink: >-
|
|
daily/2023/05/09/the-single-responsibility-principle
|
|
tags: []
|
|
---
|
|
|
|
Today, I added a new feature to a project that allows a member to search for a node based on either its title or a specified field on that node, select a result from an autocomplete list and then be redirected to their selected node.
|
|
|
|
I've already implemented this for other node types but needed to do the same for this node type.
|
|
|
|
There are some differences, such as the node type to query for; the additional field depends on which node type as does the text shown in the autocomplete list.
|
|
|
|
To do this, I needed to add a custom block and form, update the `AutocompleteController`, create a new instance of a `NodeQuery` class (a custom class within the custom module), register it as a service and update the `SearchQueryFactory` class.
|
|
|
|
A principle that I follow as much as possible is the single responsibility principle, or SRP (the 'S' in SOLID), where each function or class only has one responsibility - such as returning a response for the autocomplete list, determining the correct node query to use based on the search being run or building the query itself - these are separated and split into their own files.
|
|
|
|
Although more files and functions are created when coding in this way, though they are smaller and more straightforward to work with - which makes them easier to read, debug and maintain. It also makes code like the node query classes reusable as they aren't embedded within a larger class and are easier to test.
|