Mostrando las entradas con la etiqueta OOP. Mostrar todas las entradas
Mostrando las entradas con la etiqueta OOP. Mostrar todas las entradas

sábado, agosto 07, 2021

¿Monolitos? ¿Qué monolitos?

 Si atendemos a las definiciones de sus propios favorecedores, creo que se aboga por microservicios apoyándose en una entelequia que poco tiene que ver con el mundo real de las aplicaciones corrientes. Tomado de A Deep Dive Into Microservices vs. Monolith Architecture, por mencionar un caso que dice apoyarse en los estándares (aunque no menciona a Martin Fowler):

Monolith simply refers to one block containing all in one piece. According to Wikipedia, a monolithic application describes a single-tiered software application in which the user interface and data access code are combined into a single program from a single platform.

Y siguiendo su referencia a Wikipedia:

In software engineering, a monolithic application describes a single-tiered software application in which the user interface and data access code are combined into a single program from a single platform.

A monolithic application is self-contained and independent from other computing applications. The design philosophy is that the application is responsible not just for a particular task, but can perform every step needed to complete a particular function.[1] Today, some personal finance applications are monolithic in the sense that they help the user carry out a complete task, end to end, and are private data silos rather than parts of a larger system of applications that work together. Some word processors are monolithic applications.[2] These applications are sometimes associated with mainframe computers.

In software engineering, a monolithic application describes a software application that is designed without modularity.[citation needed] Modularity is desirable, in general, as it supports reuse of parts of the application logic and also facilitates maintenance by allowing repair or replacement of parts of the application without requiring wholesale replacement.

Modularity is achieved to various extents by different modularization approaches. Code-based modularity allows developers to reuse and repair parts of the application, but development tools are required to perform these maintenance functions (e.g. the application may need to be recompiled). Object-based modularity provides the application as a collection of separate executable files that may be independently maintained and replaced without redeploying the entire application (e.g. Microsoft "dll" files; Sun/UNIX "shared object" files).[citation needed] Some object messaging capabilities allow object-based applications to be distributed across multiple computers (e.g. Microsoft COM+). Service-oriented architectures use specific communication standards/protocols to communicate between modules.

In its original use, the term "monolithic" described enormous mainframe applications with no usable modularity.[citation needed] This, in combination with the rapid increase in computational power and therefore rapid increase in the complexity of the problems which could be tackled by software, resulted in unmaintainable systems and the "software crisis".

Es decir, si vamos a considerar "monolito" a una aplicación que en un solo ejecutable procesa los datos, define toda la lógica, y contiene la propia interfaz de comunicación con el mundo, probablemente haya que remontarse a 1970 o poco más (the term "monolithic" described enormous mainframe applications with no usable modularity).  Con seguridad, hace cuarenta años que ese paradigma no existe, salvo que incluyamos en él a las corrientes "apps" moviles. Como el propio artículo de Wikipedia menciona, simplemente la modularidad y la posibilidad de mantener una aplicación separada por responsabilidades de servicio existe no menos que desde los 80 del siglo pasado, y más atrás desde que lenguajes de alto nivel como el COBOL existen. Sólo un mal diseño, pésimo diseño, podría poner  todos los aspectos de una aplicación en un solo componente: podemos decir que existen otros modelos distintos que practican la modularidad y la separación de responsabilidades desde mucho antes de que se hablara de microservicios. 

Oponer Microservicios/Monolitos es sesgado y parcial. Otras arquitecturas/tecnologías se han desarrollado y perfeccionado para combatir los indudables perjuicios de un "monolito". Si vamos a la discusión del artículo en Wikipedia (siempre hay que ir a la historia y a la discusión), los observadores críticos del artículo así lo hacen ver:

The article lacks proper references and has a down view of the concept instead of explaining what it is. The article is also very focused on explaining what modules are and why they are good, getting out of the topic. I would go a step forward and say that this article has wrong information. 

El artículo de Wikipedia habla de "data silos". Este es un punto muy interesante y hay que verlo por separado, en otro momento. 

Pero establecer un paradigma opuesto que sea la panacea, requeriría un poco más de trabajo. Podemos decir que contra esa figura de "monolito" se ha trabajado durante treinta o cuarenta años (por ejemplo OOD/OOP), antes que se proclamara que los microservicios  son la solución.

 


sábado, junio 27, 2015

Una guía de trabajo con Plex

George Jeffcock, en su sitio relacionado con sus Stella Tools, dedica algunos párrafos a recomendar buenas prácticas en el uso de Plex. Coincidiendo con las guías de enseñanza usuales en Plex, George recomienda:
STOP Coding - Start Architecting
Plex development is essentially a three-step process involving Data Modeling, Pattern Matching and Customization. There are no shortcuts, each step must be adhered to achieve the goals. Missing a step may seemingly achieve a short term solution but in the medium and long term the solution will surely decay far quicker than it should have. The mindset required to use plex effectively is one of:
  • Object oriented approach to application design to eliminate the need to code repeatable elements of applications
  • Working at a level of abstraction rather than at the ‘nuts and bolts’ level, probably just saying the first point again but this can’t be over stressed the importance to think this way instead of coding procedural code line after line
  • Model-based and pattern-based approach to increased application quality and flexibility
  • Multiple inheritance is a key part of the way applications are developed in CA Plex therefore leveraging the full value of a site’s existing patterns
  • Encapsulation so that function interfaces contain only the attributes pertinent to the use of the function
  • An application should be separated into separate layers/tiers, Functionality should be strictly separated into data access, business logic and presentation logic, as this promotes the consistency of the application as well as the possibilities to reuse functionality.
La primera regla que un nuevo desarrollador en Plex debe asumir, es que debe escribir la menor cantidad de código posible: olvidarse de escribir líneas de código, y pensar, pensar el modelo de datos y relaciones, luego estudiar cómo abstraer y explotar patrones existentes, y sólo luego escribir código, sólo lo que es estrictamente necesario. "Whenever there is a hard job to be done I assign it to a lazy man; he is sure to find an easy way of doing it"

martes, abril 07, 2015

Diez reglas para recordar (y seguir...)

Firmado por Javin Paul, un artículo que recuerda diez reglas importantes de orientación a objetos en el diseño con Java (10 Object Oriented Design Principles Java Programmer should know), que podríamos extender fácilmente a otros campos (y estoy pensando en Plex). Un pequeño decálogo, tan escueto que podríamos pegarlo en una pizarra frente a nuestros ojos, y que deberíamos repasar todos los días.
 DRY (Don't repeat yourself)
Our first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important  not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.

Encapsulate What Changes
Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.

Open Closed Design Principle
Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful SOLID design principle, which prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. By the way, Open Closed principle is "O" from SOLID acronym.

Single Responsibility Principle (SRP)
Single Responsibility Principle is another SOLID design principle, and represent  "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java  it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality,  which require another round of testing to avoid any surprise on production environment.

Dependency Injection or Inversion principle
Don't ask for dependency it will be provided to you by framework. This has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI framework is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that.There are multiple ways to  implemented Dependency injection like using  byte code instrumentation which some AOP (Aspect Oriented programming) framework like AspectJ does or by using proxies just like used in Spring. See this example of IOC and DI design pattern to learn more about this SOLID design principle. It represent "D" on SOLID acronym.

Favor Composition over Inheritance
Always favor composition over inheritance ,if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.

Liskov Substitution Principle (LSP)
According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent  "L" on SOLID acronym.

Interface Segregation principle (ISP)
Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement.

Programming for Interface not implementation
Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.

Delegation principle
Don't do all stuff  by yourself,  delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.
Y volviendo sobre la idea de su aplicabilidad en Plex, sin duda lo es. En algunos casos fácilmente entendible, (Favor Composition over Inheritance, Encapsulate What Changes, DRY,  Favor Composition over Inheritance) y en otros casos, después de luchar contra la vía fácil de hacer las cosas (Programming for Interface not implementation). Solo veo difícil implementar Dependency Injection. Y cuando me refiero a aplicabilidad, lo hago a nivel del modelo, no a nivel del código generado, donde su aplicabilidad está asegurada.
Plex, como otros productos, admite distintas interpretaciones, distintas formas de desarrollar. Aplicar principios de OOD permite explotarlo en forma más productiva, potenciando sus características. Luchar por no usar una hoja de ruta rutinaria favorece resultados consistentes y duraderos.

domingo, febrero 03, 2013

Wikipedia y la programación

Parece ser que, en Wikipedia, no hemos logrado el respaldo de los mejores escritores en algunas áreas de programación. En OOP, desde el mismo concepto hasta varios de sus elementos constitutivos, aparecen débilmente definidos: encapsulamiento, herencia, polimorfismo, interfaz, y varios otros. Quizá se podría decir que más interesante que el artículo en sí, es, en cada caso, la discusión entre los redactores y observadores. Creo que sería más conveniente la creación de un grupo de trabajo con respaldo en buenos conocimientos, que discutiera un enfoque general común, y mantuviera un plan de redacción unificado y consistente, que abarque el problema con mejor sustento teórico, y un plan homogéneo de casos y ejemplos. No parece recomendable en varios casos, acudir a Wikipedia en busca de una respuesta. En este caso, es preferible la versión inglesa.

jueves, noviembre 17, 2011

Críticas a OOP

James Hague, programador funcional (o por lo menos por un tiempo), interesado en Python y Erlang, hablando del primero, hace una referencia a la programación orientada a objetos, puntualizando lo que lo aparta de oop:
 (Don't Distract New Programmers with OOP) 
[...] The shift from procedural to OO brings with it a shift from thinking about problems and solutions to thinking about architecture. That's easy to see just by comparing a procedural Python program with an object-oriented one. The latter is almost always longer, full of extra interface and indentation and annotations. The temptation is to start moving trivial bits of code into classes and adding all these little methods and anticipating methods that aren't needed yet but might be someday.

When you're trying to help someone learn how to go from a problem statement to working code, the last thing you want is to get them sidetracked by faux-engineering busywork. Some people are going to run with those scraps of OO knowledge and build crazy class hierarchies and end up not as focused on on what they should be learning. Other people are going to lose interest because there's a layer of extra nonsense that makes programming even more cumbersome.

At some point, yes, you'll need to discuss how to create objects in Python, but resist for as long as you can. 
Esta nota de Hague es de marzo de este año. Por casualidad o no, ese mes otro entusiasta de la programación funcional desacredita totalmente oop. Y nada menos que en un curso introductorio de Carnegie Mellon.
Sería muy interesante conocer un balance del curso terminado.

domingo, octubre 16, 2011

Una opinión sobre el valor de Java

En el curso de una discusión sobre Dart en Google+, Rafael Chaves da una interesante visión sobre Java:
"Java was not innovative at the time, and did kill many OO languages initiatives"

I am not sure Java killed other initiatives - I feel more like they were dead on arrival, at least from a market suitability PoV.

The non-technical aspects are just as important as technical merits. It does not matter how cool a language is, if it is not going to be supported by multiple vendors/platforms, if it evolves in a way that invalidates previous investments, if it is hard to learn for the average developer, if doesn't have proper support for a wide variety of application styles/domains, if is going to be hard to hire people. Getting that right is as critical as (or even more than) technical benefits.

Java got all those right, and that is why it succeeded. I don't think it is a lot about money. Sun could have poured twice as much money into it, but if they failed to recognize the importance of those aspects, it would have been a flop, or have limited success (see Microsoft .Net). But these days I wouldn't bet against similar success being attainable by an open source foundation with a strong community, without nearly the same level of financial backing, if they aimed for building for the mainstream and the long term like Sun did with Java.

As a developer, I want my investment in learning my next language to pay off for as long and across as many domains and technical architectures as possible. That is much more important than having the perfect feature set.
...y a propósito del valor de Dart, Angel "Java" López ha abierto una línea de discusión e información.

viernes, septiembre 26, 2008

(Thinking in Objects)

Henry Story, en su blog The Sun BabelFish, plantea un problema que mide los límites de la programación orientada a objetos, y la contrapone a las herramientas usuales en la Web Semantica. Con un ejemplo basado en el mundo del autismo, Story presenta un mundo de vistas personales, no de objetos reales. Probablemente el ejemplo usado no fue muy afortunado, particularmente en cómo implementarlo en OOP y en su contrapartida con RDF. Henry fue muy criticado, y en general con acierto, tanto en su expresión del problema en OOP como en la correlación parcial entre ambos ejemplos. Sin embargo, la presentación del problema es estimulante para medir OOP y sus límites:

In order to be able to have a mental theory one needs to be able to understand that other people may have a different view of the world. On a narrow three dimensional understanding of 'view', this reveals itself in that people at different locations in a room will see different things. One person may be able to see a cat behind a tree that will be hidden to another. In some sense though these two views can easily be merged into a coherent description. They are not contradictory. But we can do the same in higher dimensions. We can think of people as believing themselves to be in one of a number of possible worlds. Sally believes she is in a world where the ball is in the basket, whereas Ann believes she is in a world where the ball is in the box. Here the worlds are contradictory. They cannot both be true of the actual world.

To be able to make this type of statement one has to be able to do at least the following things:

  • Speak of ways the world could be
  • Refer to objects across these worlds
  • Compare these worlds
Henry propone un ejemplo (imperfecto y criticado por varios de sus lectores):

Let us illustrate this with a simple example. Let us see how one could naively program the puppet play in Java. Let us first create the objects we will need:

Person sally = new Person("Sally");
Person ann = new Person("Ann");
Container basket = new Container("Basket");
Container box = new Container("Box");
Ball ball = new Ball("b1");
Container room = new Container("Room");
So far so good. We have all the objects. We can easily imagine code like the following to add the ball into the basket, and the basket into the room.
basket.add(ball);
room.add(basket);
Perhaps we have methods whereby the objects can ask what their container is. This would be useful for writing code to make sure that a thing could not be in two different places at once - in the basket and in the box, unless the basket was in the box.
Container c = ball.getImmediateContainer();
Assert.true(c == basket);
try {
box.add(ball)
Assert.fail();
} catch (InTwoPlacesException e) {
}
All that is going to be tedious coding, full of complicated issues of their own, but it's the usual stuff. Now what about the beliefs of Sally and Ann? How do we specify those? Perhaps we can think of sally and ann as being small databases of objects they are conscious of. Then one could just add them like this:
sally.consciousOf(basket,box,ball);
ann.consciousOf(basket,box,ball);
But the problem should be obvious now. If we move the ball from the basket to the box, the state of the objects in sally and ann's database will be exactly the same! After all they are the same objects!
basket.remove(ball);
box.add(ball);
Ball sb = sally.get(Ball.class,"b1");
Assert.true(box.contains(sb));
//that is because
Ball ab = ann.get(Ball.class,"b1");
Assert.true(ab==sb);
There is really no way to change the state of the ball for one person and not for the other,... unless perhaps we give both people different objects. This means that for each person we would have to make a copy of all the objects that they could think of. But then we would have a completely different problem: namely deciding when these two objects were the same. For it is usually understood that the equality of two objects depends on their state. So one usually would not think that an physical object could be the same if it was in two different physical places. Certainly if we had a ball b1 in a box, and another ball b2 in a basket, then what on earth would allow us to say we were speaking of the same ball? Perhaps their name, if it we could guarantee that we had unique names for things. But we would still have some pretty odd things going on then, we would have objects that would somehow be equal, but would be in completely different states! And this is just the beginning of our problems. Just think of the dangers involved here in taking an object from ann's belief database, and how easy it would be to by mistake allow it to be added to sally's belief store.
Henry aboga por el uso de RDF (Resource Description Framework) como herramienta capaz de expresar adecuadamente las distintas vistas de un problema, en un universo de vistas en lugar de objetos. Pero sin duda, esto merece otro espacio.
De los comentarios que siguen al artículo, particularmente abre un poco más el que hiciera Ryan, y la respuesta de Henry
Ryan:
I really like your analysis of OOP and it's relation to autism. I have never thought of it in such a way, but it does make a lot of sense (when I am able to remove my preconceptions). However, why is autism bad in this scenario (if you are even implying it)? I can understand that if our perspective is not an omniscient one then this can fail us. Would you please provide a applied example of the problem at hand with relation to your point on Semantic Web? Thanks a lot!
Henry:

Thanks for asking Ryan. Yes there are a lot of examples. The following article "Extending the Representational State Transfer (REST) Architectural Style for Decentralized Systems" which you can find here
http://portal.acm.org/citation.cfm?id=999447
makes the point about how the distance between the source of a message and the recipient of a message makes perfect immediate communication impossible, if you think of it as resources having the same access to an object. But if you think of it as message passing then you can do some interesting things... Ok I read that quickly, but that is what made me decide to write this article out today.

In the AddressBook I am writing, which I describe in an audio slide cast here:
http://blogs.sun.com/bblfish/entry/building_secure_and_distributed_social
I need to get data from distributed places around the web. This can only be done seriously if you accept that there will be spammers, liars, and just simply wrong data out there. So though you may by default merge data, you may want to make it easy to unmerge it too. I wrote about that in more detail here:
http://blogs.sun.com/bblfish/entry/beatnik_change_your_mind

As I said, if you are writing tools, that you can think of as physical, mechanical objects, that don't have to have points of view on the universe, say if you are writing a web browser, a calculator, or some such thing, then this is not important. But as soon as you want to mesh the information on the web, you will need to take the opinion of others into account. We are fast moving to a world where this is going to become more and more important.

In any case it is good to know the limitations of your tools. :-)

En el mismo sentido, apunta Benjamin Damman:

Hmmmm. Parts of your intriguing article made me think of erlang.

"When one fetches information from a remote server one just has to take into account the fact that the server's view of the world may be different and incompatible in some respects with one's own. One cannot in an open world just assume that every body agrees with everything. One is forced to develop languages that enable a theory of mind. A lot of failures in distributed programming can probably be traced down to working with tools that don't."

Erlang was created for coding highly fault-tolerant (and distributed) systems; characteristics stemming this fact might make it an example of a language that 'enables a theory of mind.'

http://erlang.org/white_paper.html

Un papel sugerente de ideas, mas allá de los puntos observados por su crítica.