<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Coders Lexicon</title>
	<atom:link href="https://www.coderslexicon.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.coderslexicon.com</link>
	<description>Find Solutions in Java, .NET, C#, PHP, C++ and More</description>
	<lastBuildDate>Tue, 03 Jun 2025 19:30:16 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Building Your Own Model Context Protocol (MCP) Server With Node and Python</title>
		<link>https://www.coderslexicon.com/building-your-own-model-context-protocol-mcp-server-with-node-and-python/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Tue, 03 Jun 2025 19:30:16 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11625</guid>

					<description><![CDATA[I recently had the opportunity to build out an Agentic AI system for my employer that would allow tools like a local MySQL database to be accessed by a command line tool like Claude Code. While I was working on this I thought I would make something super easy, a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2025/06/mcp-server-sm.jpg" alt="" width="220" height="155" class="alignleft size-full wp-image-11631" />I recently had the opportunity to build out an Agentic AI system for my employer that would allow tools like a local MySQL database to be accessed by a command line tool like Claude Code. While I was working on this I thought I would make something super easy, a template if you will, that I could share with all my readers. Something that you could follow to create your own Model Context Protocol server for your own local projects. So the quest began! In this post I will show you all you need to set it up using either Node.js (using the @modelcontextprotocol/sdk) or Python (through the use of <a href="https://github.com/jlowin/fastmcp">FastMCP</a>). </p>
<h3>What is Model Context Protocol Anyways?</h3>
<p>Many of you developers out there are familiar with the concept of an API or Application Programming Interface. You might have integrated with one or even built out your own using the REST pattern. Even though you followed REST, you more than likely created your own nuanced changes and implementations that made your API slightly different than someone else&#8217;s. Then how did you communicate what was in your API? You probably cobbled together some documentation and put it on a website or through a README file. </p>
<p>MCP is a protocol that standardizes the way LLMs or AI agents access these services. Think of it as a way to wrap around functionality you want to offer and creates an interface that everyone has agreed to. No longer is your interface going to be different than another company. Instead you can set this intermediary up and let AI tools use it the same way it uses tools (or resources) from other companies. Very plug and play! Let&#8217;s see how this works.</p>
<h3>Getting Started</h3>
<p>To get started you need a project that is set up in such a way that it adheres to the standard. Rather than implement all that logic yourself, you can easily incorporate packages to help with that. Then you can simply focus on the tools and resources you are going to offer. For our first example I am going to present a simple Node.js project that is meant to be a simple template with a single tool. The goal here is for you to take the template, fire it up, connect it to something like Claude Code and see how it works. Once you see it in action, you are going to want to implement a ton of functionality. You can even spin up multiple tools in minutes!</p>
<p>To start we want to make sure you have all the packages you are going to need. Below is the contents of our package.json file. We are assuming you are familiar with getting Node.js installed and know that you can simply install all the packages by typing &#8220;<em>npm install</em>&#8220;.</p>
<p><strong>package.json</strong></p>
<pre class="brush: jscript; title: ; notranslate">
{
  &quot;type&quot;: &quot;module&quot;,
  &quot;dependencies&quot;: {
    &quot;@modelcontextprotocol/sdk&quot;: &quot;^1.12.0&quot;,
    &quot;cors&quot;: &quot;^2.8.5&quot;,
    &quot;dotenv&quot;: &quot;^16.5.0&quot;,
    &quot;zod&quot;: &quot;^3.25.36&quot;
  }
}
</pre>
<p>We have only a few packages specified. First we have the SDK needed to implement the MCP, then we have cors (which is optional and not actually used in our project, but left in the case you need to make some cross domain requests later), dotenv to handle environment variables (again not used until you need to work with sensitive variables which is most likely the case later) and zod which is to simplify parameter typing/formats.</p>
<p><strong>server.js</strong></p>
<pre class="brush: jscript; title: ; notranslate">
import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;;
import { StdioServerTransport } from &quot;@modelcontextprotocol/sdk/server/stdio.js&quot;;
import { z } from &quot;zod&quot;;

// Initialize our server
const server = new McpServer({
  name: &quot;mcp-echo&quot;,
  version: &quot;1.0.0&quot;,
  capabilities: {
    tools: {}
  }
});


// Tool definition for echoing text.
server.tool(
  &quot;echo&quot;,
  &quot;Echoes any message passed to it.&quot;,
  {
    message: z.string().describe(&quot;The message to echo&quot;)
  },
  async ({ message }) =&gt; ({
    content: &#x5B;{ type: &quot;text&quot;, text: `Tool echo: ${message}` }]
  })
);

// Start our server in Stdio transport mode.
const transport = new StdioServerTransport();
await server.connect(transport);
</pre>
<p>This is meant to be bare bones. We are setting up our MCP to offer one simple tool called &#8220;echo&#8221; which will echo back a message we give it. Take these two files, toss them in a directory, run npm install to install the dependencies. Then you are set to go. You can run this in numerous ways including:</p>
<ol>
<li>Type &#8220;<em>node server.js</em>&#8221; which will simply run the server</li>
<li>Type: &#8220;<em>npx @modelcontextprotocol/inspector node server.js</em>&#8221; to run the MCP inspector that will allow you to interact with the server through a browser GUI. Great for testing and I recommend this as your first item to try.</li>
<li>Fire up Claude Code (<a href="https://docs.anthropic.com/en/docs/claude-code/getting-started">Learn to install it here</a>) and add it to Claude&#8217;s MCP list by typing &#8220;<em>claude mcp add mcp-echo &#8212; node /path/to/the/server.js</em>&#8220;. Once added, fire up Claude Code by typing &#8220;<em>claude</em>&#8221; and if you see no errors, you are good to go to use it.</li>
</ol>
<p>Once you have Claude fired up, type &#8220;<em>/mcp</em>&#8221; to see if it is connected. If it is, you can type a prompt into Claude Code like &#8220;<em>Echo the message &#8216;Hello world!&#8217;</em>&#8221; and Claude Code should ask you to use your new tool. Say &#8220;Yes&#8221; and you will see Claude use the tool.</p>
<p>All done! Use the structure of this project to build out your own tooling. Bring in your own packages, define the tool, pick a name and description, define your parameters, define your function body and you are good to go. </p>
<h3>Stdio VS Stream HTTP / SSE</h3>
<p>In the world of MCP there are two modes (known as transport modes). Standard IO (meant for local work) and Streaming HTTP / Server Side Events (SSE) which is meant for setting up on remote servers and having others connect to it. These project templates were created for the former and there is plenty of docs out there to help you with the latter with minor changes. Develop your project with the intended goal in mind and I suggest starting with standard IO first to get a feel for things. I might do a blog post for a remote streaming transport setup later. I thought I would mention this so you are not confused between the two.</p>
<h3>Implementing MCP using Python&#8217;s FastMCP</h3>
<p>Similar steps as implementing the Node.js project works for FastMCP. Given that Python is a little cleaner and readable in its syntax, it can be done fairly simply. First start by creating a virtual environment (or fire up a new project in an IDE like Pycharm which creates the venv automatically) and install the packages &#8220;mcp[cli]&#8221;, uv, dotenv and for our example we will also use mysql-connector-python package to connect to a local MySQL server.</p>
<p>You can install all this using: <em>pip install &#8220;mcp[cli]&#8221;, uv, dotenv, mysql-connector-python</em></p>
<p>Once all that is installed, all that is left is to create our server.py template.</p>
<p><strong>server.py</strong></p>
<pre class="brush: python; title: ; notranslate">
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv
import os
import mysql.connector

load_dotenv(&#039;.env&#039;)

# Connect to our MySQL server using environment variables
mysql = mysql.connector.connect(
    host=os.getenv(&quot;DB_HOST&quot;),
    user=os.getenv(&quot;DB_USER&quot;),
    password=os.getenv(&quot;DB_PASS&quot;),
    database=os.getenv(&quot;DB_DATABASE&quot;)
)

# Create our FastMCP server
mcp = FastMCP(name=&quot;Demo MySQL Server&quot;, host=&quot;0.0.0.0&quot;, port=8050)

# Simple example of showing all MySQL tables
@mcp.tool()
def show_tables() -&gt; list:
    cursor = mysql.cursor()
    cursor.execute(&quot;SHOW TABLES&quot;)
    return cursor.fetchall()

# Start our server in standard IO mode.
if __name__ == &quot;__main__&quot;:
    mcp.run(transport=&quot;stdio&quot;)
</pre>
<p>This project assumes you have a .env file set up with the appropriate environment variables. <strong>Note:</strong> Make sure your local MySQL server is going to hear you and you are using the correct user credentials to login. </p>
<p>As you can see, we import the required packages, connect to our MySQL database, set up our FactMCP server with a name, host and port (which are all optional if you are just doing local) and you define tools by wrapping functions in a @mcp.tool() decorator. Type hint your parameters and return types and lastly start your server.</p>
<p>Connecting this server to Claude Code is pretty similar as the Node.js service. Type: &#8220;<em>claude mcp add mcp-mysql-py &#8212; python /path/to/your/server.py</em>&#8220;. Of course use &#8220;python&#8221; or &#8220;python3&#8221; according to your environment and how you typically run your python code. </p>
<p>You can use the same MCP inspector tool to also inspect your Python MCP server if you like. With this project we offered one tool for showing the database tables in the MySQL server.</p>
<h3>Conclusion</h3>
<p>In this article we explored two very simple layouts for local MCP server implementations. These can be a great starting point for you to build out your own services for AI agentic systems to use various tools and resources. Whether it be to access systems like databases, send requests to APIs for email or even process vast amounts of remote server data, the sky is the limit. I hope you found this quick spin through the projects an easy way for you to get started using MCP and finding out more about other servers out there that you can bring into your projects.</p>
<p>Thank you for reading! 🙂</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating Self-Signed OpenSSL Certs in Python For Development</title>
		<link>https://www.coderslexicon.com/creating-self-signed-openssl-certs-in-python-for-development/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Tue, 03 Sep 2024 16:05:11 +0000</pubDate>
				<category><![CDATA[Desktop Programming]]></category>
		<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11589</guid>

					<description><![CDATA[Do you need a quick way to generate OpenSSL self-signed certificates for your local projects? In this article, we&#8217;ll show you how to create a utility that automates the process. You&#8217;ll find the code you need to get started quickly and easily. This solution was developed as part of a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2024/09/openssl-cert-sm.png" alt="" width="220" height="155" class="alignleft size-full wp-image-11593" />Do you need a quick way to generate OpenSSL self-signed certificates for your local projects? In this article, we&#8217;ll show you how to create a utility that automates the process. You&#8217;ll find the code you need to get started quickly and easily. This solution was developed as part of a script to set up self-signed certificates and virtual hosts on an Apache 2.4 installation on Windows.</p>
<h3>First Step, Installing OpenSSL</h3>
<p>Before we can have Python generate some certs for us, we have to install OpenSSL. One of the easiest ways to get this installed, along with other useful tools, is to use <a href="https://git-scm.com/downloads">Git Bash</a>. When you install this tool, you will get a lot of functionality for handling Git and it comes with OpenSSL out of the box. Start the process of installing that and once completed, we can use Python to run openssl commands. </p>
<h3>Second Step, Wrap the Command In a Function</h3>
<p>To make things a bit easier, we are going to wrap our OpenSSL command code in a function which we can call on to build keys for each site we create dynamically. We will make this function include two pieces of information. The first is a site slug we can use to identify the site (this might be a site slug used to setup folders and write to the hosts file and vhosts entries) and the path to where we would like to save the key/crt files. This is how the function may look&#8230;</p>
<pre class="brush: python; title: ; notranslate">
import os
import subprocess

def generate_ssl_key(site_slug: str, destination_path: str,) -&gt; None:
    command = &#x5B;
        &#039;openssl&#039;, &#039;req&#039;, &#039;-new&#039;, &#039;-x509&#039;, &#039;-days&#039;, &#039;3652&#039;,
        &#039;-nodes&#039;,
        &#039;-keyout&#039;, fr&quot;{destination_path}\{site_slug}.key&quot;, &#039;-out&#039;, fr&quot;{destination_path}\{site_slug}.crt&quot;,
        &#039;-subj&#039;, f&quot;/C=US/ST=Oregon/L=Portland/O=Company Name/OU=Org/CN={site_slug}.local&quot;
    ]

    # Silence the output of openssl by sending it to devnull
    with open(os.devnull, &#039;wb&#039;) as null_file:
        subprocess.run(command, stdout=null_file, stderr=subprocess.STDOUT, check=True)
</pre>
<p><strong>Explanation:</strong> This function will take a site slug that we will use to associate the files with a given site. We will also provide a destination path to tell openssl where we would like to put these keys once it generates them. To use this function, we will need to include both the &#8220;os&#8221; and &#8220;subprocess&#8221; modules. The command is setup to create a .key file and a .crt file. We are telling openssl to create the key that is a X.509 certificate instead of a .csr. We are currently issuing the license for about 10 years (adjust the -days parameter as you see fit). We are then using the destination path and the site slug to determine where we would like to save the certificate files.</p>
<p>As part of the process we are setting some details of the key issuer including the country code, state, city, company name etc. You can set these how you like. I have set this to be from Portland Oregon in the USA for the company &#8220;Company Name&#8221; and the certificate will be for the domain &#8220;sitename.local&#8221;. If your development environment is going to be configured differently, make sure the CN is setup to match the environment. For me a site would be something like &#8220;example.local&#8221;. </p>
<p>Lastly, OpenSSL is going to output a bunch of information as it creates the certificate and we want to silence that. What we did here is open up a stream to a special location that will essentially throw away whatever data we stream to it. In the *nix world this would be devnull but for our purpose we are calling it simply null_file. </p>
<p>The idea here is that we will direct the standard out stream to this null file and whatever openssl outputs will simply be thrown away and never displayed. In the case of error, we redirect the standard error stream to standard out which again is thrown away at the end. We use the subprocess.run() command to run our openssl command. This module is very useful for running processes, so take some time to look it up. The information there is priceless.</p>
<h3>The Result</h3>
<p>Once we have this all setup, calling this function is going to run the openssl command which will generate the certificate files in our destination path with the site_slug name and registered for our site_slug.local domain. The output openssl outputs will be silenced and will end. Because of the silencing, be sure to put in a quick print statement to let you know when it has ended.</p>
<h3>Conclusion</h3>
<p>In this article we talked about a quick way to generate local self-signed certs for our local web development projects using OpenSSL and Python. We provided some example code and ran through it to see how it works. Mixing this code along with code that then writes a vhosts entry to your Apache vhosts SSL conf file and writes to your hosts file to set site_slug.local to point to your local IP, you can quickly configure and launch your own development environments with a few keystrokes. I hope you found this little trick useful and something you can use in a bigger project to create your own web development environments using the power of Python!</p>
<p>If you&#8217;d like to support future articles, please check out our <a href="https://www.coderslexicon.com/product/the-programmers-idea-book-200-software-project-ideas-and-tips-to-developing-them-ebook/">Programmers Idea Book</a> and make a purchase. It&#8217;s full of project ideas that can help take your skills to the next level and well worth the investment. Thank you! 🙂</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Handling Time Zone Calculations in Your Web Applications with UTC and MySQL</title>
		<link>https://www.coderslexicon.com/handling-time-zone-calculations-in-your-web-applications-with-utc-mysql/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Fri, 09 Aug 2024 18:37:56 +0000</pubDate>
				<category><![CDATA[.NET Programming]]></category>
		<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11572</guid>

					<description><![CDATA[Whether you&#8217;re a seasoned web developer or just starting out, handling time zones can be a tricky task. Time zone calculations are often done incorrectly, and even experienced developers can find them challenging. In this article, we won’t dive deep into the complexities of dates and time zone mathematics. Instead, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2024/08/utc-clock.png" alt="" width="220" height="155" class="alignleft size-full wp-image-11577" />Whether you&#8217;re a seasoned web developer or just starting out, handling time zones can be a tricky task. Time zone calculations are often done incorrectly, and even experienced developers can find them challenging. In this article, we won’t dive deep into the complexities of dates and time zone mathematics. Instead, we&#8217;ll share a simple trick that uses UTC and MySQL timestamps to help you display time accurately for your users. We&#8217;ll briefly cover how to store, retrieve, and properly display time on your website or in your application.</p>
<h3>The Story of UTC</h3>
<p>If you&#8217;ve worked with time in software development, you&#8217;ve probably encountered UTC, or &#8220;Coordinated Universal Time.&#8221; UTC is equivalent to Greenwich Mean Time (GMT), the time zone that covers Greenwich, England. It serves as the standard from which all other time zones around the world are calculated, with an offset of +00:00. By knowing the time zone offset (whether it&#8217;s east or west of UTC), you can accurately determine the local time anywhere.</p>
<p>But why is this important, and how does it help us display time correctly? Since UTC is the baseline for calculating time zones, we can store all our times in this universal format in the database. For instance, if you&#8217;re in the Pacific Standard Time zone, you can convert the current local time to UTC before storing it in the database. When you need to display the time, you retrieve the UTC value, adjust it based on the user&#8217;s time zone (and account for daylight savings if necessary), and then display it correctly.</p>
<h3>MySQL Timestamps and DateTime</h3>
<p>In MySQL, there are two main types of fields for storing time: TIMESTAMP and DATETIME. When you insert a time into MySQL, the way it’s stored and later retrieved depends on the type of field you use.</p>
<p>When you store a TIMESTAMP, MySQL automatically converts the time to UTC. When you retrieve it, MySQL converts it back to the time zone of the server (for example, if you&#8217;re using a server-side language like PHP). On the other hand, with a DATETIME field, no conversion occurs—neither during storage nor retrieval. The date and time are stored exactly as you input them, similar to a plain text string.</p>
<p>To ensure consistent and accurate time display for users, it’s best to store dates and times in UTC format. This way, when you need to adjust the time for a user’s local time zone, it’s straightforward. If you store a raw DATETIME, you would need to know the time zone it was stored in and adjust it accordingly, or risk displaying an incorrect time to the user—something you want to avoid.</p>
<h3>Getting User Time Info and Display Our Time Correctly</h3>
<p>Now that we understand the importance of storing dates as UTC timestamps in the database, let&#8217;s focus on how to retrieve and display that time in a way that makes sense for the user. For example, if someone in Pacific Standard Time (PST) makes a comment at 1:00 PM, someone in Mountain Standard Time (MST) would see that same event as occurring at 2:00 PM. To display the correct time for users in different time zones, two key pieces of information are needed:</p>
<ol>
<li>The UTC time (which is easy to get since it&#8217;s stored in the database after being converted from PST).</li>
<li>The user&#8217;s time zone (in this case, MST).</li>
</ol>
<p>With these two pieces of information, you can accurately convert and display the time for the user. Daylight Saving Time (DST) might also come into play, but most programming languages handle this conversion automatically based on the user’s locale. If your language doesn’t account for DST, you may need to manually add or subtract the appropriate amount of time depending on whether DST is in effect for the user’s region.</p>
<p>To illustrate how to display time correctly, we&#8217;ll use three different programming languages: JavaScript, Python, and C#.</p>
<p>Starting with PHP, since it&#8217;s a server-side language, the user needs to specify their time zone, often by filling in this information in their profile on the website. PHP, like the other languages we&#8217;ll explore, typically handles DST calculations based on the user&#8217;s time zone and locale. However, it&#8217;s crucial that the user provides this information for accurate time conversion.</p>
<pre class="brush: php; title: ; notranslate">
$query = &quot;SELECT timestamp_column FROM your_table&quot;;
$result = $mysqli-&gt;query($query);
$row = $result-&gt;fetch_assoc();
$utc_timestamp = $row&#x5B;&#039;timestamp_column&#039;];

// Assume user&#039;s time zone is stored in $user_timezone
$user_timezone = new DateTimeZone(&#039;America/New_York&#039;); // Example time zone
$utc_datetime = new DateTime($utc_timestamp, new DateTimeZone(&#039;UTC&#039;));
$utc_datetime-&gt;setTimezone($user_timezone);
$user_time = $utc_datetime-&gt;format(&#039;Y-m-d H:i:s&#039;);

echo $user_time; // This will print the timestamp in the user&#039;s time zone
</pre>
<p><strong>Explanation:</strong> The first part of this code simply fetches the time zone field from the database and sticks that into a variable called [il]$utc_timestamp[/il]. The second part assumes that the user is in the America/New York (Eastern Standard Time) time zone and uses the DateTimeZone class to set the time zone on the DateTime object we made with the  [il]$utc_timesamp[/il] variable. We then format it to be whatever format we want to display it as. If we hadn&#8217;t gotten the user&#8217;s time zone from them, we would have to adjust the time based on the server time. If our website was hosted in a different time zone (or the server was set to a specific time zone) it would have used that. </p>
<p><strong>Note:</strong> It might be smart to always set your server to be UTC no matter where it is hosted. This would make it easy, in the age of cloud computing, to deploy the code anywhere in the world.</p>
<p>Ok, let&#8217;s move on to JavaScript. Since JavaScript is typically rendered on the client side we can have JS detect some stuff automatically. The first part is to fetch our timestamp again from the database (using something like PHP) and display it as JavaScript&#8230;</p>
<pre class="brush: php; title: ; notranslate">
$query = &quot;SELECT timestamp_column FROM your_table&quot;;
$result = $mysqli-&gt;query($query);
$row = $result-&gt;fetch_assoc();
$utc_timestamp = $row&#x5B;&#039;timestamp_column&#039;];

echo &quot;&lt;script&gt;const utcTimestamp = &#039;$utc_timestamp&#039;;&lt;/script&gt;&quot;;
</pre>
<p>Then we run some JavaScript to use this variable and make a conversion&#8230;</p>
<pre class="brush: jscript; title: ; notranslate">
// Convert the UTC timestamp to a JavaScript Date object
const utcDate = new Date(utcTimestamp + &#039;Z&#039;); // Tell JS that this is UTC with the &#039;Z&#039; flag.

// Format the local date as needed
const options = { 
   year: &#039;numeric&#039;, month: &#039;numeric&#039;, day: &#039;numeric&#039;, 
   hour: &#039;numeric&#039;, minute: &#039;numeric&#039;, second: &#039;numeric&#039; 
};
    
const localTimeString = utcDate.toLocaleString(undefined, options); // Takes into account locale and DST

console.log(localTimeString); // This will print the timestamp in the user&#039;s local time zone
</pre>
<p><strong>Explanation:</strong> As you can see from the JS, it is pretty clear what this is doing. We take in the timestamp and specify UTC by appending a &#8216;Z&#8217; suffix. This will make [il]utcDate[/il] recognizable as a UTC date. </p>
<p><strong>Note:</strong> If you print or use any of the string functions on this date, it will convert it to a local time. So do this only when you ready to display at the end. For fun we also specify some formatting options and convert the UTC Date over to a local time string for display.</p>
<p>Finally we will show a simple example of how this can be done using something like a C# console app. We won&#8217;t show anything related to fetching from the database for brevity, but assume that [il]utcTimestamp[/il] was the timestamp fetched from the database. Again it would be coming in as a UTC based timestamp.</p>
<pre class="brush: csharp; title: ; notranslate">
// Example UTC timestamp as a string
string utcTimestamp = &quot;2024-08-08 19:12:45&quot;;
        
// Parse the UTC timestamp into a DateTime object (make sure the format matches!)
DateTime utcDateTime = DateTime.ParseExact(utcTimestamp, &quot;yyyy-MM-dd HH:mm:ss&quot;, null, System.Globalization.DateTimeStyles.AssumeUniversal);
        
// Convert UTC DateTime to local time
DateTime localDateTime = utcDateTime.ToLocalTime();
        
// Format the local time as needed
string localTimeString = localDateTime.ToString(&quot;yyyy-MM-dd HH:mm:ss&quot;);
        
// Display the local time
Console.WriteLine(&quot;Local Time: &quot; + localTimeString);
</pre>
<p><strong>Explanation:</strong> We start with the incoming UTC timestamp and use [il]DateTime.ParseExact[/il] to parse that into a DateTime object. From there we can convert the time to local time and format it as we like before displaying.</p>
<h3>Another Reason for UTC</h3>
<p>A great advantage of storing times in UTC across your database and servers is the consistency it brings, especially when it comes to logging. Have you ever looked through a set of logs, noticed a timestamp without a time zone, and wondered, &#8220;Is this time in my local time, the server&#8217;s time, the user&#8217;s time, or UTC?&#8221; Wouldn&#8217;t it be simpler if you could always assume it&#8217;s UTC? Once you get used to it, converting UTC to your local time in your head becomes second nature. Regardless of the time format you choose, it&#8217;s crucial to maintain consistency across your systems. This ensures that when different systems communicate, everyone is on the same page—which is exactly why UTC was established.</p>
<h3>Conclusion</h3>
<p>In this article, we explored the concept of storing time as a UTC timestamp and then converting it for display using JavaScript, PHP, and C#. We discussed the importance of storing date and time in UTC format and only converting it when displaying it to the user based on their time zone and locale. This approach allows you to store time in a universal format and then tailor it to each user, ensuring consistency and smooth communication between systems.</p>
<p>I hope you found this article helpful. If you&#8217;d like to support future articles, please check out our <a href="https://www.coderslexicon.com/product/the-programmers-idea-book-200-software-project-ideas-and-tips-to-developing-them-ebook/">Programmers Idea Book</a> and make a purchase. It&#8217;s full of project ideas that can help take your skills to the next level and well worth the investment. Thank you! 🙂</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Random Quote Generator Using Try-With-Resources in Java</title>
		<link>https://www.coderslexicon.com/random-quote-generator-using-try-with-resources-in-java/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Fri, 14 Apr 2023 00:42:54 +0000</pubDate>
				<category><![CDATA[Desktop Programming]]></category>
		<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11427</guid>

					<description><![CDATA[We at The Coders Lexicon thought it might be advantageous for some of you learning Java to learn how you might structure something like a basic random quote generator. To make things a little more interesting, what if we read the quotes from a file and used a &#8220;try-with-resources&#8221; statement? [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2023/04/java-try-with-resources-thumb.png" alt="Java and try-with-resources" width="220" height="155" class="alignleft size-full wp-image-11434" />We at The Coders Lexicon thought it might be advantageous for some of you learning Java to learn how you might structure something like a basic random quote generator. To make things a little more interesting, what if we read the quotes from a file and used a &#8220;try-with-resources&#8221; statement? That way we could add additional quotes to it over time and have the program generate random quotes on demand. In this post we will show you one way to do this and explain all the steps. We will use an ArrayList to hold our quotes, java.util.Random to select a quote at random and a BufferedReader object to read from a file. Let&#8217;s jump in!</p>
<h3>Setting up our quotes file</h3>
<p>To start off, we are going to need some quotes file. Create a simple text file in your project and on each line setup a single quote. Remember where you put this file because you are going to need to know the path to that file to read it during program execution. In the code below, make sure to put that file path in the [il]loadQuotes()[/il] function. </p>
<h3>Open the file with a try-with-resources setup</h3>
<p>In Java SE 7+ a new statement was introduced called &#8220;try-with-resources&#8221;. This statement allows you to work with classes that implement the &#8220;<a href="https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/AutoCloseable.html">java.lang.AutoCloseable</a>&#8221; interface. The interface is used to make sure that any resources you use are automatically closed and cleaned up prior to the exit of the try-with-resources statement. It works very much like a traditional try-catch statement, however you will see that there is an expression in the &#8220;try&#8221; part. Since BufferedReader implements the AutoClosable interface, we can use it in a try-with-resources statement to make sure that the file is closed when the try-catch exits&#8230; even if there is an error!</p>
<p>Prior to Java SE 7, you could use a finally clause on your try-catch to do something similar. This is because the finally clause would execute no matter what happened in the try catch. However, a try-with-resources is a little bit cleaner and you should use it whenever you work with resources that implement the AutoClosable inteface to make sure you are always closing the resource when it is done.</p>
<h3>The Code</h3>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;

public class Main {
    // List to hold our quotes we will load in
    static private ArrayList&lt;String&gt; listQuotes = new ArrayList&lt;String&gt;(0);

    public static void main(String&#x5B;] args) {
        // First load the quotes into our list.
        loadQuotes();

        // Next, generate a random integer based on the size of the quote list. Use the integer to then access a quote from the list.
        if (listQuotes.size() &gt; 0) {
            Random r = new Random();
            System.out.println(listQuotes.get(r.nextInt(listQuotes.size())));
        } else {
            System.out.println(&quot;There are currently no quotes to read.&quot;);
        }
    }

    // This function simply loads quotes from our file.
    public static void loadQuotes() {
        // Here we have a try-with-resources setup that will automatically close BufferedReader
        try (BufferedReader bufReader = new BufferedReader(new FileReader(&quot;path_to_quotes.txt&quot;))) {
            String line;

            // Read each line until we hit the end. Add each line to the list.
            while ((line = bufReader.readLine()) != null) {
                listQuotes.add(line);
            }
        } catch (IOException e) {
            System.out.println(&quot;Error loading quotes. Make sure the file is readable and exists.&quot;);
        }
    }
}
</pre>
<p>As you can see from the code above, we start by setting up an ArrayList of strings to hold all of our quotes. You could use another listing data structure like a LinkedList or another form of list (I wouldn&#8217;t recommend an simple array however) but that is an implementation detail I will leave up to you. </p>
<p>After that, we start in [il]main()[/il] where we call a function called [il]loadQuotes()[/il]. In that function we use our try-with-resources statement to setup a <a href="https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/io/BufferedReader.html">BufferedReader</a> to read a file. Remember that file we set up earlier? Here is where you are going to put in the path to that file. Notice how the BufferedReader (which we call bufReader here) is assigned right after the try keyword in parenthesis. After this line, we can work with the reader and when we exit the try-catch, the try-with-resources statement will make sure our BufferedReader is closed automatically! Notice I have no [il]close()[/il] function call here. If an exception is thrown, we will print a simple error message. Again, even if there was an error, the BufferedReader is always closed.</p>
<p>Returning back to our [il]main()[/il] function, we check if there are any quotes in our list. We do this by simply checking the length of the list. If there are some, we setup our random number generator to get a random number between 0 and the size of the list. Remember that [il]nextInt()[/il] is going to exclude the number passed in. The fact that lists start at a zero index makes it so that if we pass in the total size of the list, it will pick numbers between 0 and the the size of the list &#8211; 1 (the last index of our list). Then we use the random index number to fetch the quote from the list using the &#8220;get&#8221; method of the ArrayList.</p>
<p>Once we have the selected random quote, all we have left is to print it and we are done. </p>
<h3>Conclusion</h3>
<p>In this short article we run through an example of using the try-with-resources statement, and a random number generator, to select a random quote from an ArrayList and display it. We showed how the code might work and quickly ran through an explanation. One of the reasons a program like this is good for learning is that the pattern of building up a list, randomly selecting one and managing our resources while doing it is a common pattern you will see in programming. Here we are working with strings, but we could have had a list of objects or varying lists of different sizes that a pattern like this would work well with.</p>
<p>We hope you enjoyed the code and learned something new about the try-with-resources statement. Thanks again for reading! 🙂</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functions Are Half the Battle</title>
		<link>https://www.coderslexicon.com/functions-are-half-the-battle/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Tue, 20 Sep 2022 22:48:42 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<category><![CDATA[General Programming]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11112</guid>

					<description><![CDATA[At this point I have been programming for nearly a quarter century. I have done multiple languages and worked with multiple platforms and technologies. Some of it can become quite complex and with that complexity comes extensive testing and solutions that just don&#8217;t feel elegant at times. I often find [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="https://www.coderslexicon.com/wp-content/uploads/2022/09/distilled-functions-thumb.png"><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2022/09/distilled-functions-thumb.png" alt="Distilled Functions" width="220" height="155" class="alignleft size-full wp-image-11117" /></a>At this point I have been programming for nearly a quarter century. I have done multiple languages and worked with multiple platforms and technologies. Some of it can become quite complex and with that complexity comes extensive testing and solutions that just don&#8217;t feel elegant at times. I often find myself asking the questions &#8220;How do I simplify this?&#8221; or &#8220;There has to be a simpler way, what is it?&#8221; With these questions I often lean on refreshing the basic principles of programming like classes, variables and most importantly functions. In this post I will cover some of my thoughts on functions and that if we can really isolate the idea of a function, and its parts, as this will give us half the solution to any problem thrown at us.</p>
<h3>Distilling Down the Idea of a Function</h3>
<p>If you are a programmer that has been doing it for any length of time, you may be thinking about a whole slew of things when the topic of functions come up. Ideas like parameter types, in/out parameters, variable number of parameters, function naming, return types, function length etc. For the time being lets just distill a function down to its essence without all the &#8220;flowery&#8221; terms. A function takes zero or more values, does something with them and possibly returns a value. For example, an &#8220;add&#8221; function may take two values and return a sum value. If we are not considering optimization, memory management or the like wouldn&#8217;t you say that a basic function can do some pretty incredible things? With this basic idea of a function, what do we need to do to make sure that it can do its thing? Well, we need to make sure that the info we give it is solid and correct. We then just need to make sure that its result is correct based on those inputs. Sure it might do some bad things in the middle but if the inputs and outputs are good, we have a large part of the work done.</p>
<p>If you have any experience with functional programming, you may be saying to yourself &#8220;purity&#8221;. In a way this is what I am saying, but again lets remove the notion of purity for a minute and just look at the idea of a function as a stand-alone idea void of any complex labeling. With a function that has correct and valid inputs and a solid output all that is left for us as programmers is to make sure that it stays that way. However, if you want to dive into some of these ideas of purity, check out my blog post on <a href="https://www.coderslexicon.com/applying-functional-programming-ideas-to-oop/">Applying Functional Programming to OOP</a>.</p>
<h3>Function Inputs</h3>
<p>Ok we have our distilled-down idea of a function. It is a piece of code that could take some inputs and may or may not return an output. If we can make sure that what comes into the function and what leaves the function are always right, the function itself is basically correct. Now it may not be the most efficient or it may do a bunch of basic &#8220;bad things&#8221; but from a holistic overall approach it works.</p>
<p>So let&#8217;s think about the function inputs. Can they be simple? Can they be typed? What can we do to make sure that the inputs we provide the function is as solid as they can be so the function can be confident that it is being told the truth. Should we validate them before calling the function or should the function itself make sure they are right? Well, that is up to you, but just make sure they are right in either case. If our &#8220;add&#8221; function expects two integers, isn&#8217;t that easier to think about than some complex wrapper class around an integer value? A class that may be null or may be dirty etc.?</p>
<p>I am not saying we can always create functions that work on strictly primitives, but the closer we can get to that simple value, the easier things could become. Often times when I am working on complex systems, I purposely step back and say &#8220;Hey, can this just be simpler? Can I reduce the number of inputs? Can I make this a simple number instead of this complex ugly class instance? Sure the instance might be more efficient, but what if efficiency wasn&#8217;t a concern? Would I still do this?&#8221;. </p>
<p>I find that if I take a function and think of it as a basic block in isolation and give it the simplest types of inputs, and reduce the number of inputs, that the function gets really solid and error proof. I mean, how hard is it to mess up an &#8220;add&#8221; function that takes two integers and returns an integer sum? You could code that without even needing Google.</p>
<h3>Function Outputs</h3>
<p>Like the inputs, I then think about the outputs. Again, very high level and without all the jargon that flies around in the development community. What is this function really suppose to tell me at the end of the day based on the inputs? Is it simply a sum? Is it going to return anything at all? Does the result have to be an array or can it just be a single primitive? Can you CLEARLY see the path between the inputs and its output when looking at this function in isolation? If you can&#8217;t, maybe the function is still too convoluted and needs to be broken down into other functions.</p>
<p>I think this is a good time to also mention that one line functions are NOT BAD! As long as the function simplifies the concepts, it works no matter if it is one line or 20. Of course we want to keep functions as short as possible, but one line is not too short is all I am saying.</p>
<h3>Does One Thing and Does It Well</h3>
<p>You have probably heard of the age old adage of functions that they should do one thing and do it well. It is true and I think if you look at a function in a distilled-down form and think of its inputs and outputs only without the fancy terms. If you think like this, you will already be 90% of the way to having a function that does one thing and does it well. The other 10% is just to make sure that the function isn&#8217;t brining in other data (globals, databases, files etc.) and NOT counting those as inputs. Along with this idea we also need to make sure that the output is the same for the given inputs and we got it nailed down. Again, this is the idea of &#8220;purity&#8221; in functional programming but you don&#8217;t need to study up on functional programming to get this concept. In fact, I think functional programming takes this to extremes at times, but I digress.</p>
<h3>Putting It All Together</h3>
<p>Ok, so if you follow the idea of taking a function in isolation, simplify its inputs and outputs and making sure to avoid crazy global use or not accounting for info being brought into the function from other means, you should have solid functions. As this post is titled, that is only HALF the battle. What is the other half? Well, obviously if you are working in object oriented programming you have things like classes, structures, variables, enums and all the other stuff that goes along with programming. However, I think that if you can write programs that have well solidified functions you will get the most bang for your buck in any project you work on. At least half of it will be solved. </p>
<p>Until you have seen a several thousand line program get cut down to a couple hundred lines by a few solid basic functions, you may have never felt the joy that great functions bring. The elegance is mind boggling. If you want to master any single idea in programming, functions is where it is at. Master them and just watch how much value you get out of your work!</p>
<h3>Conclusion</h3>
<p>In this post I talked a bit about the ideas of functions, but more importantly, how you should think about functions from a very distilled idea of simplicity and elegance. By taking the idea of a function and making sure that what goes into a function and what comes out of it is pure and solid we can get some pretty amazing functions. Functions that can greatly simplify and drive even the largest projects. We all have written bad functions. We have written bad functions yesterday. Then today, taking a hard look at them, we can realize they are bad. But it is better to simplify the function down into its basic form, study that, determine what it depends on and what it provides can be invaluable. Once we see the function is solid, then we can go about adding additional syntax sugar or work on efficiency.</p>
<p>If you are ever having trouble reading your own code, distilled its functions down, refactor them, get at their most basic form and you will often find out what code is doing (right or wrong) and how to improve it. Thanks for reading! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Applying Functional Programming Ideas to OOP</title>
		<link>https://www.coderslexicon.com/applying-functional-programming-ideas-to-oop/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Mon, 30 Aug 2021 18:05:00 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=11026</guid>

					<description><![CDATA[The ideas of functional programming have been around for a long time. This paradigm has several key principles that, while not exactly compatible with the Object-Oriented Programming (OOP) paradigm, do have credibility and advantages in their own right. Is functional programming better than OOP? In some ways yes, but in [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2021/08/functional-programming.png" alt="Functional programming in OOP" width="220" height="154" class="alignleft size-full wp-image-11030" />The ideas of <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> have been around for a long time. This paradigm has several key principles that, while not exactly compatible with the Object-Oriented Programming (OOP) paradigm, do have credibility and advantages in their own right. Is functional programming better than OOP? In some ways yes, but in some ways no. It really depends on the problem you are trying to solve and the best way to think about the problem. In this article I will outline why I think applying some of the basic ideas of functional programming can only strengthen your OOP code if done correctly. These are just some general ideas and are open to your own design spin. I want to also say that OOP is not weaker than functional programming, it is just a different way to look at problems.</p>
<h3>What Are Some Core Tenants of Functional Programming?</h3>
<p>If you have been working with functional programming and OOP, you already know that the two paradigms don&#8217;t really jive together nicely. Mainly due to the fact that OOP deals with state and that state really causes problems with function purity and immutability. Before we talk about ways to get some ideas working together, let&#8217;s first talk about a few key functional programming concepts. We will then go into why these don&#8217;t exactly fit in OOP but how we might glean some ideas from them to make OOP work better.</p>
<ol>
<li>Pure Functions &#8211; This concept states that functions should receive some input, work on only that input and return output&#8230; the same output for the same given inputs. This harkens back to mathematics where a function. Let&#8217;s say we have the function [il]f(x) = y[/il]. This takes an input [il]x[/il] and returns [il]y[/il]. This is what makes it pure. In this sense a pure function is more of a transformative feature that transforms one value to the other and nothing more. It doesn&#8217;t write to a file or database, it doesn&#8217;t log anything, it doesn&#8217;t print to a console or modify variables outside the scope of the function. All of these extra tasks are often referred to as &#8220;side effects&#8221;. It also states that given the same value of [il]x[/il] you will ALWAYS get the same value for [il]y[/il]. Not sometimes [il]y[/il] and sometimes [il]z[/il] depending on some external factor.</li>
<li>First Class Functions &#8211; This simply states that functions should be able to be passed around and called on like any other variable. That functions can then be passed to other functions to form what is known as higher order functions. Think of things like callbacks or closures. Many languages support this and you have probably already seen it.</il>
<li>Variables Immutability &#8211; Once a variable has been declared and assigned a value, it is not to be changed. Think of things like constants. If I assigned the value 4 to the variable [il]wheels_on_car[/il] you should not be able to change it later to 5. You can copy the value to a new variable and operate on it, but not on the original input.</li>
<li>Referential Transparency &#8211; A fancy way to say that wherever you call a function, you should be able to replace that function call with the function&#8217;s result and the code won&#8217;t break. Given our example in the previous point, if we have a function [il]getNumberOfCarWheels()[/il] that returns 4, we should be able to replace all function calls to this function with the value 4 and it won&#8217;t break. I find that if you observe purity and avoid relying on any values outside of the function, you should be pretty close to having referential transparency.</il>
</ol>
<h3>What Ideas Can We Glean From Functional Programming to Use in OOP?</h3>
<p>Well, we know that we won&#8217;t necessarily have pure functions in an OOP class because that function will likely operate on class variables&#8230; aka class state. These values can be manipulated outside of the current method by other methods in the class (or in the case of public class variables, maybe even another part of the system). However, we can glean the idea that if we strictly control access to class variables, and possibly look to not even using them, then we can strive for purity. We can do this by first defining the function to work locally and only when other methods in the class ABSOLUTELY need to share a state, then promote the appropriate variables to the class as state. This is in contrast to putting in class variables from the start, even if only one method uses that state.</p>
<p>What about functions as first-class citizens and composing higher order functions? Well, I don&#8217;t see much of a problem here in OOP. In theory you could pass a reference to one method to another method and call that method as a callback or a standalone function. You could even define some other function outside of a class and pass it to a class method which takes a function as a parameter. Now would you do this with methods defined in the same class instead of calling them directly? Possibly. The idea is that if the method was generic enough, that method could take any function (defined in the class or not) and it should still work. If it is a private helper method, it might make more sense that it receives another private helper method and works with it than calling the other helper method directly. The goal here is reusability and building up these higher order functions where the low-level functions can be used in other projects.</p>
<p>As for variables being immutable, again state is often meant to be changed by more than one method. State is all about change. Again, if we reduce our reliance on state variables we have half the problem solved. The other thought is that if we can apply strict rules on when state can be changed and what values that state can have at any given time, we can almost treat state as immutable. For instance, if we say that cars can only have 4 wheels, anything that violates that rule should not be allowed. Then we treat that variable as if it was immutable. Or that it is mutable but only with a finite set of known states. This could be maintained by strict setter methods of a class that evaluates the state change and absolutely forbids any changes that violate the set of rules for a given variable. Setting wheel count to 5? Nope! Not going to do it.</p>
<p>Lastly, what about referential transparency? I think this is perfectly doable. However, if you are working with state in a method, and even if that state has a finite number of values due to strict control, referential transparency would still be violated as the same input may lead to different outputs and thus you can&#8217;t replace calls to a method with a known result in all situations. But you could still strive for this, especially for static methods. However, to truly do it you would need to keep state (and any side effects) out of the method&#8230; period.</p>
<h3>How Might We Use These Ideas Anyways</h3>
<p>I already mentioned above a few tactics and trains of thought we could use to help integrate some of the ideas of functional programming into our OOP world. Here I would like to help solidify some of the thoughts around some general themes. Even if we can&#8217;t implement these 100%, I believe that incorporating as much as possible of the idea into our OOP can only help strengthen our code.</p>
<ul>
<li>Strive for purity. Think about the values a method takes in and the values it returns. Keep them free of side effects as much as possible. We all know that side effects are inevitable, but maybe regulate side effect use to a few key methods only. If we think of the inputs to our methods as constant and that we limit our use of state, we can get pretty close to creating pure functions/methods. This also means that we don&#8217;t reuse our input variables (copy them if need be and assign to new variables). Look to avoid using state defined variables by first defining them locally and only promote them to class level if needed by multiple methods. You might be surprised how easy a method may become if you keep state out of it and you define the method&#8217;s goal well. Lots of code bloat comes from dealing with external entities just because of error checking alone.</li>
<li>Strive for first class function/method use. Look for method synergies that allow you to compose methods that are made up of other methods/functions being passed to it. This might work better in the realm of private class method helpers, but anywhere you can compose a higher order method, you should try to do it rather than calling methods directly. But before you flame the idea, I will say that it really depends on design and if you think possibly a function defined outside of the class could be passed into the method too. If you think it makes sense in that regard, then higher order methods could be an idea that works great.</li>
<li>Strive for immutability. Look to possibly have class variables set as constants. If they can&#8217;t be constant, strictly control the access to that state using setter methods that regulate the set of values that a class variable could implement. You should look to have the possible value set as small as possible. While not truly functional programming immutability, at least having a small value set of well-defined values can be thought of as not changing frequently or limiting their mutability. Obviously using data types that are also immutable by nature (like tuples) will also help enforce this.</li>
<li>Strive for cutting out side effects. Limit state, limit calling on anything outside of what a function is given and this will all certainly help. One great way to know if this is a problem is to go back to the idea that if given a certain value as input, can anything you are doing possibly result in the output not being the same? If the answer is yes, you probably have a side effect. For instance if you give a method the value 4 and depending on what you read from a database the returned value can be 8 or 12, then you know you have a side effect.</li>
</ul>
<h3>Conclusion</h3>
<p>We talked about some of the basic ideas behind functional programming and how the ideas behind some of them might be used to strengthen OOP code. We talked about pure functions and immutability and how we can look to avoid elements in OOP that might violate these rules&#8230; primarily class state. By knowing some of these concepts and looking to get as close as possible to implementing some of these ideas we will find that our OOP code will take on a functional programming flavor that should lead to stronger methods and overall stronger classes. Encapsulating our class state and then putting severe restrictions on how state is managed (looking to avoid state if possible) can lead to methods that exhibit functional programming strengths that may prove useful even in a class context. </p>
<p>I hope you found this article interesting and help improve your code in the future. I enjoy some of these ideas and look forward to implementing many of these concepts in my future coding projects. Thanks for reading! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Using Multiple Submit Buttons With A Single Form</title>
		<link>https://www.coderslexicon.com/using-multiple-submit-buttons-with-a-single-form/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Fri, 02 Apr 2021 20:10:59 +0000</pubDate>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[HTML]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=10968</guid>

					<description><![CDATA[After a while of web development, developers usually come across a project where they need to create multiple submit buttons with a single form. This usually occurs right when they have a table that has several rows and each row has a couple buttons to edit or delete the row. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2021/04/multiple-submit-thumb.png" alt="Multiple Submit Buttons" width="220" height="147" class="alignleft size-full wp-image-10981" />After a while of web development, developers usually come across a project where they need to create multiple submit buttons with a single form. This usually occurs right when they have a table that has several rows and each row has a couple buttons to edit or delete the row. These rows might have been added dynamically using JavaScript or they could have been simply created sever-side as the table is generated from a list of records in a database. When one of the buttons is clicked, you usually need to know what button was clicked and take an action on it. In this post we will take a look at 4 different ways to handle this scenario and what the pros and cons are to each. Let&#8217;s get started!</p>
<h3>Option 1 &#8211; Buttons With Same Name, Different Text</h3>
<p>This solution involves creating several input elements with the type being set to &#8220;submit&#8221;. Their &#8220;name&#8221; attribute is also the same for all the buttons and the value of the button, which is what users see, is usually different. Here is an example of that&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
&lt;input type=&quot;submit&quot; name=&quot;submit_button&quot; value=&quot;Update1&quot;&gt;
&lt;input type=&quot;submit&quot; name=&quot;submit_button&quot; value=&quot;Update2&quot;&gt;
&lt;input type=&quot;submit&quot; name=&quot;submit_button&quot; value=&quot;Update3&quot;&gt;
</pre>
<p>Here you see we have three submit buttons, all with the same name &#8220;submit_button&#8221; but with different values. When the user sees this form, they see the &#8220;Update1&#8221;, &#8220;Update2&#8221; and &#8220;Update3&#8221; labels. When submitted, the clicked button value is placed in the &#8220;submit_button&#8221; name and you can compare the value to know which button was clicked.</p>
<ul>
<li><strong>Pros:</strong>
<ol>
<li>Usually easy to implement, especially if the buttons were added dynamically (through something like JavaScript)</li>
<li>works for older browsers (IE 9 and below usually)</li>
</ol>
</li>
<li><strong>Cons:</strong>
<ol>
<li>Not at all internationally friendly. What if you wanted the form in Spanish? Update1 could be Spanish and you would have to check for the Spanish equivalent.</li>
<li>Also each button has to have a different text value. You couldn&#8217;t name all three &#8220;Update&#8221; and expect to know which one was clicked.</li>
</ol>
</li>
</ul>
<h3>Option 2 &#8211; Different Names For Each Button</h3>
<p>The next solution involves using a different name for each of the buttons. Much like the first solution, this involves using an input type of submit. Here is an example of how this might work&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
&lt;input type=&quot;submit&quot; name=&quot;update_button1&quot; value=&quot;Update&quot;&gt;
&lt;input type=&quot;submit&quot; name=&quot;update_button2&quot; value=&quot;Update&quot;&gt;
&lt;input type=&quot;submit&quot; name=&quot;delete_button&quot; value=&quot;Delete&quot;&gt;
</pre>
<p>Here we have a couple of update buttons and a delete button. Depending on which one is clicked, the server-side script can see a different name submitted (and only one is submitted). So in one case you may see &#8220;update_button2&#8221; as an element in the POST array and another time you may see &#8220;update_button1&#8221;. But never &#8220;update_button1&#8221; AND &#8220;update_button2&#8221; together.</p>
<ul>
<li><strong>Pros:</strong>
<ol>
<li>Internationally friendly because now the button values could be any language. The name is what you would look at in your script.</li>
<li>They can also have the same text (like shown in the example above. We see two &#8220;Update&#8221; buttons and this is fine. Again works for older browsers.</li>
</ol>
</li>
<li><strong>Cons:</strong>
<ol>
<li>Big drawback is now you have to detect if any of these names are in the submission. You have to check if update_button1 is in the submission or is it update_button2 or is it delete_button? The server-side logic here can get tedious and lead to spaghetti code.</li>
<li>The names also have to be unique so this may lead to complex logic for those scripts wanting to create the buttons dynamically. You may find yourself using a loop and creating names like &#8220;update1&#8221;, &#8220;update2&#8243;&#8230; &#8220;updateN&#8221;.</li>
</ol>
</li>
</ul>
<h3>Option 3 &#8211; Use Button Element with Same Name With Different Supplied Value</h3>
<p>Here we take a different approach and instead of using the input element we use a button element. Here we can get some flexibility that seems to solve a lot of previous issues. Here is an example of that&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
&lt;button type=&quot;submit&quot; name=&quot;action&quot; value=&quot;update1&quot;&gt;Update&lt;/button&gt;
&lt;button type=&quot;submit&quot; name=&quot;action&quot; value=&quot;update2&quot;&gt;Update&lt;/button&gt;
&lt;button type=&quot;submit&quot; name=&quot;action&quot; value=&quot;delete&quot;&gt;Delete&lt;/button&gt;
</pre>
<p>Here these buttons will act like a submit button. However, they share the same name and have different values. As you probably can tell, this still solves many of the issues of the other solutions. Let&#8217;s take a look at the pros and cons of this&#8230;</p>
<ul>
<li><strong>Pros: </strong>
<ol>
<li>Internationally friendly because the button text can be any language. That text is not what is submitted, it is what is in the value attribute.</li>
<li>This is also easy to add dynamically as the only thing that needs to be different is the button value attribute. Again you have to make sure these are unique, but being that the user doesn&#8217;t see these it ok to do something like appending a row number. It has the same name, so this is all you have to look for. Clicking the second update button will lead to &#8220;update2&#8221; being the value of &#8220;action&#8221; in the POST submission. Also works fine in older browsers.</li>
</ol>
</li>
<li><strong>Cons: </strong>
<ol>
<li>As mentioned the only real drawback, a minor one, is that the values of each button still has to be unique and so if generated dynamically you have to make those values are unique. Appending a row number or ID should work nicely. Just read the &#8220;action&#8221; POST value and break off the ID/Row from the value. If the values are not all similar, then you still have to detect what value &#8220;action&#8221; has.</li>
</ol>
</li>
</ul>
<h3>Option 4 &#8211; Using Formaction Attribute (Just a Mention)</h3>
<p>Now I don&#8217;t really consider this a solid solution to posting to the same form with multiple buttons because this formaction attribute overrides the action attribute of the form. This causes the submission to be sent to a different location. Now the only reason I am mentioning this solution in the context of this article is that it is fairly new and can be used to at least determine which button was clicked because it goes to a different URL. Our example&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
&lt;button type=&quot;submit&quot; name=&quot;action&quot; formaction=&quot;/update1&quot;&gt;Update&lt;/button&gt;
&lt;button type=&quot;submit&quot; name=&quot;action&quot; formaction=&quot;/update2&quot;&gt;Update&lt;/button&gt;
&lt;button type=&quot;submit&quot; name=&quot;action&quot; formaction=&quot;/delete&quot;&gt;Delete&lt;/button&gt;
</pre>
<p>If the user clicks the first update button, they will submit the form to the [il]/update1[/il] URL. If they click the second update, they will send the form submission to [il]/update2[/il] URL. So as you can see we are not really submitting the buttons to the same form action and thus doesn&#8217;t quite hit the nail on the head when it comes to submitting the values to some server-side processing script.</p>
<p>Lets see some pros and cons of this&#8230;</p>
<ul>
<li><strong>Pros: </strong>
<ol>
<li>Internationally friendly as before since the button text can be any language. Great if you want the buttons to submit to different URLs like REST endpoints perhaps.</li>
<li>Again fairly easy to add these buttons dynamically.</li>
</ol>
</li>
<li><strong>Cons: </strong>
<ol>
<li>Not really submitting values to the same server-side script. If you expect one form &#8220;handler&#8221; script to process the form, then this solution just doesn&#8217;t work.</li>
<li>Requires you to have multiple form submission destinations.</li>
<li>Formaction is also fairly new, so doesn&#8217;t work on browsers like IE9 and below.</li>
</ol>
</li>
</ul>
<h3>What is the best?</h3>
<p>Honestly I think option 3 is really the best in most situations. It offers the most flexibility in that the buttons can be easily generated programatically if desired, you can check out the same name on the server-side script and is internationally friendly if you want to change the text on buttons. I have seen some proponents of the formaction attribute recently, but again it doesn&#8217;t really answer the direct question if you want one simple handler script for your form. So give option 3 a try and if you don&#8217;t like that, you can possibly fall back on option 1. Option 2 is really the only one I wouldn&#8217;t advise in that it really makes the server-side script a bit brittle and hard to scale. If you know you will only have less than 4 or 5 buttons, you could get away with it. </p>
<p>I hope this answered your questions around multiple submit buttons for a single form and hope you find them useful. Thanks again for reading! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating Enumerations in PHP</title>
		<link>https://www.coderslexicon.com/creating-enumerations-in-php/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Sun, 14 Feb 2021 22:50:39 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Abstract Classes]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=10921</guid>

					<description><![CDATA[If you are experienced in any of the major programming languages (.NET, Java, Python etc.) you are probably familiar with the idea of &#8220;Enums&#8221; or &#8220;Enumerations&#8221;. These are used to help increase readability by assigning readable names to a collection of static values. It is much easier to read &#8220;Color.Red&#8221; [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2021/02/enum-colors.png" alt="Color Enumeration" width="220" height="151" class="alignleft size-full wp-image-10923" />If you are experienced in any of the major programming languages (.NET, Java, Python etc.) you are probably familiar with the idea of &#8220;Enums&#8221; or &#8220;Enumerations&#8221;. These are used to help increase readability by assigning readable names to a collection of static values. It is much easier to read &#8220;Color.Red&#8221; than seeing &#8220;#FF0000&#8221; or &#8220;1&#8221;. To expand on this idea imagine writing an if statement where you would compare a hex value to the color red&#8230;. [il]if (&#8220;#FF0000&#8221; == Color.Red) { // Do stuff }[/il] seems to make a bit more sense and straight forward. Or perhaps you are comparing a value against multiple cases in a switch statement. It is easier to compare &#8220;#FF0000&#8221; against Color.Red, Color.Blue and Color.Green than &#8220;#FF0000&#8221;, &#8220;#00FF00&#8221; and &#8220;#0000FF&#8221; or &#8220;1&#8221;, &#8220;2&#8221; and &#8220;3&#8221;.</p>
<p>If you are familiar with enums, and with PHP, you probably are saying &#8220;Hey wait! PHP doesn&#8217;t have enums!&#8221; and you would be right. You get a gold star! But that doesn&#8217;t mean we couldn&#8217;t easily create them using a class. In this article I will quickly show you how we can create enums using a class and constants. In addition, I will show using reflection to look up an enumeration key given a value (which is often the reverse of why you use enums, but could still be warranted). Let&#8217;s get started!</p>
<h3>Enumerations in PHP</h3>
<p>To start off we are going to create a simple color enumeration which will list three colors: Red, Blue and Green. As with other languages you might know we would reference these color values like Color.Red, Color.Blue and Color.Green in our code. We wouldn&#8217;t have to create some kind of class instance or anything. Usually languages define their own enums as part of the language syntax and/or let you add your own. PHP on the other hand does not have this concept. So what we must do is use a class, an abstract class to be exact, to do what we want. For our various values, we will define some constants. This is how it may look&#8230;</p>
<pre class="brush: plain; title: ; notranslate">
abstract class Color {
   const RED = 1;
   const BLUE = 2;
   const GREEN = 3;
}
</pre>
<p>With an abstract class, we don&#8217;t need to create an instance of the class to get access to the variables it contains. With this definition we can begin using our enum class to compare against values 1, 2 and 3 to be RED, BLUE and GREEN respectively. Besides readability, why might we want to use an enum? Well, maybe we can only store the color as an integer in a database. We could store 1 in the database and then compare that value from the database to see if it is equal to Color.RED. Without this enum, we may not know that 1 is the representation of &#8220;red&#8221; in the database. It sounds silly not to just use a string in the database, but you would be surprised why things are never that straight forward&#8230; especially when working in a large organization with dozens of developers.</p>
<h3>How To Use</h3>
<p>Most of you familiar with Enums usually know that you use a period to access the values. For example Color.Blue or Color.Green. Since this is an abstract class and PHP&#8217;s resolution operator for access members of a class is [il]::[/il] then you would have to use [il]Color::BLUE[/il] and [il]Color::GREEN[/il]. Not too bad right? </p>
<h3>Convert an Enum Value Into Its Key</h3>
<p>As touched on in the beginning, most of the time you would use an Enum to compare some value you get from somewhere else to the enum&#8217;s values. Get the value from the database, compare it to Color.BLUE and then change the color of a page to blue in response. However, what about if we have a value like 3 and we want to know what color that is in our enum? Sure we could try that value against each of our three defined constants and have our answer. But what if we don&#8217;t know what all the constant values are? What if there are 20 constants? That would be a bit much to do 20 if/else statements or setup a switch with 20 cases. The code below takes a different approach. We use reflection to get the constants, loop through them and compare the values of each constant to the value we provide. If none is found, we return null. </p>
<pre class="brush: plain; title: ; notranslate">
function getConstantName($enum, $constantValue) {
    try {
        $reflection = new ReflectionClass($enum);
    } catch (ReflectionException $ex) {
        return null;
    }

    $constants = $reflection-&gt;getConstants();

    foreach ($constants as $key =&gt; $val) {
        if ($val === $constantValue) {
            return $key;
        }
    }

    return null;
}
</pre>
<p>With this code we could feed in our Color enumeration name and a value we are looking for and it will return the key. Make sure you give it a enum name or instance of our class that the function can see defined! For instance if we call [il]getConstantName(&#8216;Color&#8217;, 3);[/il] will return &#8220;GREEN&#8221;. You may or may not decide to use this functionality, but it is certainly something you could use if you were wondering if 3 even equals a color defined in our enum &#8220;Color&#8221;. If you use [il]getConstantName(&#8216;Color&#8217;, 6);[/il] you get a null back and know that it is not even a supported color and could default the color of the page to [il]Color::Red[/il].</p>
<h3>Future Considerations</h3>
<p>Now of course I know there is a ton of other things you may want to do with an enum. Heck you could even do something like mixing [il]Color::BLUE[/il] and [il]Color::YELLOW[/il] and want it to return [il]Color::GREEN[/il]. The sky is the limit. Since we have created an abstract class there is no issues with moving your functions into the class and making them static methods. If you do a bit of searching on the web you can find others who mention an idea similar to this and take it in other directions including defining a base class and inheriting from that. I just wanted to provide you with a nice simple and easy to implement solution that will help you make your code much more readable. After all, readability is a key. We write code for other developers to read. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Thanks for reading and keep up the coding! </p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Exception Handling With A Level of Abstraction</title>
		<link>https://www.coderslexicon.com/exception-handling-with-a-level-of-abstraction/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Fri, 10 Jul 2020 01:39:15 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<category><![CDATA[Exception Handling]]></category>
		<category><![CDATA[General Programming]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=10790</guid>

					<description><![CDATA[One of the common topics you always see in programming articles is the one about proper use of exception handling and the try/catch mechanism (if supported by your language of choice). As you absorb the wisdom of the sacred text, looking for that nugget of information about how to do [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2020/07/exception-handling-abstractions.jpg" alt="Exception Handling Abstraction Levels" width="220" height="155" class="alignleft size-full wp-image-10792" />One of the common topics you always see in programming articles is the one about proper use of exception handling and the try/catch mechanism (if supported by your language of choice). As you absorb the wisdom of the sacred text, looking for that nugget of information about how to do it properly, you almost always come across the idea of abstraction. The incantation often reads something like &#8220;Throw exceptions at the proper level of abstraction that makes sense.&#8221; What do they mean by that? How do I know if I am throwing at the correct level? What do they even mean by level? I will break it down for you, bit by bit, in this article.</p>
<h3>Levels of Abstraction, Say What?</h3>
<p>To help illustrate what abstractions are and what other people might mean by levels, I am going to talk about a person. A person is a complex system made up of other systems like the digestive system, circulatory system, endocrine system, nervous system etc. When you talk about a person (in the general sense) you are talking about an abstraction. The person is a &#8220;high level view or concept&#8221; of all those internal systems working together. You don&#8217;t deal with a person&#8217;s circulatory system, you deal with a person as a whole. A person is a concept.</p>
<p>Let&#8217;s say that we were a surgeon who specializes in the circulatory system of the human body (maybe a cardiologist). When we are operating on a person, we are focused on fixing the blood related problems that a person may have. The circulatory system is an abstraction or &#8220;high level view&#8221; of the heart, veins, arteries and capillaries. If the lungs want to deliver oxygen to the body, it has to interact or &#8220;interface&#8221; with this idea of the circulatory system. </p>
<p>If a person is an abstraction of their body&#8217;s subsystems, a subsystem is an abstraction of its subsystems and on and on we go. These form the levels. Our world is full of abstractions because it helps us think about the world. We can deal in the abstraction, talking to a person, without knowing how their circulatory system works. </p>
<h3>Where does exceptions fit into all this?</h3>
<p>Well, the human body has its issues. We get sick, our bodies break down to aging or something in one system goes wrong and it can make us feel like garbage. Imagine that you were talking to your friend and suddenly they yelled out &#8220;Stomach acid overflow detected, aborting!&#8221; You would probably be like &#8220;Wtf?&#8221; This is a scenario where an error in the digestive system throws an exception and it is not caught until it reaches your ears. The proper level of abstraction would have suggested that instead the digestive system throws the exception and it is caught by the person who owns the stomach where it is translated to &#8220;Heartburn&#8221;. Your friend then says, in a more friendly message, &#8220;Oh I think that burger didn&#8217;t agree with me. I have a bit of heartburn.&#8221;</p>
<p>We in the outside world should not be talking to your stomach, we talk to the person. The person is what &#8220;abstracts away&#8221; the functions of the digestive system. It does us no good to know of a stomach acid overflow because what does that mean to us or how are we suppose to realize that is heartburn. Imagine a single cell dies. Does it need to throw that fact up all the way to the person? Can you imagine knowing about every cell in your body when it dies?</p>
<h3>Handling exceptions and their levels in software</h3>
<p>Taking the same concept, and providing an example in software, imagine you have a class that is responsible for interacting with a website. It opens a connection, sends and receives data and closes the connection. It has many moving parts or subsystems. As an abstraction, you deal with the class WebsiteConnection, you don&#8217;t care about the underlying parts of how it sends and retrieves the data. Much like our example of the stomach, if the connection fails we don&#8217;t throw a raw exception up to say &#8220;opening TCP connection failed&#8221;. We may not even know the class ueses a tcp connection, nor do we even care. All we care about is if the class is successful in reading the website. The dead give away that this is the problem is when you read the error and say &#8220;Where do I even setup a TCP connection?&#8221; because it appears to you that you are only dealing with a WebsiteConnection and mention nothing of TCP.</p>
<h3>The Problem We Are Trying to Solve</h3>
<p>The problem with not throwing exceptions on the right level is that it leaks information that we may not even be aware of. In our class example, it just leaked that it opens the connection with a TCP connection. We as developers may not mind this, but imagine that someone is using our image editing app and suddenly they get an error message pop up saying &#8220;opening TCP connection failed&#8221;. They will be like &#8220;What does that mean?&#8221;</p>
<p>Not only are we unaware, we are now forced to know all the inner details of our class and the exceptions it may throw. Should we be looking to catch a TCP specific exception when dealing with a WebsiteConnection class? What about IOException? I don&#8217;t know, I would have to look at the source code of the class or read the docs. I hope you get my point.</p>
<p>One rule you may see people mention is that you should not try to catch an exception if you don&#8217;t know how to handle it. In general this is very good advice. The one exception (pun not intended) to this is in the case of levels of abstraction. It is perfectly acceptable to catch that TCP connection failed exception only to wrap it in a new exception that makes more sense at the higher level. For example, you catch TCP connection failed inside your class but then you wrap it in a new exception called &#8220;ReadConnectionException&#8221; and has a message of &#8220;Unable to read data from the website. Maybe it is down.&#8221; and throw that. If an exception like that bubbles up to the user at least it will make sense. It will be a message at a higher level of understanding where the user is not being exposed to the inner workings of network error messages.</p>
<h3>Applying Out Solution</h3>
<p>Let&#8217;s go back to our Person/DigestiveSystem analogy and take a look at a generic example where we have two classes. Person makes use of the DigestiveSystem class. Let&#8217;s try and apply our new idea of escalating exceptions at the proper level.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class DigestiveSystem {
	public function Digest($food) {
		// Something goes wrong
		throw new DigestionException(&quot;Stomach acid overflow! Aborting!&quot;);
	}
}

class Person {
	protected $name;
	protected $age;
	protected $digestiveSystem;

	public function __construct($name, $age) {
		$this-&gt;name = $name;
		$this-&gt;age = $age;
		$this-&gt;digestiveSystem = new DigestiveSystem();
	}

	public function eat($food) {
		// This will throw the exception, but since we don't catch it, it bubbles up out of the person class.
		// Wrong level of abstraction!
		$this-&gt;digestiveSystem-&gt;digest($food);
	}
}
</pre>
<p>Here is one way we could write the eat() method to better utilize the correct level of abstraction from DigestiveSystem to Person&#8230;</p>
<pre class="brush: php; title: ; notranslate">
public function eat($food) {
	// This time we catch the exception at this level and even though we can't do anything about it now,
	// we will wrap it up and throw it with the correct level of abstraction.
	// This way any user of the Person class sees a message and exception that makes sense!
	try {
		$this-&gt;digestiveSystem-&gt;digest($food);
	} catch (DigestionException $e) {
		// Notice we include $e in the exception so we have the stack trace
		// Also notice that this new exception makes more sense coming from a person.
		// We could also take this opportunity to do something internally with $e (like log it).
		throw new HeartBurnException(&quot;Whoa, $food doesn't agree with me! I have heartburn!&quot;, 0, $e);
	}
}
</pre>
<p>As you can see from the code and comments above, we don&#8217;t let the DigestiveSystem exception bubble its way out of the Person class. We capture it, re-wrap it and throw it up but this time in a more correct context. A person can have heart burn, their stomach doesn&#8217;t tell you that stomach acid is overflowing. Now don&#8217;t abuse this with all your exceptions. Too much wrapping can lead to complexity and make things less readable. Use in moderation! Also, if you do use it, make sure to ALWAYS put the inner exception so you don&#8217;t lose your stack tracing!</p>
<h3>Conclusion</h3>
<p>In this article we talked about the idea of an abstractions or &#8220;high level view/concept&#8221; of one or more subsystems/components. A person is an abstraction of its various internal subsystems. A car is an abstraction of an engine, tires, steering wheel etc. An engine is an abstraction of its pistons, spark plugs, timing belts etc. We talked about how a level of abstraction is how deep into the systems we view. A person is one level of abstraction, a digestive system is another, a stomach is another level etc.</p>
<p>After that we translated the concepts over to software and code design. We talked about how a sub system of a class should not be shouting its issues directly outside the class. If you find yourself trying to catch a TCP exception for a class called &#8220;WebsiteConnection&#8221; then you should see a red flag because you would have to know that WebsiteConnection is using a TCP connection to start to know it is going to possibly throw that kind of exception.</p>
<p>We revisited our earlier example and provided one quick code example of how we could properly throw exceptions at the right level. We captured the internal exception, re-wrapped it and threw it with a more correct context.</p>
<p>If you make sure that the types of exceptions that make their way up from the specific method, to class, to component to system and on to the user are at the proper levels of abstraction, the exception should always make sense. If you see an exception that appears to be cryptic on an abstraction that is general in nature, be reminded of my example. You don&#8217;t care to know about a person&#8217;s stomach, you care to know about the person.</p>
<p>Thanks for reading! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Minimalism in Code</title>
		<link>https://www.coderslexicon.com/minimalism-in-code/</link>
		
		<dc:creator><![CDATA[Martyr2]]></dc:creator>
		<pubDate>Sun, 12 Jan 2020 22:59:27 +0000</pubDate>
				<category><![CDATA[General Discussion]]></category>
		<category><![CDATA[Programming Theory]]></category>
		<guid isPermaLink="false">https://www.coderslexicon.com/?p=10675</guid>

					<description><![CDATA[You may have heard of minimalism before in all sorts of disciplines and philosophies of life. Some of you might have heard of it as living without many possessions or perhaps in computing to refer to using as least amount of hardware and software resources as possible. I would like [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" src="https://www.coderslexicon.com/wp-content/uploads/2020/01/minimal.png" alt="Minimalism in Code" width="200" height="159" class="alignleft size-full wp-image-10682" />You may have heard of minimalism before in all sorts of disciplines and philosophies of life. Some of you might have heard of it as living without many possessions or perhaps in computing to refer to using as least amount of hardware and software resources as possible. I would like to take a small spin on perspective of applying this philosophy of life and apply it to writing code. While I believe the minimalism of computing is a bit more about the resources, I will speak of minimalism more in terms of using less in programming.</p>
<h4>Why even adopt such a philosophy?</h4>
<p>&#8220;Ok Martyr, why even should I care about any of this code minimalism garbage?&#8221; Well, you should always be striving to write better code. No matter how many years you have tucked under your belt writing systems, you can always improve. Many programmers tend to look at a piece of simple chunk of minimal code and think of it as &#8220;elegant&#8221;. It just makes sense. It has no unneeded statements, no fancy tricks, straight to the point and has ultimate readability. Minimalism, as I think of it, will help with all of these things. The philosophy has a few key ideas&#8230;</p>
<ol>
<li>Decompose complex problems to ridiculously simple functions, statements and structures.</li>
<li>Don&#8217;t bloat your code to use the most fancy syntax sugar.</li>
<li>Use as few steps as possible to solve the problem in a straight forward manner. We are NOT talking about premature optimization.</li>
<li>Lastly, uphold good readability with proper naming and adequate spacing. In other words, maintain a good code rhythm and style.
</ol>
<p>You may follow some, or all, of these tips already and that is good. I am trying to codify the practice into a way of thinking that will help you realize what it means to have simple code. I think many programmers still don&#8217;t know what it all means. They also don&#8217;t realize why much of the code they see online is largely bad code. By the way, I think much of this code online is written by people who are new or just writing enough to get a job done&#8230; not that they are passionate. Read my article on &#8220;<a href="https://www.coderslexicon.com/why-everyone-should-not-learn-to-code/" rel="noopener noreferrer" target="_blank">Why everyone should NOT learn to code</a>&#8221; for my ideas about that.</p>
<h4>Decompose complex problems in simple terms</h4>
<p>Programmers are complex thinkers. As engineers we think of a solution and it is often the first one we think of that we go with. It is also the first one we think of that is the most complex. We lean on what we know, we lean on something we just read and want to try out, we also think about the code we might have already written that could help and shoe horn that code into the solution. </p>
<p>Just recently I was in a meeting with other engineers who needed to solve a problem about running some desktop style software from the web. We needed a web interface to feed data into a command line across languages, across systems and across platforms. Of course as soon as the engineers started brain storming they started throwing out ideas like &#8220;We could use a file to store some parameters and the software could read this file using a queue, but it would need access to the other server. Oh and what about race conditions and timing and &#8230;&#8221; I sat back and let the ideas roll a bit and then started throwing out ideas that many people thought at first were counter productive. &#8220;We don&#8217;t need a file. Heck, the front-end doesn&#8217;t even need to store the parameters. On top of that the other server doesn&#8217;t even care about the front-end. We don&#8217;t need to do that, this or the other thing. That is all too complex.&#8221;</p>
<p>The other developers were confused at first but then immediately caught on to what I was doing. I wasn&#8217;t talking specifics quite yet, but they saw that I was reducing reducing and simplifying the problem space. As I chopped away at the problem, they saw the code they would write get more minimal and simpler. That is what we want! Simple means clear, concise and often has a lower bug rate. For the developers, it also meant less code writing and more at work doing something else more in line with their passions.</p>
<h4>Don&#8217;t bloat your code to use the most fancy syntax sugar</h4>
<p>Ok, one of the problems I am finding, particularly with C# (btw C# is my favorite compiled language) is that they keep introducing stupid syntax sugar. We talk about readability yet they take what was simple loops and reduce them to dumb lines that to the untrained reader doesn&#8217;t even look like a loop. Yeah simple for experienced users, but horrible for new people. Sure the language lets you do this, but it doesn&#8217;t mean you should. Of course we are always excited to use what we just read about from the latest tech magazine, but it may not be the most straight forward way to do it. Often times I see 3 lines of code added just to setup the situation to use the new line of code. I could have just written 1 line of run-of-the-mill code and accomplish the same thing. Use the simplest syntax to get the point across.</p>
<h4>Use as few steps as possible</h4>
<p>People read this principle and think premature optimization. I am not talking about that. Going back to the previous paragraph above, if you find yourself adding code to use other code rather than a simpler non-glamorous way, you are doing it wrong. We can always optimize later, but often times we want code that just looks vanilla and does the task. I rather stare at a simple loop and say &#8220;Duh, seen this a 1000 times before&#8221; than see a new line of code with a bunch of setup code and be like &#8220;What the heck is this?&#8221; Don&#8217;t write 4 lines to do what 1 line would do easily. I know it is not exciting, but you will be more excited when you have less bugs and things &#8220;just work&#8221; at the end.</p>
<h4>Do NOT reduce readability</h4>
<p>This rule is the top rule of them all. Minimal code doesn&#8217;t mean the fewest character variable names and a ton of abbreviations. It is minimal in its ideas and thoughts. If you are making a peanut butter and jelly sandwich, call it a knife, not a &#8220;metallic serrated blade used for cutting&#8221;. Call your variables what they are, what everyone would know it as, what a 5 year old looking at it would know it as. Simple ideas make for simple code and simple code starts with simple words.</p>
<h4>Conclusion</h4>
<p>No matter the language, I think if you adopt one, or many, of these principles when thinking about your next class/function/data structure you may find your code &#8220;boring&#8221; but it would also be highly effective and usable. That project I spoke of earlier, I minimalized the process so much in the end it lead to my work load being reduced from something like a week to 1.5 days. I needed to write a little HTML/CSS/JS and talk to a few REST endpoints using some AJAX. I don&#8217;t have to worry about files flying back and forth, I don&#8217;t have to worry about a database connection and how the other process would read it. In addition to that, I put more pieces into a preferred partner platform we wanted to show off (for the curious it was Amazon) which would make the bosses happy. All because I apply a few minimal code philosophies to what others thought would be a much more complex project. The major pay off, I won&#8217;t have a dev a year down the road coming to me to ask what the code does. They just look at it in all its simple glory! Thanks for reading!</p>
<p>If you liked this article and want to get started with a project, consider my book called &#8220;<a href="http://www.coderslexicon.com/downloads/the-programmers-idea-book/">The Programmers Idea Book</a>&#8220;. It features 200 project ideas including comments to get started, resource links, difficulty rating and more. </p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
