<?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>Pattern &amp; Best Practice &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/category/pattern/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Fri, 08 Mar 2024 12:10:24 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Outbound-Pattern Microservices Architektur: Sichere Datenübergabe in verteilten Systemen</title>
		<link>https://sterl.org/2024/03/outbound-pattern-microservices-architektur-sichere-datenuebergabe-in-verteilten-systemen/</link>
					<comments>https://sterl.org/2024/03/outbound-pattern-microservices-architektur-sichere-datenuebergabe-in-verteilten-systemen/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 08 Mar 2024 12:08:51 +0000</pubDate>
				<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[YouTube]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Micro Services]]></category>
		<category><![CDATA[Outbound Pattern]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[software architektur]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=1020</guid>

					<description><![CDATA[In verteilten Systemen, wie Microservice-Architekturen, stellen sich unweigerlich folgende Fragen: Das Outbound-Pattern kann uns hierbei helfen, dieses Problem zu lösen. Es handelt sich um eine bewährte Methode, um Datenkonsistenz und Transaktionen in verteilten Systemen zu gewährleisten.]]></description>
										<content:encoded><![CDATA[
<p>In verteilten Systemen, wie Microservice-Architekturen, stellen sich unweigerlich folgende Fragen:</p>



<ol class="wp-block-list">
<li>Wie können wir Daten/Updates sicher bzw. transaktional zwischen den Services übergeben?</li>



<li>Wie schaffen wir es, dass die unterschiedlichen Services nicht auseinanderlaufen?</li>
</ol>



<p>Das Outbound-Pattern kann uns hierbei helfen, dieses Problem zu lösen. Es handelt sich um eine bewährte Methode, um Datenkonsistenz und Transaktionen in verteilten Systemen zu gewährleisten.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Outbound-Pattern Microservices Architektur: Sichere Datenübergabe in verteilten Systemen" width="640" height="360" src="https://www.youtube.com/embed/Nzdpcuk5GdQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2024/03/outbound-pattern-microservices-architektur-sichere-datenuebergabe-in-verteilten-systemen/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Grundlagen Datenbanken &#124; als Architekt &#124; DB Locks vs Write Ahead &#124; Event-Sourcing &#124; Micro Services</title>
		<link>https://sterl.org/2023/12/grundlagen-datenbanken-als-architekt-db-locks-vs-write-ahead-event-sourcing-micro-services/</link>
					<comments>https://sterl.org/2023/12/grundlagen-datenbanken-als-architekt-db-locks-vs-write-ahead-event-sourcing-micro-services/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 30 Dec 2023 11:21:43 +0000</pubDate>
				<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[YouTube]]></category>
		<category><![CDATA[Architekt]]></category>
		<category><![CDATA[Best Practice]]></category>
		<category><![CDATA[Datenbanken]]></category>
		<category><![CDATA[Datenbankoptimierung]]></category>
		<category><![CDATA[Event-Sourcing]]></category>
		<category><![CDATA[Locks]]></category>
		<category><![CDATA[Micro Services]]></category>
		<category><![CDATA[Micro Services skallieren]]></category>
		<category><![CDATA[Write Ahead]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=984</guid>

					<description><![CDATA[]]></description>
										<content:encoded><![CDATA[
<ol class="wp-block-list">
<li>Was können Architekten tun, um parallele Objektzugriffe zu synchronisieren, ohne die Skalierbarkeit zu beeinträchtigen? </li>



<li>Wie verarbeitet unser System nach einer Downtime viele Updates auf einmal? </li>



<li>Strategien zur Bewältigung von Lastspitzen: Ist ein DB Lock die Lösung? </li>



<li>Wann sollten Locks in der Architektur eingesetzt werden? </li>



<li>Wann sind Write-Ahead Logs sinnvoll und welche Vor- und Nachteile gibt es? </li>



<li>Weitere Optimierungsmöglichkeiten: 
<ul class="wp-block-list">
<li>Wie kann Event-Sourcing-Architketur helfen? </li>



<li>Wie kann eine Microservice-Architketur helfen?</li>
</ul>
</li>
</ol>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Datenbanken Grundlagen | als Architekt | DB Locks vs Write Ahead | Event-Sourcing | Micro Services" width="640" height="360" src="https://www.youtube.com/embed/57ditWK_uKw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2023/12/grundlagen-datenbanken-als-architekt-db-locks-vs-write-ahead-event-sourcing-micro-services/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Microservices Event- &#124; Command- &#124; Data-Bus &#124; Event Driven</title>
		<link>https://sterl.org/2023/10/microservices-event-command-data-bus-event-driven/</link>
					<comments>https://sterl.org/2023/10/microservices-event-command-data-bus-event-driven/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 13 Oct 2023 08:02:30 +0000</pubDate>
				<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[YouTube]]></category>
		<category><![CDATA[Command Bus]]></category>
		<category><![CDATA[Data Bus]]></category>
		<category><![CDATA[Event Bus]]></category>
		<category><![CDATA[Event Driven]]></category>
		<category><![CDATA[Microservices]]></category>
		<category><![CDATA[software architektur]]></category>
		<category><![CDATA[training]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=977</guid>

					<description><![CDATA[Was kann schon schief gehen? Ereignisgesteuerte (Event Driven) Architekturen dienen keinem Selbstzweck. Häufig soll sie Problemen vorbeugen und uns helfen eine stabile Service Architektur zu entwickeln. Abseits vom &#8222;Happy Case&#8220;, was kann den wie und wo schief gehen; wie kann uns diese Architektur helfen? Wir schauen uns drei typische Lösungsmethoden an:]]></description>
										<content:encoded><![CDATA[
<p>Was kann schon schief gehen?</p>



<p>Ereignisgesteuerte (Event Driven) Architekturen dienen keinem Selbstzweck. Häufig soll sie Problemen vorbeugen und uns helfen eine stabile Service Architektur zu entwickeln. Abseits vom &#8222;Happy Case&#8220;, was kann den wie und wo schief gehen; wie kann uns diese Architektur helfen?</p>



<p>Wir schauen uns drei typische Lösungsmethoden an:</p>



<ol class="wp-block-list">
<li>Event Bus </li>



<li>Command Bus</li>



<li>Data Bus</li>
</ol>



<figure class="wp-block-embed is-type-wp-embed is-provider-pauls-blog wp-block-embed-pauls-blog"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="UXukIktPzo"><a href="https://sterl.org/2023/10/useful-links-for-event-driven-architectures/">Useful links for Event Driven Architectures</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8222;Useful links for Event Driven Architectures&#8220; &#8212; Pauls Blog" src="https://sterl.org/2023/10/useful-links-for-event-driven-architectures/embed/#?secret=t04w2nAzky#?secret=UXukIktPzo" data-secret="UXukIktPzo" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Microservices Event- | Command- | Data-Bus | Event Driven | Was kann schon schief gehen?" width="640" height="360" src="https://www.youtube.com/embed/fJCAhTeZv7I?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2023/10/microservices-event-command-data-bus-event-driven/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Datenbanken &#124; Transaktionen &#124; Locks &#124; Isolationslevel</title>
		<link>https://sterl.org/2023/10/datenbanken-transaktionen-locks-isolationslevel/</link>
					<comments>https://sterl.org/2023/10/datenbanken-transaktionen-locks-isolationslevel/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Tue, 03 Oct 2023 09:12:50 +0000</pubDate>
				<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[YouTube]]></category>
		<category><![CDATA[ACID]]></category>
		<category><![CDATA[Datenbanken]]></category>
		<category><![CDATA[Isolationslevel]]></category>
		<category><![CDATA[Locks]]></category>
		<category><![CDATA[Transaktionen]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=962</guid>

					<description><![CDATA[Als Basis für weiterführende Videos zum Thema Event Driven Architekturen, oder Eventual Consistency wollen wir uns zusammen Datenbanken und Transaktionen anschauen. Hier geht es darum ein Grundverständnis für Basiskonzepte zu schaffen wie:]]></description>
										<content:encoded><![CDATA[
<p>Als Basis für weiterführende Videos zum Thema Event Driven Architekturen, oder Eventual Consistency wollen wir uns zusammen Datenbanken und Transaktionen anschauen. Hier geht es darum ein Grundverständnis für Basiskonzepte zu schaffen wie:</p>



<ul class="wp-block-list">
<li>Transaktionen</li>



<li>ACID </li>



<li>Isolationslevel</li>



<li>Locks</li>
</ul>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Datenbanken Grundlagen | Transaktionen | Locks | Isolationslevel | praktisch erklärt | transactions" width="640" height="360" src="https://www.youtube.com/embed/F8Hdrb62-4c?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2023/10/datenbanken-transaktionen-locks-isolationslevel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Datenbank Timeouts &#124; Locks &#124; Isonaltionlevel &#124; Transaktionen</title>
		<link>https://sterl.org/2023/10/datenbank-timeouts-locks-isonaltionlevel-transaktionen/</link>
					<comments>https://sterl.org/2023/10/datenbank-timeouts-locks-isonaltionlevel-transaktionen/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Mon, 02 Oct 2023 11:15:27 +0000</pubDate>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[YouTube]]></category>
		<category><![CDATA[Datenbanken]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Isonaltionlevel]]></category>
		<category><![CDATA[Lock]]></category>
		<category><![CDATA[Locks]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[Timeouts]]></category>
		<category><![CDATA[Transaktionen]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=955</guid>

					<description><![CDATA[Häufig vergessen, oder nur teilweise gemacht. Timeouts tragen einen wesentlichen Bestandteil zur Stabilität und dem Ressourcenmanagement von Software bei. Insbesondere bei Microservices sollten diese immer richtig eingestellt sein. Timeouts spielen auch eine wesentliche Rolle in Bezug auf Transaktionen, Locks und Isolationslevel. Sollte man zudem den Zugriff auf die Datenbank auch Dritten gewähren, also nicht nur&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Häufig vergessen, oder nur teilweise gemacht. Timeouts tragen einen wesentlichen Bestandteil zur Stabilität und dem Ressourcenmanagement von Software bei. Insbesondere bei Microservices sollten diese immer richtig eingestellt sein. Timeouts spielen auch eine wesentliche Rolle in Bezug auf Transaktionen, Locks und Isolationslevel. Sollte man zudem den Zugriff auf die Datenbank auch Dritten gewähren, also nicht nur den Services selbst, dann sind diese umso wichtiger, für alle Clients, die auf die Datenbank zugreifen.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Datenbanken Grundlagen | Timeouts | Locks | Isonaltionlevel | DB | als Architekt | Microservices" width="640" height="360" src="https://www.youtube.com/embed/cW_k_VtOVmQ?start=217&#038;feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2023/10/datenbank-timeouts-locks-isonaltionlevel-transaktionen/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>A better way for TypeScript Enum</title>
		<link>https://sterl.org/2023/08/a-better-way-for-typescript-enum/</link>
					<comments>https://sterl.org/2023/08/a-better-way-for-typescript-enum/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 18 Aug 2023 11:10:28 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[TypeScript]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Pattern]]></category>
		<category><![CDATA[Patterns]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=939</guid>

					<description><![CDATA[A better way to define enums in Typescript In this way it is much easier to provide an enum including a potential mapping to a different value e.g. a display value. This solution is usually considered being better, as long as enums aren&#8217;t supported by JavaScript natively. Links]]></description>
										<content:encoded><![CDATA[
<p>A better way to define <code>enums</code> in Typescript</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/typescript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;TypeScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;typescript&quot;}">const ORDER_STATUS = {
  OPEN: 'Offen',
  ORDERED: 'Bestellt',
  CANCELED: 'Storniert'
} as const;

type OrderStatus = keyof typeof ORDER_STATUS;

function methodWithEnum(status: OrderStatus) {
    console.info(`${ORDER_STATUS[status]}: ${status}`);
}

methodWithEnum(&quot;OPEN&quot;);</pre></div>



<p>In this way it is much easier to provide an <code>enum</code> including a potential mapping to a different value e.g. a display value.</p>



<p>This solution is usually considered being better, as long as <code>enums</code> aren&#8217;t supported by JavaScript natively.</p>



<h2 class="wp-block-heading">Links</h2>



<ul class="wp-block-list">
<li><a href="https://www.typescriptlang.org/docs/handbook/enums.html" target="_blank" rel="noreferrer noopener">https://www.typescriptlang.org/docs/handbook/enums.html</a></li>



<li><a href="https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums" target="_blank" rel="noreferrer noopener">https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2023/08/a-better-way-for-typescript-enum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Clean Code</title>
		<link>https://sterl.org/2020/12/clean-code/</link>
					<comments>https://sterl.org/2020/12/clean-code/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Tue, 22 Dec 2020 13:12:00 +0000</pubDate>
				<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=774</guid>

					<description><![CDATA[Jede Funktion macht genau eine Sache Damit wird sichergestellt das dieser eine klare API und Funktion hat und der Nutzer einer Methode nicht überrascht wird, zB indem es zu einem unerwarteten Seiteneffekt führt. Beispiele: &#8222;readPersonById&#8220; ändern zudem auch den Status in der DB, weil es den Zugriff protokolliert &#8222;formatDate&#8220; vom DateFormatter führt zu einem Fehler,&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Jede Funktion macht genau eine Sache</h2>



<p>Damit wird sichergestellt das dieser eine klare API und Funktion hat und der Nutzer einer Methode nicht überrascht wird, zB indem es zu einem unerwarteten Seiteneffekt führt. Beispiele:</p>



<ul class="wp-block-list"><li>&#8222;readPersonById&#8220; ändern zudem auch den Status in der DB, weil es den Zugriff protokolliert</li><li>&#8222;formatDate&#8220; vom DateFormatter führt zu einem Fehler, weil statisch auf eine Lokalisierungsdatei zugegriffen wird, die erst geladen werden muss, welche sich aber in einem anderen Modul befindet</li><li>&#8222;readFile&#8220; löscht auch die Datei nach dem einlesen</li></ul>



<h2 class="wp-block-heading">Sollte lesbar sein</h2>



<p>Variablen und Methoden drücken das aus, für was sie stehen z.B.</p>



<ul class="wp-block-list"><li>&#8222;Magic Numbers&#8220; wurden als Konstanten definiert und sprechend benannt</li><li>Komplizierte IF Prüfungen wurden als eigene benannte Funktionen extrahiert</li></ul>



<p>dadurch sollte sich eine Art lesbarer Code ergeben.</p>



<h2 class="wp-block-heading">Kommentare sollten weitgehend nicht notwendig sein</h2>



<p>Durch die Verwendung von sprechenden Methoden- und Variablennamen sind weitere Kommentare nicht notwendig. Wenn überhaupt dann auf Klassen bzw. Public-Methoden ebene ein Verweis auf JIRA oder Confluence stehen, bzw. die Verantwortung eines Services abgegrenzt werden.</p>



<h2 class="wp-block-heading">Code einer Methode sollte der Erwartung entsprechen</h2>



<p>Ein Entwickler sollte beim lesen der Implementierung einer Methode möglichst nicht überrascht werden. Da er aufgrund des Methodennamen bereits rückschließen konnte wie die Methode aufgebaut ist, bzw. was diese macht.</p>



<h2 class="wp-block-heading">Der Code sollte einfach zu verstehen sein</h2>



<p>Jeder im Team sollte den Code schnell erfassen und ändern können, z.B. nach einem Jahr wenn man selbst die fachlichen Anforderungen weitergehen vergessen hat, warum der Code so ist.</p>



<h2 class="wp-block-heading">Darf keine zirkulären Abhängigkeiten haben</h2>



<h2 class="wp-block-heading">Jedes Modul modifiziert nur seinen eigenen Status</h2>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2020/12/clean-code/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Dates, DateTime, Timezone and the DB</title>
		<link>https://sterl.org/2017/10/dates-datetime-timezone-and-the-db/</link>
					<comments>https://sterl.org/2017/10/dates-datetime-timezone-and-the-db/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sun, 08 Oct 2017 12:08:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Best Practice]]></category>
		<category><![CDATA[Instant]]></category>
		<category><![CDATA[LocalDate]]></category>
		<category><![CDATA[LocalDateTime]]></category>
		<category><![CDATA[OffsetDateTime]]></category>
		<category><![CDATA[Pattern]]></category>
		<category><![CDATA[Timezone]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=684</guid>

					<description><![CDATA[TL;DR Summary Java Type DB Type Description SAVE Long NUMBER Just using a long as milliseconds, between the current time and midnight, January 1, 1970 UTC is the most secure way. SAVE Instant NUMBER Using in Java an Instant and converting it into a NUMBER to save it in the DB will also avoid any&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">TL;DR Summary</h2>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><th></th><th>Java Type</th><th>DB Type</th><th>Description</th></tr><tr><td><span class="badge badge-success">SAVE</span></td><td><code>Long</code></td><td><code>NUMBER</code></td><td>Just using a long as milliseconds, between the current time and midnight, January 1, 1970 UTC is the most secure way.</td></tr><tr><td><meta charset="utf-8"><span class="badge badge-success">SAVE</span></td><td><code>Instant</code></td><td><code>NUMBER</code></td><td>Using in Java an <code>Instant</code> and converting it into a <code>NUMBER</code> to save it in the DB will also avoid any issues you might encounter. APIs using the <a rel="noreferrer noopener" href="https://datatracker.ietf.org/doc/html/rfc3339" target="_blank">RFC3339</a> format usually also avoids any problems.</td></tr><tr><td><span class="badge badge-warning">CONFIGURE</span></td><td><meta charset="utf-8"><code>Instant</code></td><td><meta charset="utf-8"><code>TIMESTAMP</code></td><td>Ensure you set your JDBC driver to UTC, as it might cause issues saving and loading the date. e.g.: <code>spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code></td></tr><tr><td><span class="badge badge-error">AVOID</span></td><td><code>OffsetDateTime</code></td><td><meta charset="utf-8"><code>TIMESTAMP</code></td><td>If an offset time zone is used, ensure the DB type support the time zone too.</td></tr><tr><td><meta charset="utf-8"><span class="badge badge-success">SAVE</span></td><td><meta charset="utf-8"><code>OffsetDateTime</code></td><td><meta charset="utf-8"><code>TIMESTAMP</code> <code>with timezone</code></td><td>A time stamp with zone e.g. <code>timestampz</code> in PostgreSQL combined with an <code>OffsetDateTime</code> is usually a save way to go too.</td></tr><tr><td><span class="badge badge-error">AVOID</span></td><td><code>LocalDateTime</code></td><td><meta charset="utf-8"><code>TIMESTAMP</code></td><td>Avoid the usage of local date or local date time. if this is not possible use always a time zone and set it in the jdbc driver e.g.:<br><code>ZonedDateTime.now(ZoneOffset.UTC)</code><br><code>spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code><br><code>-Duser.timezone=UTC</code></td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Problem </h2>



<p>Working with dates and a DB usually tends to create issues: </p>



<ul class="wp-block-list"><li>Which type to use?</li><li>Which type to save in the DB?</li><li>How to handle time zones?</li><li>How to avoid moving times?</li><li>How to show the time in the correct time zone of the user?</li></ul>



<h2 class="wp-block-heading">Scenario</h2>



<figure class="wp-block-image size-large"><a href="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone.png"><img loading="lazy" decoding="async" width="1024" height="583" src="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-1024x583.png" alt="" class="wp-image-731" srcset="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-1024x583.png 1024w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-300x171.png 300w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-768x437.png 768w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone.png 1374w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>Times zones scenario</figcaption></figure>



<h3 class="wp-block-heading">Our test entity</h3>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Entity @Data
public class Person {
  @Id
  private Long id;
    
  private long longDate;
    
  private Instant instantDate;
    
  private LocalDateTime localDateTime;
    
  private OffsetDateTime offsetDateTime;
    
  @Column(columnDefinition = &quot;timestamptz&quot;) // we use here postgresql
  private OffsetDateTime offsetDateTimeZone;
}</pre></div>



<h3 class="wp-block-heading">Given</h3>



<ul class="wp-block-list"><li>We use the entity above</li><li>We use a PostgreSQL DB</li><li>Service instance 1 accesses the DB using the time zone GMZ / UTC</li><li>Service instance 2 accesses the DB using the time zone GMZ + 1</li><li>We have one or more users with direct DB access from their local computer using the time zone Europa/Berlin</li><li>We have currently winter time as it is october</li></ul>



<h3 class="wp-block-heading">When</h3>



<ul class="wp-block-list"><li>Service instance 1 write a record into the DB</li></ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;ruby&quot;,&quot;mime&quot;:&quot;text/x-ruby&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Ruby&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;ruby&quot;}">// Instance 1: GMT WRITE
Person(
  longDate           = 1507751058820, 
  instantDate        = 2017-10-11T19:44:18.820418Z, 
  localDateTime      = 2017-10-11T19:44:18.969400, 
  offsetDateTime     = 2017-10-11T19:44:18.969438Z, 
  offsetDateTimeZone = 2017-10-11T19:44:18.969455Z
)</pre></div>



<h3 class="wp-block-heading">Then</h3>



<ul class="wp-block-list"><li>Service Instance 2 reads the data</li></ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;ruby&quot;,&quot;mime&quot;:&quot;text/x-ruby&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Ruby&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;ruby&quot;}">-- Instance 2: GMT+01:00 READ
Person(
  longDate           = 1507751058820, // correct
  instantDate        = 2017-10-11T18:44:18.820418Z, // wrong by one hour
  localDateTime      = 2017-10-11T19:44:18.969400,  // wrong by one hour as local time zone is +1
  offsetDateTime     = 2017-10-11T19:44:18.969438+01:00, // wrong by one hour too late
  offsetDateTimeZone = 2017-10-11T20:44:18.969455+01:00  // correct
)</pre></div>



<ul class="wp-block-list"><li>A user looks into the DB</li></ul>



<figure class="wp-block-image size-large"><a href="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view.png"><img loading="lazy" decoding="async" width="1024" height="68" src="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view-1024x68.png" alt="" class="wp-image-739" srcset="https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view-1024x68.png 1024w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view-300x20.png 300w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view-768x51.png 768w, https://sterl.org/wp-content/uploads/2021/10/java-date-time-zone-user-view.png 1384w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>



<p>Only the <code>timestampz</code>, number and instant column value looks okay. Storing an offset date into a type which doesn&#8217;t support the time zone leads here to an error.</p>



<h3 class="wp-block-heading">Change the JDBC session to UTC</h3>



<p>If the JDBC session is adjusted to use UTC instead of the JVM time zone using e.g. <meta charset="utf-8"><code>spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code> we end up with the following result:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;ruby&quot;,&quot;mime&quot;:&quot;text/x-ruby&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Ruby&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;ruby&quot;}">// Instance 1: GMT WRITE
Person(
  longDate           = 1507751058820, 
  instantDate        = 2017-10-11T19:44:18.820418Z, 
  localDateTime      = 2017-10-11T19:44:18.969400, 
  offsetDateTime     = 2017-10-11T19:44:18.969438Z, 
  offsetDateTimeZone = 2017-10-11T19:44:18.969455Z
)
-- Instance 2: GMT+01:00 READ
Person(
  longDate           = 1507751058820, // correct
  instantDate        = 2017-10-11T19:44:18.820418Z, // now correct
  localDateTime      = 2017-10-11T20:44:18.969400,  // now also correct
  offsetDateTime     = 2017-10-11T20:44:18.969438+01:00, // now also correct
  offsetDateTimeZone = 2017-10-11T20:44:18.969455+01:00  // now also correct
)</pre></div>



<p>Now all dates are okay, if all our instances really work with the same JDBC session time zone.</p>



<h2 class="wp-block-heading">Avoid any time Zones in the business logic</h2>



<p>Mathematically the time zone isn&#8217;t relevant assuming any date in the backend is saved and transferred as UTC date time with now time zone at all.</p>



<div class="bs-callout bs-callout-info"><strong>As a rule of thumb:</strong> The simplest and safest method is to remove any time zone from the backend code. If we have a time zone in the code, we need it in the DB too.</div>



<p>Save the date time as UTC <code>long</code>, which is anyway the simplest method to compare dates to each other. (<em>Means as milliseconds, between the current time and midnight, January 1, 1970 UTC.</em>)</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">class Pojo {
  String foo;
  long dateTimeInMs = System.currentTimeMillis();
  long dateTimeInS = Instant.now().getEpochSecond();
}</pre></div>



<h2 class="wp-block-heading">Even in the DB using a long / NUMBER has several advantages</h2>



<ul class="wp-block-list"><li>Any direct usage of the DB itself is hindered</li><li>Date Time conversion by the JDBC driver is avoided</li><li>A time zone cannot be introduced or assumed</li><li>Clear also in external APIs using the Service</li><li>The precision can be selected based on the domain, in most use cases seconds is enough</li></ul>



<h2 class="wp-block-heading">Instant in Java 8 or later</h2>



<p>A valid alternative solution is to use Java <code>Instant</code>, which is in the end a wrapped UTC <code>long</code> and provides some further methods. It can be saved either as <code>NUMBER</code> or <code>TIMESTAMP</code> in the DB. But as soon as a real date type is used we have also to provide a time zone information in our JDBC URL e.g.:</p>



<ul class="wp-block-list"><li>e.g. using <code>serverTimezone=UTC</code></li><li>or <code>spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code></li></ul>



<h2 class="wp-block-heading">OffsetDateTime</h2>



<p>Many projects have chosen  an offset date time type to avoid any issues with the time zone. The problem is, that it usually doesn&#8217;t address the issue if for some reason the time zone of your system changes.</p>



<h3 class="wp-block-heading">Running save and load in different Time zones</h3>



<h2 class="wp-block-heading">Avoid Local Date Time</h2>



<p>Local date time tends to surprise the people each time, even if it states, that the e.g. <code>LocalDate</code> represents a date without a time zone, same applies to <code>LocalDateTime</code>, it uses behind the scenes the system time zone:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">    public static LocalDate now() {
        return now(Clock.systemDefaultZone());
    }

    public static LocalDateTime now() {
        return now(Clock.systemDefaultZone());
    }</pre></div>



<p>Which leads to the problem, that we have a time which was build using a time zone which is lost as soon as we have only the object. The value depends on the OS time zone which leads to interesting problems in a hosted server environment. Imagine e.g. that one node of the cluster has a different time zone because of some configuration issue in the infrastructure.</p>



<p>Having just the following simple test let us review the results, take in mind that my local time zone would be GMT+2 but currently we have wintertime, GMT+1.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">    @ParameterizedTest
    @ValueSource(strings = {&quot;&quot;, &quot;GMT+1&quot;, &quot;GMT+6&quot;})
    void test(String timeZone) {
        if (timeZone.length() != 0) {
            TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
        }
        System.out.println(java.util.TimeZone.getDefault());
        System.out.println(&quot;Instant:        &quot; + Instant.now());
        System.out.println(&quot;LocalDateTime:  &quot; + LocalDateTime.now());
        System.out.println(&quot;OffsetDateTime: &quot; + OffsetDateTime.now());
    }</pre></div>



<p>Already this very simple example generates here with <code>LocalDateTime</code> three different results. Even if the offset looks correct.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;lua&quot;,&quot;mime&quot;:&quot;text/x-lua&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Lua&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;lua&quot;}">ZoneInfo[id=&quot;Europe/Berlin&quot;,offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
Instant:        2017-10-10T09:54:45.370020Z
LocalDateTime:  2017-10-10T11:54:45.379338
OffsetDateTime: 2017-10-10T11:54:45.380626+02:00
ZoneInfo[id=&quot;GMT+01:00&quot;,offset=3600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Instant:        2017-10-10T09:54:45.394314Z
LocalDateTime:  2017-10-10T10:54:45.394416
OffsetDateTime: 2021-10-10T10:54:45.394455+01:00
ZoneInfo[id=&quot;GMT+06:00&quot;,offset=21600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Instant:        2017-10-10T09:54:45.397258Z
LocalDateTime:  2017-10-10T15:54:45.397353
OffsetDateTime: 2017-10-10T15:54:45.397406+06:00
ZoneInfo[id=&quot;GMT&quot;,offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Instant:        2017-10-10T09:54:45.399973Z
LocalDateTime:  2017-10-10T09:54:45.400040
OffsetDateTime: 2017-10-10T09:54:45.400076Z</pre></div>



<p>If the code base is already based on local date times and a refactoring isn&#8217;t possible the following actions could be applied to reduce the risk of moving dates and times:</p>



<ul class="wp-block-list"><li>Check the current time zone in production, as all dates may require an update</li><li>Change all dates to UTC/ GMT+0 in the DB</li><li>Apply a fixed time zone to the JVM: <code>-Duser.timezone=UTC</code></li><li>Apply a fixed time zone in the JDBC URL (since hibernate 5.2 a hibernate property is available)</li><li>Verify that the date isn&#8217;t displayed to the user, or a time zone conversion is applied</li></ul>



<h2 class="wp-block-heading">Links</h2>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm" target="_blank">https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm</a></li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2017/10/dates-datetime-timezone-and-the-db/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>JavaScript Module Pattern or Just Private Variables</title>
		<link>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/</link>
					<comments>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 11 Jul 2015 14:14:01 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[Module Pattern]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=62</guid>

					<description><![CDATA[JavaScript is a wonderful language to get thinks fundamentally wrong from the start. As so where are many patters around to help us to avoid some of these challenges ;-). The module pattern is one of the most known and used. It helps us to create private variables or better to avoid side effects in&#8230;]]></description>
										<content:encoded><![CDATA[
<p>JavaScript is a wonderful language to get thinks fundamentally wrong from the start. As so where are many patters around to help us to avoid some of these challenges ;-).</p>



<p>The module pattern is one of the most known and used. It helps us to create private variables or better to avoid side effects in a larger JS application between the different JS files we load or frameworks we use.</p>



<h2 class="wp-block-heading">The problem</h2>



<p>Overall the problem is that in JavaScript everything is more or less public. Currently, most frameworks register their name in the Global space, also known as the window Object. You know them as <code>angular</code> or just <code>$</code> or maybe even as <code>Y</code>. </p>



<p>Imagine the following code (<a rel="noreferrer noopener" href="http://output.jsbin.com/muxekusezi/1" target="_blank">jsBin</a>): </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// first JS file
var CLASS_NAME = &quot;A1&quot;;
function A1() {}
A1.prototype.sayHallo = function() {
  $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
};

// second class in a different JS file
var CLASS_NAME = &quot;B1&quot;;
function B1() {}
B1.prototype.sayHallo = function() {
  $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
};

// some code
$('#cmdA1').click(function() {
  new A1().sayHallo();
});
$('#cmdB1').click(function() {
  new B1().sayHallo();
});</pre></div>



<p>It doesn&#8217;t matter which button you press the result will always be <code>B1</code>&nbsp;because we have overwritten the value in <code>CLASS_NAME</code> in the second part.</p>



<p>Even if this sample is somehow of course constructed, this problem can easily happen in a larger JS application. We must take this into account an protect ourself.</p>



<h2 class="wp-block-heading"><strong>The solution</strong></h2>



<p>The solution is pretty straight forward. We just wrap our class definition into an anonymous function. This does not only protect us but it allows us to create really private variables in JS which can&#8217;t be overwritten from outside &#8212; we can protect the access to them with functions.</p>



<p><a href="http://output.jsbin.com/fegexecisu/2" target="_blank" rel="noreferrer noopener">jsBin again</a></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;JavaScript&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;js&quot;}">// first JS file
MyGlobal = {};
(function($) {
  var CLASS_NAME = &quot;A1&quot;;
  function A1() {}
  A1.prototype.sayHallo = function() {
    $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
  };
  MyGlobal.A1 = A1;
})(window.$); // pass any global scope

// second class in a different JS file
(function($) {
  var CLASS_NAME = &quot;B1&quot;;
  function B1() {}
  B1.prototype.sayHallo = function() {
    $('#out').html(CLASS_NAME + &quot;: says hallo!&quot;);
  };
  MyGlobal.B1 = B1;
})(window.$);

// some code
$('#cmdA1').click(function() {
  new MyGlobal.A1().sayHallo();
});
$('#cmdB1').click(function() {
  new MyGlobal.B1().sayHallo();
});</pre></div>



<h2 class="wp-block-heading"><strong>What have we learned?</strong> </h2>



<ul class="wp-block-list"><li>In JavaScript, the best practice is to wrap our code into anonymous functions</li><li>Define one global scope variable which we use to register all our classes (here MyGlobal)</li><li>Anonymous function also allow us to create private/ protected variables</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2015/07/javascript-module-pattern-or-just-private-variables/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Strong IDs</title>
		<link>https://sterl.org/2015/06/pattern-strong-id/</link>
					<comments>https://sterl.org/2015/06/pattern-strong-id/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 13 Jun 2015 11:01:24 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Pattern & Best Practice]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[id]]></category>
		<category><![CDATA[Strong ID]]></category>
		<category><![CDATA[StrongID]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=36</guid>

					<description><![CDATA[In some projects you may encounter the so called &#8222;strong id pattern&#8220;. What is it? Strong IDs are simply wrapped primitive or simple types into classes. Just remember what we did in Java before the Enum come around. We had just Strings or Numbers in the code which we used to assign well known values&#8230;]]></description>
										<content:encoded><![CDATA[<p>In some projects you may encounter the so called &#8222;strong id pattern&#8220;.</p>
<h2>What is it?</h2>
<p>Strong IDs are simply wrapped primitive or simple types into classes. Just remember what we did in Java before the <code>Enum</code> come around. We had just Strings or Numbers in the code which we used to assign well known values to specific objects. In some projects these Strings has already been wrapped into classes. Now with <code>Enums</code> this is mostly obsolete. But for Ids we can still apply this pattern.</p>
<p>Imagine the following classes:</p>
<pre class="lang:java decode:true" title="Simple Class">class Office {
  String id;
  String name;
}

class Person {
  String id;
  String name;
}
// we could use any string we want, even the ID from the office
interface PersonService {
  Person getById(String id);
}</pre>
<p>Both classes have an <span style="color: #ffffff; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;"><span style="font-size: 14px; line-height: 21px; background-color: #333333;">id</span></span>, simply just as a <code>String</code>. Keeping just these ids in hand you cannot tell if it is a <code>Person Id</code> or the <code>Office Id</code>. To make it more obvious we could change the code too:</p>
<pre class="lang:default decode:true" title="Simple class with Strong ID">final class OfficeId {
  String value;
}
class Office {
  OfficeId id;
  String name;
}

final class PersonId {
  String value;
}
class Person {
  PersonId id;
  String name;
}
// we can now use the real type, compile time save
interface PersonService {
   Person getById(PersonId id);
}</pre>
<p>If you now have either the <code>OfficeId</code> or <code>PersonId</code> in hand, you cannot accidentally mix them up. You exactly know what you have and what it identifies.</p>
<p>Usually the ID classes are not mutable too.</p>
<h2>Advantages</h2>
<p>In larger projects you have many classes, it is easier to understand and keep different IDs in method signatures. That we use the right type in generic lists or method calls can be ensured now during compile time.</p>
<p>Also nice we can easyer change the type of ID, e.g. from <code>String</code> to <code>Long</code> or to a composite type.</p>
<p>If we move this sample to REST where we usually want to return a URI as an identifier to an object this pattern even gets more attractive. If we assume our IDs have been initially just simple Longs wrapped into a Strong ID we could change the value it a String and create URI / String which we return to the clients.</p>
<h2>Disadvantages</h2>
<p>Well no pro without a contra. Having strong ids in the system makes the handling sometimes awkward. E.g. if you serialize this to JSON you get:</p>
<pre class="lang:js decode:true ">// with strong ID
{ id: {value: "abc"}, name: "Main Office"}

// without strong id, or what you usually want
{ id: "abc", name: "Main Office"}</pre>
<p>Furthermore Hibernate nor simple bean serializer/ deserializer can handle well immutable classes. Overall we would need to add additional code to handle that. e.g. Hibernate custom types etc.</p>
<p><a href="https://github.com/sterlp/training/tree/master/jpa-hibernate/src/main/java/org/sterl/jpa/strong_id">Github JPA example</a></p>


<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Kompakt: JPA | Hibernate | eigene @Id Datentypen |  Strong ID Pattern" width="640" height="360" src="https://www.youtube.com/embed/wPiE4hF6Si0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2015/06/pattern-strong-id/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
