Skip to main content

One post tagged with "molokotech"

View All Tags

Intro

· One min read
Axel Berlot
Java developer @ Opendev Pro

banner

Sección de reflexiónes

Como les comenté en mi presentación, soy un programador que se enamoró de Java por donde lo veas, es sin duda mi lenguaje predilecto, sin embargo en esta sección la voy a dejar a reflexiones de la vida laboral, compartir situaciones que otros colegas pueden haber vivido, están viviendo o vivirán, ya que dentro de mis recién cumplidos 10 diez años en el mundo de sistemas fue como una rollercoster de sistuaciones vividas relacionadas al trabajo ya que tuve la suerte o maldición de mutar en mis puestos de trabajo a diferentes roles con diferentes responsabilidades, he sido felicitado, criticado y hasta como a la mayoría de los individuos en sus inicios laborales desvinculado, dicho esto creo que la experiencia me habilita a realizar determinados descargos o reflexiones sobre temas relacionados al mundo donde vivimos.
Podría estar escribiendo esto en X.com o linkedin.com, Medium.com, etc, sin embargo elijo hacerlo en un blog absolutamente propio donde pueda diseñar los estilos, decir lo que quiero y no tener limitaciones de ningún tipo.

Bienvenidos a mi sillón.

="text-align:justify">Un microservicio conceptualmente es una aplicación que tiene una función determinada y que sirve datos a traves de alguna API del algún tipo, es un concepto de desarrollo que puede tener variantes dependiendo cómo se lo use, pero lo más importante es que cumpla con el concepto de responsabilidad única más allá del tamaño ya que un microservicio puede ser chico, mediano o grande ya que la palabra micro es sólo un concepto abstracto que atomiza responsabilidades en sistemas distribuidos.
Microservicio
Este ejemplo sólo muestra una aplicación que para poder llamarla microservicio debe cumplir una responsabilidad única, si la misma tiene una función particular puede llamarse microservicio, sino sólo es una aplicación que expone servicios mediante algún tipo API por ejemplo la más común REST.

microservice1

Ecosistema de microservicios
Un ecosistema de microservicios es un conjunto de aplicaciones distribuidas con diferentes responsabilidades que funcionan en forma autónoma y que su forma de comunicación es mediante algún tipo de API, los ecosistemas de microservicios habitualmente son un proyecto a nivel empresarial para responder ante una demanda de aplicaciones que consumirán diferentes orígenes de información.

microservice2

Monolito de microservicios distribuidos
En sus inicios los microservicios se utilizaron para tener una responsabilidad única y muy importante poder funcionar autónomamente sin tener acoplamiento con otras aplicaciones lo que le daba inependencia de funcionamiento, esto hoy en día está siendo sobreescrito en diferentes ecosistemas que se desarrollan con dependencias entre microservicios acoplando el funcionamiento de uno con la existencia de otro en comunicaciones server to server, aunque este escenario está tomando más auge y adopato su uso en gran cantidad de empresas es el más riesgoso de todos los escenarios nombrados anteriormente, ya que acopla el funcionamiento de aplicaciones con otras, lo cual necesita una orquestación particular entre células que mantengan actualizadas aplicaciones. Un Monolito distribuido es una práctica común hoy en díaen el mundo empresarial, la cual puede de ser mejor monitoreada con aplicaciones como Istio, service Mesh u Observabilidad en trazas, sin embargo si no se toman estas medidas de monitoreo el control del mismo es caótico ya que a diferencia de los monolitos estandar acá son aplicaciones están distribuidas en diferentes orígenes pero son dependientes unas de otras.

microservice3

Microservicios distribuidos en cadena
Existen esquemas más maduros de un monolito distribuido donde en realidad es una cadena de microservicios que ejecutan un resultado final, es en definitiva un monolito con pasos definidos y una distribución de la carga controlada, por ejemplo es conocido el esquema de microservicios en cadena que tiene Netflix, con aplicaciones distribuidas que tienen diversas funcionalidades para obtener un resultado, la comunicación entre las mismas puede ser por HTTP, por TCP u otro tipo, lo importante de definir acá es que éstas arquitecturas demandan un mantenimiento y una gestión diferente ya que la interoperabilidad entre las aplicaciones es el core de su funcionamiento.

microservice3

Bio

· 3 min read
Axel Berlot
Java developer @ Opendev Pro

banner

Sobre mi

Me presento, mi nombre es Axel, cumplo el rol de arquitecto de software en una reconocida Software Factory de Argentina, comencé mis primeros pasos en el mundo del desarrollo allá por el 2014 de software con PHP y HTML,
thumb
sin embargo la curiosidad de saber me empujó a aprender otros lenguajes hasta que conocí Java, sin duda mi lenguaje predilecto. Java me permitió crear aplicaciones desktop con Swing y JavaFX muchos años atrás cuando algunos pocos todavía demandaban este tipo de soluciones, con el tiempo los requerimientos fueron avanzando y el romanticismo por ese tipo de aplicaciones fue desapareciendo hasta caer en la realidad de las aplicaciones web, este fue un camino de ida, que pasó por dos grandes etapas, la primera del mundo monolítico con aplicaciones integradas por completo en un core y la segunda hasta hoy orientadas a microservicios.
Como profesional del código no me cierro a ningún lenguaje pero siento y quiero seguir especializandome en el lenguaje Java, uno de mis objetivos es completar certificaciones directas de Oracle, las cuales cuentan con un nivel de prestigio muy alto ya que tienen una dificultad poco común.
En mi trabajo actual pasé por varios roles, desde desarrollador en su mayoría de lenguaje Java, Angular y un poco de NodeJS, pasé por puestos de líder técnico de una o más células hasta el día de hoy que cumplo el rol de arquitecto de software, realmente me gusta lo que hago y le dedico tiempo y esfuerzo, utilizando mis tiempos libres para seguir capacitándome en nuevas tecnologías para que la aplicación que creemos el día de mañana sea mejor y más performante que la de hoy.

Gracias por leer y bienvendio a mi Blog!


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Greettings {

public static void main(String[] args) throws Exception {
ScheduledExecutorService sched = Executors.newSingleThreadScheduledExecutor();
sched.scheduleAtFixedRate(() -> System.out.println("Wellcome to my blog"), 2, 2, TimeUnit.SECONDS);
}

}

tyle="color:#393A34">() {
Streamable.privatEstaticMethod("678");
}

// Belongs to the class and must've a body too
private static void privatEstaticMethod(String numbers) {
numbers = numbers + "456"; // this will compile OK!!!
System.out.println(Streamable.numbers);
}

}
tip

Desde Java 8 en adelante se habilitó el uso de expresiones lambda ampliamente utilizadas en programación funcional, la que mejora notablemente la lectura del código y limita la cantidad de líneas de código haciendo una lectura de los códigos fuente más legible.

Autoboxing and Unboxing

· 3 min read
Axel Berlot
Java developer @ Opendev Pro

banner

Autoboxing is the conversion from a primitive value to a Wrapper Classes. It is a background operation outside from de programmer control, that transform primitive types creating objects without explicity creating in the code.

The simplest way:
Integer i = 1;

From behind the scenes compiler run new Integer(1) although the IDE says it's deprecated when you type it, the intention is to write cleaner code.

It runs when:

  1. Passed as a parameter to a method that expects a value of the corresponding object wrapper type.
  2. Assigned to a variable of the corresponding object wrapper type.
package com.molokotech.models;

public class Autoboxing {

// Assigned to a variable
void number() {
int number = 100;
Integer num = number; // The compiler converts from int to new Integer
}

// Passed as a parameter
void iterate() {
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i)
li.add(i); // The compiler converts from int to new Integer
}

// Simplest examples
void autoboxing() {
Character c = 'c'; // char to new Character
Integer i = 1; // int to new Integer
}

/* remainder (%) and unary plus (+=) operators does'nt works with:
Integer
Byte
Short
Only primitive types are allowed for this operators so from behind the scenes always invokes i.intValue() */
public int sum(List<Byte> li) {
int sum = 0;
for (Byte i : li)
if (i % 2 == 0)
sum += i;
return sum;
}

}

autoboxing

Unboxing is the conversion from an Object to a primitive value.

The simplest way:
Integer number = 100; int num = number;

  1. Passed as a parameter to a method that expects a value of the corresponding primitive type.
  2. Assigned to a variable of the corresponding primitive type.
package com.molokotech.models;

public class Unboxing {

// Assigned to a variable
void number() {
Integer number = 100;
int num = number; // The compiler convertes from Integer to int
}

// Passed as a parameter
void iterate() {
int[] li = new int[50];
for (Integer i = 1; i < 50; i += 2)
li[i] = i;
}

}

unboxing

Java compiler run the background operation with for autoboxing and unboxing on the corresponding wrapper clases:

Primitive typeWrapper class
booleanBoolean
byteByte
charCharacter
floatFloat
intInteger
longLong
shortShort
doubleDouble

Access modifiers

· 3 min read
Axel Berlot
Java developer @ Opendev Pro

banner

Access modifiers are implemented in java with four levels of abtraction.

Improves:

They are aplicable to:

  1. Classes → public | default
  2. Interfaces → public | default
  3. Constructors → public | default | protected | private
  4. Class member attributes and methods → public | default | protected | private
  5. Interface member attributes and methods → public | private

Level of visibility:

Defaultrefers at no reserve keyword just, it isn't the keyword of the example bellow because this refers to the type of member method

Classes and Interfaces could be public or default (no keyword).

Interfaces cannot have members with default or protected access modifiers, please remember that the default modifier it's not the keyword.

Real life example for access modifiers in an interface:

package com.molokotech.interfaces;

// Accesible from any package
public interface Loggueable {
void log(); // implicitly public by default write public does not affect

// private access modifier allowed but should have body
private String colorConsole(String color) {
switch(color) {
case "yellow":
return "WARN";
case "red":
return "ERROR";
case "blue":
return "INFO";
default:
return "INFO";
}
};

/* default methods cannot be private are always public or implicity public
every instance implementation should be access to it */
default void labelColor(String color) {
colorConsole(color);
}
}

// Accesible with in the same package
interface AnotherLoggeable {

}

Member attributes and methods on the class can carry all types of modifiers.

public class AccessModifiers {

public int n1;
protected int n2;
int n3;
private int n4; // accesible only somewhere inside the class

public static void main(String[] args) {
System.out.println("HOLA");
}

public AccessModifiers() {

}
}

class Protected {
protected Protected() {
new Private(); // this NOT COMPILE at all! cannot access to the constructor outside the class
}

}

class Default {
Default() {
new Protected();
}
}

class Private {
private Private() {
new Default();
}
}

It is important to note that some modifiers affects the overriding behavor.

Data Types

· 5 min read
Axel Berlot
Java developer @ Opendev Pro

banner

sandbox.molokotech.com are powered by the Molokotech.

Java has an strong dependency with data types, it is important to understand how they works and how to use it.

Have you ever tougth why there are so many data types from different sizes? it's really easy to explain, just because when Java was created sitting on 1995 and years later, the devices were Java could installed were pretty small in memory, so the aproach to used only data types that reserves less memory was important.

Today no one is concerned by this because your phone today is faster and bigger about memory speaking than your computers.

Today it's not a problem if you choose to use a byte or an int because it does'nt have side effects on the devices.

Data Types in Java.

package com.molokotech.models;

public class DataTypes {
private int num = 1; // Integer wrapper Class
private boolean isBigger = true; // Boolean wrapper Class
private char ch = 'j'; // Character wrapper Class
private float f = 100; // Float wrapper Class cast needed 100f/100F
private long l = 5000; // Long wrapper Class cast needed 5000l/5000L
private short sh = 1234; // Short wrapper Class
private byte b = 0; // Byte wrapper Class

// private vars can access to methods from the same class
private void getDataType() {
System.out.println("primitive type " + this.num + " in Java is the default for all non decimal numbers");
System.out.println("primitive type " + this.isBigger + " default value is false");
System.out.println("primitive type " + this.ch + " should be rounded by simple quotes default value 0 or u0000, character/letter");
System.out.println("primitive type " + this.f + " it's used by default like int default value 0.0");
System.out.println("primitive type " + this.l);
System.out.println("primitive type " + this.sh);
System.out.println("primitive type " + this.b + " values from -128/127");
}

// getDataType() should be called only from this class
public static void main(String[] args) {
new DataTypes().getDataType();
}
}

result

Wrapper classes Float and Long shoud be casted when declared until it reference another variable, in this momment compile apply autoboxing strategy.

package com.molokotech.models;

public class Cast {

private float f = 100; // Float wrapper Class cast needed 100f/100F
private long l = 5000; // Long wrapper Class cast needed 5000l/5000L

private void doCast() {
Float sh = 123f; // must be casted -> Float sh = 123; not compile!!
Float shRef = this.f; // Autoboxing when ref another variable not casting needed

Long l = 123l; // must be casted -> Long l = 123; not compile!!
Long lref = this.l; // Autoboxing when ref another variable not casting needed
}

}

There three rules:

  1. Every number data-types non-decimal is treated as an int always unless it is explicitly cast.
  2. Every number data-types decimal es treated as an double always unless it is explicitly cast.
  3. Cannot do reference from a smaller data-type to a bigger data-type, because it does'nt fit, unless it is casted, in that case the value will try to fit passing maximun values.

The next image it's not absolute and is just note the different sizes between data types in a graphical way.

result

This code has some COMPILATION PROBLEMS related to bigger data-types trying to fit in smaller or incompatible data-types and other valid code you should copy into your IDE and make an analize it.


package com.molokotech.utils;

public class ReferenceMemory {

void referenceMemoryPoints() {
int num1 = 1000;
Integer num2 = num1; // autoboxing compile

byte num3 = 123;
Integer num4 = num3; // compiler knows that a byte is not an Integer -> not compile

byte num5 = 123;
int num6 = num5; // num5 primitive treated as an int, fit as an int -> compile

short num7 = 1234;
int num8 = num7; // num6 primitive treated as an int, fit as an int -> compile

int num9 = 123;
byte num10 = num9; // num9 does'nt fit in a byte because is bigger unless be casted -> not compile

int num11 = 123;
byte num12 = (byte) num11; // num11 does'nt fit in a byte because is bigger but is explicitly casted -> compile

long num13 = 12000;
Integer num14 = num13; // compiler knows that a long is not an Integer -> not compile

long num15 = 13000;
Integer num16 = (int) num13; // long is not an Integer but just casted -> compile

long num17 = 900000000033333l;
int num18 = num17; // long cannot fit into an Integer -> not compile

long num19 = 900000000033333l;
int num20 = (int) num19; // cannot fit but cast exced limits of the datatype -> compile

int num21 = 2000;
byte num22 = (byte) num21;
System.out.println(num22); // cannot fit but cast exced limits of the datatype -> compile
}

}

Viewing the results in the IDE

result

If we comment the compilation problems and run the program we see that prints a negative number even if we assign a positive number, this is because it reach out the max size of data-type and force it to assign with the cast, so it tries to fit anyway passing the limits.

max