Copy/Paste Is For Word Software Construction and more

Web Name: Copy/Paste Is For Word Software Construction and more

WebSite: http://www.copypasteisforword.com

ID:230559

Keywords:

Is,For,Copy,Paste,Word,and,more,Software,

Description:

keywords:
description:
Skip to Main Content Copy/Paste Is For Word Software Construction and more HomeWhat is this about? Understanding React Posted on enrique No Comments

I have just released my book Understanding React The Simplest Practical Guide to Start Coding in React.

Every successful framework or library provides something unique which gives developers a new tool for writing better software. In the case of React, that tool is called component. You might be thinking that you have been reading about components as the solution to your spaghetti software nightmare for the last 15 years without any success. You are not wrong. However, React is an exception. It provides the constructions and tools to build highly cohesive components to assemble your next application. In this book, we will study React core concepts, to end up being very practical describing how to split an application into components and to fully implement it.

Learn how to code applications in React by following a solid path that starts by studying essential JavaScript constructions to then go into React core concepts to finally write an application. Understand how to split an application into components (class or function-based ones), how to use props, state, events, hooks, react router and more.

Posted in Frameworks, React Coding an Architecture Style Posted on enrique No Comments

I have just released my book Coding an Architecture Style.

If you have had the bad experience of having to maintain a complex big ball of mud enterprise application, with pressure from the business to go to production with new features under an aggressive schedule, you, better than anyone, know how important is to have a solid architecture with clear defined rules where we can make modifications, having an understanding where every change will impact.

However, it is not enough to understand how to create solid architectures by looking at beautiful architectural diagrams. Or by reading long explanations about the benefits of Microservices or Modularity. Understanding how to create solid structures requires opening an IDE and starting coding. We have to learn what syntactical constructions, other than classes, functions and procedures, our favourite programming language offers to create large-scale applications and just there we will be able to craft different software structures and start recognizing their benefits and drawbacks.

Throughout this book we will iterate an application in order to show how to code different architecture styles. In each iteration we study and implement an architecture style, going through layered architecture, hexagonal (or ports and adapters), modular and microservices. All this is supported by solid architecture concepts, simple designs and good practices. We use Java 11 to implement all the mentioned styles. In particular, to implement the modular architecture style we use the module system incorporated in Java since version 9. We also show different options to verify the architecture rules imposed by each style. All sources are available for the reader.

Although the implementation is done in the Java language, it is possible to apply the same concepts in languages such as PHP, Ruby, Python or .NET.

We will also review the different architectural views, we discuss properties of monolith vs distributed architectures to finish with a pragmatic study of availability and scalability quality attributes.

Posted in Design Architecture Tagged with: architecture, Clean Architecture, Hexagonal, Microservices, Modular Architecture, Ports and Adapters
React: Thinking in Self Contained Components Posted on enrique No Comments

This is a post that will get you start with React. It is intended for server-side developers with basic JavaScript or JQuery experience, for Angular developers and for web developers in general without knowledge in React. Basically, that is me, a server-side developer with JQuery and Angular experience. Im very far to be a React expert. I was curious about React but what makes me to start learning was React Native (build once, in JavaScript/React Design, then, deploy in Android and iOS, real native mobile apps). To begin with, I decided to start with plain React and after that continue with React Native. I have to say that I liked React, a lot! It is a great library created to build real Object Oriented Designs on Web UI. This post is a brief of what I think you have to know to start developing with React.

I will start talking a bit about Reacts spirit and why it was created. Then I will follow with their few main concepts that you must understand to build applications with React. And finally, I will explain how I built a pretty small React application called react-simple that helped me to put in practice what I have read.

Object Oriented Style

React is a JavaScript library for building user interfaces. It was created by Facebook developers. ¿Why not use one of the many existing JavaScript libraries or frameworks instead of create another one? Well, they think that existing ones are unnecessary complex and doesnt help with maintainability for big front-end applications (like Facebook). So, they came up with a way to build and communicate self-contained UI components.

The first great thing that React gives you is a way to build small loosely coupled components to create User Interfaces. The really (seriously really) hard thing, as always, is Design!. I mean, how you should break a User Interface in small reusable components? There is a nice tutorial that helps specifically on this: Thinking in React.

The other great thing that React gives you is the rendering system, which takes care of DOM. You dont need to manipulate the DOM yourself. Reacts rendering system will do that for you thanks to a mechanism called Virtual DOM. When the internal state of a component change, it is re-painted on the screen by the rendering system. Pretty match like an observer pattern (or before that, like the Dependency Mechanism of the MVC implementation that comes with Smalltalk). But in contrast to the Observer Pattern, Reacts Components are the observer and the observable, that responsibility is not separated. The Components contain the state and the markup to paint that state on the screen. Do you see how nice is this? This is against many well known development styles where User Interface markup is on a template and gets mixed with state to be painted on the screen. Usually, this is done on Controllers, where state comes from Models and UI from templates Views. Sounds like MVC right? Well, React mindset is pretty different to this.

Reacts Main Concepts

There are few, but very important concepts that you have to understand. I will describe them as an introduction to the next section, in which I present a simple React application.

Component-driven Design:

As mentioned, the component is the primary syntactical construction of React used to create user interfaces. Reacts components interface requires you to implement a single method called render. The responsibility of the components render method is to paint itself on the screen.

Properties and state:

Reacts components encapsulates properties (props) and state. When any of these change, the component is re-painted on the screen. Properties are passed as arguments from components when creates (or instantiates) other components (in a parent/child relationship). They are read-only, they cannot change after the component is created. State is a special property which is mutable and is created and maintained inside de component. Once the component is created, you might want to change their state, in order to re-paint the component on the screen. This is where the state property is used. A typical use case is when your component gets data from a remote end point (making an Ajax call) and make changes to the State and that trigger the component to be re-painted.

Rendering System:

The rendering system is the mechanism that keep observing the special state property to trigger the call to the render method when it change (along with other hook methods from the life cycle, see below). So, we can say that Reacts components provides a kind of observer / observable (or subject) mechanism, but these two responsibilities resides inside the same object (or component). As you might have guessed, the render produce changes on the DOM. To implement this automatic update of the DOM, React use a data structure in memory called Virtual DOM, which is synced with the real DOM. While the algorithm is different, you can say that this process is similar to what ORMs do to keep the in memory objects in the persistence context synced with the persistent storage.

Components Life Cycle:

Reacts components follows a defined life cycle triggering events at certain moments depending on what the component has done or will do. The events are grouped in categories, which are three: Mounting (an instance of a component is attached to the DOM), Updating (The component is updated as a result of a change in props or state), UnMounting (When an instance of a component is detached from the DOM). The following table shows the sequence of life cycle events, grouped by category, illustrating which of them depends on changes on props and state. While is not an event, Im adding the constructor to the table. The events function are shown in the order in which they are executed by React.

Life Cycle TableCategoryEvent FunctionsMountingconstructor(), componentWillMount(), render(), componentDidMount()Updating PropscomponentWillReceiveProps(), shouldComponentUpdate(), componentWillUpdate(), render(), componentDidUpdate()Updating StateshouldComponentUpdate(), componentWillUpdate(), render(), componentDidUpdate()UnMountingcomponentWillUnmount()JSX:

JSX means JavaScript XML. It is an XML-like markup to describe the User Interface. This markup will end up creating instances of React Elements and Components. You will see that React Elements generally match with those found in HTML. More about JSX on the next section.

React-Simple Application

In this section I will go through react-simple, a basic application to put in practice the concepts I described in the previous section. I will explain how to download and run react-simple and then show the components and its communications in order you can see the concepts implemented.

Clone, Install and Start

Firstly you should clone the repo, install the dependencies of the project and start it (You will need to have installed: git, nodejs and npm. And this process will require a github account).

> git clone https://github.com/enriquemolinari/react-simple.git> cd react-simple> npm install> npm start

This will start the application in Nodejs, by default on port 3000. If you go to http://localhost:3000/, you should see a NavBar with the users link. See the picture below:

If you click on the More button you will see a fake details of the user, see below:

This application use react-bootstrap and react-spinners. It also use a free and online Random User API and to make ajax calls the Fetch API which is implemented in most of the browsers today.

Source Code

As mentioned, React applications can be built from many small components and those components communicates as a consequence of instantiation or event handling (button clicks, links, etc). Each React application can be seen as a tree structure of components. I will start describing the components that form the application, and then I will explain the most important lines of code of each component.

Below you will see the tree relationship of components I wrote for the react-simple application.

     -   App.js  -    /              \  MenuHeader.js  UserTable.js                   |             UserDetailModal.js                   |               UserDetail.js

To compare with what you would do in Java, since Reacts style is very object oriented, our application mains method would be launched in this way, just to give you other view of how this application is designed.

class Main { public static void main(String[] args) {    App app = new App(                    new MenuHeader(...),                     new UserTable(                          new UserDestailModal(                               new UserDetail(...)                          )                    )              );    app.render();  }}

The explanation of the source code follows the tree structure of components in preorder. In the source code below you will see more components in JSX markup. They belong to the dependencies of react-simple, like react-bootstrap and react-spinners.

index.html: This is just a simple html template where the main div container resides at line 17.

!DOCTYPE htmlhtml lang=en  head    meta charset=utf-8    meta name=viewport content=width=device-width, initial-scale=1, shrink-to-fit=no    meta name=theme-color content=#000000    !-- Bootstrap css files --    link rel=stylesheet href=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css integrity=sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u crossorigin=anonymous    titleReact Simple/title  /head  body    noscript      You need to enable JavaScript to run this app.    /noscript    div id=root/div  /body/html

index.js: This is the main method, the entry point, that render the root component, App, inside the div id=root container. Note that App / is the way to instantiate a component in JSX markup.

ReactDOM.render(App /, document.getElementById('root'));

App Component: Here is our root component, that is why it is called App. Or in terms of an Object Oriented Programming, this is our system object that will delegate on other object. Inside the render method we have the MenuHeader component being instantiated using JSX. As a parameter, property in Reacts world, we are passing a function called usersItemMenuClicked(). This function is received in the MenuHeader component as a property, acceded using this.props.usersItemMenuClicked. After that, in a conditional expression you see the UserTable component. Then, if we run this application, the App#render() will instantiate the MenuHeader and as described above, it will trigger the MenuHeader#constructor and then the MenuHeader#render(). Those methods are the only ones implemented in MenuHeader.js, see below. And finally it will also paint the text: Please, use the Users menu.

class App extends Component {  constructor(props) {    super(props);    this.usersItemMenuClicked = this.usersItemMenuClicked.bind(this);    this.state = {          userTableClicked : false    };    this.apiurl = 'https://randomuser.me/api/'; }  render() {    return (      div        MenuHeader usersItemMenuClicked={this.usersItemMenuClicked}/        {          this.state.userTableClicked ?            UserTable apiurl={this.apiurl}/            :            'Please, use the Users menu...'        }      /div    );  }  usersItemMenuClicked() {    this.setState({userTableClicked : true});  }}

MenuHeader Component: This is the component that render a NavBar (a react-bootstrap component) on the screen. If you see at line 23, there is an onClick event declared which will execute the handleClick instance method. If you see the implementation of that method at line 8, you will see that it is calling the function received as a parameter from the parent component App. And here is when the magic of React start. If the menu item is clicked, it will call the method App#usersItemMenuClicked in the parent component, which change an state property called this.state.userTableClicked. As described in the life cycle table above, this will make to trigger the App#render() method as we changed the state property owning by the App component. And that execute MenuHeader#render() (as is already there, that part on the real DOM is not updated since it will match with the one on the Virtual DOM), and instantiate the UserTable component. Lets continue there.

class MenuHeader extends Component {  constructor(props, context) {    super(props, context);    this.handleClick = this.handleClick.bind(this);  }  handleClick() {    this.props.usersItemMenuClicked();  }  render() {    return (      div        Navbar inverse collapseOnSelect          Navbar.Header            Navbar.Brand              a href=http://copypasteisforword.comReact Simple/a            /Navbar.Brand            Navbar.Toggle /          /Navbar.Header          Navbar.Collapse            Nav              NavItem eventKey={1} href=# onClick={this.handleClick}                Users              /NavItem              NavItem eventKey={2} href=#                Other Item ...              /NavItem            /Nav          /Navbar.Collapse        /Navbar      /div    );  }}

UserTable Component: This component knows how to bring users from the Random User API, using the Ajax Fetch API. This is done from two life cycle functions, componentDidMount(), on line 21 and componentWillReceiveProps(), on line 26. As described in the Life Cycle Table in the previous section, the first time you click on the Users menu item, the constructor(), and then render() are executed. At this point, we have the state property this.state.users initialized with an empty array, so you will only see the html table header on the page. The life cycle execution chain continue right after that, with the componentDidMount(), consuming the random users API and changing the this.state.user property, which will trigger the render() method again. This will end up painting the html table with 10 users.

Any other time you click on the Users menu item, since the UserTable component is already mounted and we are passing a property to it, the Update Props category is being executed, calling the componentWillReceiveProps() method bringing another random page of 10 users, which change the this.state.users property producing a call to the render() method again.

After rendering users, comes the instantiation of the UserDetailModal component, with a conditional based on a button click and a change in a state property owned by this component. The open button belongs to the UserTable component, but the close button belongs to the UserDetailModal component. However, the property this.state.showModal is owned by the UserTable component, so that component is the resposible to show and hide the modal window. Note that the UserDetailModal receives as a property (handleClose) an anonymous function from the UserTable component that is executed on the close event but in the context of the UserTable component.

class UserTable extends Component {  constructor(props, context) {    super(props, context);    this.state = {            users: [],            loading: false,            error: false,            errorMsg: '',            showModal: false          };  }  bringUsers() {    this.setState({loading: true});    fetch(this.props.apiurl + '?results=10')    .then((resp) = resp.json())    .then((users) = this.setState({users: users.results, loading: false}))    .catch((error) = this.setState({error: true, errorMsg: error.error, loading: false}));  }  componentDidMount() {    this.bringUsers();  }  //Needed for bringing another 10 users if menu item is clicked after mounted  componentWillReceiveProps() {    this.bringUsers();  }  render() {    if (this.state.error) {      return (        Alert bsStyle=danger          strongUps.../strong something went wrong ({this.state.errorMsg})        /Alert      )    }    return (      div        div          BarLoader color = {'#123abc'} loading = {this.state.loading} /          Table striped bordered condensed hover            thead              tr                th#/th                thGender/th                thName/th                themail/th                thactions/th              /tr            /thead            tbody              {                this.state.users.map((item, key) =                  tr key={key}                    td{key}/td                    td{item.gender}/td                    td{item.name.first} {item.name.last}/td                    td{item.email}/td                    tdButton href=# onClick={() = this.setState({showModal: true})}More.../Button/td                  /tr                )              }            /tbody          /Table        /div        { (this.state.showModal) ?             UserDetailModal                  apiurl={this.props.apiurl}                  show={this.state.showModal}                  handleClose={() = this.setState({showModal: false})}/        : ''        }      /div    );  }}

UserDetailModal Component: When the button More on the UserTable parent component is clicked, this component is mounted, executing the life cycle as explained in the previous section, bringing a random user on the componentDidMount() method, changing the this.state.user property, which trigger the render() method which now open a modal window instantiating the UserDetail component. The close event in this component change the state on the parent component (UserTable.state.showModal) triggering the UserTable#render(), which will paint the table of users but now without the modal, causing the unmounting of the UserDetailModal component. Note again that the table of users in the real DOM is not re-painted, since the Virtual DOM and the real DOM are identical there.

class UserDetailModal extends Component {  constructor(props, context) {    super(props, context);    this.handleClose = this.handleClose.bind(this);    this.state = {            user: null,            loading: false,            error: false,            errorMsg: '',          };  }  componentDidMount() {    this.setState({loading: true});    fetch(this.props.apiurl) // Simulate getting details from a user selected    .then((resp) = resp.json())    .then((user) = this.setState({user: user.results, loading: false}))    .catch((error) = this.setState({error: true, errorMsg: error.error, loading: false}));  }  handleClose() {    this.props.handleClose();  }  render() {    if (this.state.error) {      return (        Alert bsStyle=danger          strongUps.../strong something went wrong ({this.state.errorMsg})        /Alert      )    }    return (      div        Modal show={this.props.show}          Modal.Header            Modal.TitleUser Detail/Modal.Title          /Modal.Header          Modal.Body            {                (this.state.user) ? UserDetail details={this.state.user[0]}/                                   : BarLoader color = {'#123abc'} loading = {this.state.loading} /            }          /Modal.Body          Modal.Footer              Button onClick={this.handleClose}Close/Button          /Modal.Footer        /Modal      /div    );  }}

UserDetail Component: This is a stateless component. There is no state declared, only a prop with a user object that is painted on the screen.

class UserDetail extends Component {  render() {    let details = this.props.details;    return (      div        pimg src={details.picture.thumbnail} alt=user fake face//p        pbFirst Name: /b{details.name.first}/p        pbLast Name: /b{details.name.last}/p        pbId: /b{details.id.name} {details.id.value}/p        pbAddress: /b{details.location.street} ({details.location.city} {details.location.state})/p        pbPhone: /b{details.phone}/p        pbCell: /b{details.cell}/p      /div    );  }}

And that is it. See how interesting is this? Self-contained components that knows how to get the data and knows how to paint itself on the DOM when the internal state change. Pretty nice, right? I hope this can help understand better Reacts concepts. It is a different approach to build JavaScript front-ends, with a well known design mindset, but with an innovative rendering system which takes care of the DOM.

Posted in Frameworks Elegant Objects: Book Review Posted on enrique 1 Comment

I have been reading these two books about Object Oriented Programming: Elegant Objects (Volume 1) and Elegant Objects (Volume 2), by Yegor Bugayenko. They both are great books. I really recommend you to read them. They are full of advises to make your code more maintainable (and elegant!).

In this post I will make a short review of the books, but before doing that, lets go back in time, and let me explain how did I find these books and how I convinced myself that I had to buy them.

How did I arrived to these books?

If you have read this page you already know that Im teaching Object Oriented Programming II (You can say that is a course about Object Oriented Design) at Universidad Nacional de Río Negro. This job keeps me busy reading papers, blog articles and books in order to give to my students better answers and illustrative code samples written in OOP (but well written, or with good style, or Elegant!).

A year ago, I was searching at amazon.com about object-oriented programming books. To be completely honest, I dont think there are many good books about OOP. Indeed there are very few, and fewer with code samples. I have found good advises about Object Oriented Design on books that are not specific to that. For example, in the TDD book, there is a good example on how to create a Money Object. During the TDD exercise the author explains some design decisions he made. Going back to my searching on amazon.com I arrived to the Elegant Object book (Volume 1). The table of content caught my attention, specially the recommendation to not use getters and setters (which I mention to my students all the time) and also the recommendation on using checked exceptions (which I dont like). Anyway, by that time I was not enough convinced to buy the book.

Few months later, I was trying to find new examples where the Decorator Pattern could be applied and I ended up at Yegors Blog, more specifically at this post. There Yegor suggest to use Decorators to apply defensive programming. I liked it, so I use it in classroom.

Some time after that, I arrive to a post called Printers Instead Getters. In this post, Yegor shows how strong his advice dont use getters is. I tell to my students that it is only valid to use getters when you have to show a value on View. In any case, the name of the method should not be getSomthing(), just something(). But Yegor goes beyond that suggesting Printers instead, which looks elegant (and I thought that this is an example on how to take encapsulation very seriously).

I also found that Yegor suggest to read the book Object Thinking by David West. He was attracted specially by the definition of an object that David propose in his book, where objects are living organism and should be treated like a human being. I read David Wests book in 2012 and I wrote a post about that. Anyway, after that I found that Yegor interviewed David West. You can find the interview on YouTube: Yegor interviewing David West part 1, and Yegor interviewing David West part 2. Excellent talk, really!. You will learn from them. There are some funny moments, but one I really enjoy was when David expressed his love to the relational model :).

Well too many good things. I decided to buy their books :).

My thoughts on these books

As I mention before, they are great books. It will open your mind and you will re-think some things you were doing. However, Im not agree with everything he expose. There are few items which I have a different opinion.

Next you will see my review of these books, in two sections. The first one is about what I like it more and the second one is about the proposals that Im not agree with. In both sections I will be talking about the two volumes as if they were just one book.

1. Items I Like it More

Never use -er names. This is for class names. How many of you have named one of your classes like SomethingManager? Or Encoder?. The author explains why that is bad. His suggestion is supported by the idea of objects as living organisms. Think of what he is, not what he does. See what his objects will encapsulate and come up with a name.

Choose method names carefully. The author divides methods in two categories: builders and manipulators (same as query and commands), proposing names for each of them. This item and the previous are simple rules, which are easy to apply to your code making it more elegant. Builders are nouns, manipulators are verbs.

Dont use public constant. I have learn something here. Very nice approach!

Its all about prefixes. This refers to getters and setters. After talking about all bad things about them, specially that treat objects as data structures, the author make a very appropriate distinction about naming methods that return something (getters in this case). It was good to see that is exactly what I say to my students. You can have methods that return data encapsulated in the object, but the name of that method should not reveal nothing about the internals of the object. There is a nice explanation about this. In addition, returning encapsulated data should be allowed only for very specific purposes, like presenting it in a View. And, if possible, return a copy of that, not a reference.

Algorithms. I love this chapter. The author takes a program in Basic, then re-write it in Pascal, then in C and then in procedural Java. After that he re-write it using the Object Oriented Paradigm (in Java). Converting a clearly procedural and imperative program in an object-oriented and declarative program. I suggest that every introductory course in Object Oriented Programming should start with a demonstration like the one in this chapter. It will open students mind from the very beginning.

2. Items I have other opinion

Before start with the items, there are some things I would like to comment. The author does not mention anything about Smalltalk in their books. But if you check on the web, He is writing a new Object Oriented Language called eolang. He said that will be a pure Object Oriented Language (due to Smalltalk, Java, Ruby, and others have features that should not be included in a pure object-oriented language). But the guys who invented the term Object Oriented (Alan Kay and others) told us that Smalltalk is the pure object-oriented language. So? who is right?. And I dont want to start a discussion here about if a pure object-oriented language should have static or dynamic typing :). Eolang will have static typing. In any case, it is very valuable to contribute with these ideas implemented in a new language with only educational intentions.

There is another interesting point that the author mention that is different but somehow aligned with Smalltalk. He suggest that if statements/keywords are borrowed from procedural languages and should not be available in a pure object-oriented language (same as Smalltalk at this point). He propose that there should be a class called If, where by constructor accept a boolean expression, a then expression and an else expression. That differs from Smalltalk where Boolean is an object and ifTrue and ifFalse are methods of the Boolean class. Below is an example of how to write if statements in Smalltalk:

a  b  ifTrue: [^'a is less than b']  ifFalse: [^'a is greater than or equal to b']

a b is an instance of either True or False class (they both inherit from the Boolean abstract class). ifTrue and ifFalse are methods defined in both classes: True and False. In the example above, the Smalltalk runtime will call both methods, ifTrue and ifFalse, but the block passed as argument (the one in square brackets) will be evaluated only in the correct instance. This means, that if a b evaluates to an instance of True, the runtime will call ifFalse and ifTrue in the True instance. Guess what now? Yes the implementation of ifFalse in the True class just does nothing (return nil). And the implementation of the ifTrue method in the True class, does the evaluation of the block passed as argument. Very Object Oriented right?

Which design is better? if as an object or if as a method of a Boolean class? or which one is more object-oriented?. Maybe, a comparison of these approaches generates a new post in Yegors blog :). Anyway, these were few things that went through my head while reading the book.

Below you will find some topics that I have a different opinion than the author. I will describe a bit what is the author intention and then I will give my point. The item list is in no particular order.

Code free constructor: The author suggest to not do more than an assignment of the input parameters in the constructor. My opinion is that validation of the parameters should be done there. See an example below:

public class Person {   ...   public Person(String ssn) {      this.ssn = new SocialSecurityNumber(ssn);   }   ...}public class SocialSecurityNumber {   ...   public SocialSecurityNumber(String ssn) {      if (!this.validFormat(ssn)) {            throw new RuntimeException(The ssn should              have the format: AAA-GG-SSSS);      }      this.ssn = ssn;   }   ...}

If I have a SocialSecurityNumber class and one of their constructors accepts a Social Security Number in String type, I have to validate the format. As a client of the class I prefer to receive as soon as possible that there is a mistake, and that is right after I create the instance. If this is not done there, where should we put the validation? when a method of the class use the SSN? This is not clear in the book. In any case, I think that validations should be done in the constructor.

Be either final or abstract: The author suggest that a class should be abstract or final, which means that if you want your clients inherit from your classes then those must be abstract, if not, declare them final (nobody will be able to inherit from them). In my opinion, most of the time that should be the rule to guide you. There are many reason why you should favor composition over inheritance (See Effective Java by Joshua Bloch). Few times we might have scenarios where inheritance is just fine and a good fit. You just need to apply it properly. I have written this post Use Inheritance Properly with my thoughts on this. Basically, dont use inheritance for code reuse. Use it only if there is a true subtype relationship between the subclass and the superclass. What about the Object class of languages like Java or Smalltalk? Should that class be abstract then? In these languages Object is a concrete class and we extend from it. Another discussion.

Throw Only Checked Exceptions: Yegor suggest to throw always checked exceptions. His argument is that they make pretty visible to the clients that a method might fail somehow. While that is true, it also force the client to handle the exceptions, using a catch block or re-declaring it. As a developer and client of different libraries, most of the time I have a top-level piece of code that handle any exception that may occur, in my code or in librarys code. Most of the time, I dont care what exceptions the libraries I use may throw, Im more interesting in log them properly when they occur and make my team aware of that as soon as possible (with proper monitoring). If for some reason, I have to know what exceptions a method might throw I go to the documentation. So, force me to do something else (writing additional lines of code) just to make the compiler happy is not something I like. I prefer runtime exceptions.

This chapter in the book continues with sections named Only one exception type is enough and Dont catch unless you have to, which are advises that Im totally agree with.

ORM: This is the chapter that it is the most controversial for me. The author hates ORMs because he says that treats objects as data containers. Well that is true, ORMs needs access to your private members to create instances. It force you to generate getters and setters of each attribute. He also, along the ORM chapter, refers to ORM as the mapping from table rows to objects. He says that the entire concept of mapping tables rows to object is wrong, and he simple propose that objects should just use SQL. And there should be a persistent layer in your app with persistent objects, like DbBook, which encapsulate SQL statements. He does not mention anything about concepts related with Object Oriented Databases, which are the ones that a ORM tries to simulate.

I agree with him about that objects should never be treating as data structure, that is procedural thinking. And it is also true that most bibliography when shows you how to use ORMs, happily presents objects full of getters and setters. However, you can take advantage of ORMs and using it in a better way. First of all, Objects should map to table rows, and not in the other way. That is the way of thinking. If you already have a relational model, then mapping them to objects will just create data structures. First you do object-oriented programming, taking that the volatile memory is just persistent. After you are happy with your design, you then think how that can be persisted in a real persistent storage. In the end, that is exactly what you do if you use an Object Oriented Database. I like to think persistence as transparent as possible to my objects (domain model). And transparent persistence is a great thing that can be achieved with a good use of a ORM like Hibernate. I wrote this post and this, and this describing the concept.

Another bad thing that the author allude is that data is injected into the object without his knowledge. The objects dont know about that because it happen outside his control. This is a phrase that he repeat several times along their books, the objects must be in control of what happens with the state they encapsulate. He takes this rule pretty seriously. For example, solving access control using annotations and having a framework that allows or not the invocation of that method (based on the information provided in the annotation) is something wrong. He suggest to use Decorators instead.

This rule is good, but as always there are pros and cons. In the case of a ORM, we should not forget that the persistent storage was first populated with objects that we created, using the simple and beauty objects constructor which contains the validations according to our business rules. So, we should be fine and trust our data storage (and the framework creating instances for us). You can also declare getters and setters protected and that will be enough for your ORM. And then make a rule with your dev team that those are only for the ORM, not for other reason.

To sum up, I think what ORMs offer to us (which is taken from OODBMS): Transparent Persistence and Persistence by Reachability, help us with maintainability more than not using it.

That was all I have for now. Now I have to clarify to my wife why Im saying that a piece of code should be treated as a living organism

Posted in Object Oriented Programming Object Oriented Frameworks: Concepts, White Box and Black Box Examples Posted on enrique No Comments

When teaching Object Oriented Frameworks (usually in Advanced Object Oriented Programming courses) there is a challenge for students to understand their nature, differences with libraries and the difference between white box frameworks vs black box frameworks.

In this post I will start talking very briefly about general concepts of frameworks. Then I will implement a pretty simple white box framework as an example and after that I will transform the white box framework into a black box framework.

Frameworks Definition

The key driver that made to evolve software development into the creation and use of Frameworks was, is and will be code reuse.

Before frameworks appeared, the only software constructions used to obtain code reuse were library of functions, for procedural / imperative programming languages and library of classes for object oriented languages (other ways you can find out there are modules in Modula, packages in Ada and/or clusters in CLU). Libraries in general allows you to reuse only source code and for an specific task.

Frameworks came into the world of software development to provide design and source code reuse. Frameworks provides a greater level of reuse. They define a design and the implementation of an specific class of software application allowing the users, which are developers, to use it as it is (with some configuration like connection strings and i18n for instance), or extend it to adapt it to their specific needs.

To give a definition of what a framework is, I will take the one from the GOF book: A framework is a set of cooperating classes that make up a reusable design for a specific class of software. A framework define the design of our application, the key classes, responsibilities and collaborations. It will also determine the control flow of our application, where the execution always start in the frameworks code.

How Frameworks are different from Libraries?

When you use a software library, the execution start in the applications code and is the application who call the library to use it. With frameworks, the execution start in the frameworks code, and is the framework who call application methods. This is called Inversion of Control and is one of the key concepts for frameworks and a key distinction between frameworks and libraries.

How to provide extension points and how they are achieved?

There are no new or magic mechanisms in how the frameworks provides extension points, also called hook methods. They are available thanks to the dynamic binding concept, well known from the very beginnings of Object Oriented Programming. Frameworks are able to make calls to object methods which can be replaced or interchanged at runtime with developers code (users of the framework) thanks to the dynamic binding mechanism.

Within the flow of collaborations implemented in a framework, there will exists documented extension points or hook methods that users can take advantage of to inject their own behaviour. This is the way of how you can extend a framework.

Why White Box or Black box Frameworks?

The way in which the framework provides the extensibility make the framework be of type white box or black box. A framework that provides extensibility by using inheritance are white box. Which means that if you need to customize a framework and to do that you have to inherit from a frameworks class and override a method then that is white box.

A framework that provides extensibility by composing and injecting objects to combine different collaborations are black box. Which means that if you need to customize a framework and to do that you have to implement an specific interface and somehow the framework will pick your class and call it at the extension points that was documented, then that is a black box.

White Box Framework Example

Lets imagine that in the Java programming language, printing a message in a dialog box is very hard. So, in order to make a software that need to do that you need to use a framework to make your life easier. Here we will develop the framework using white box design and then we will demonstrate how a developer can use our framework.

Below you will see our PrintOnScreen framework, including some comments to explain how is used.

package ar.cpfw.whitebox;import javax.swing.JFrame;import javax.swing.JOptionPane;/* This framework allows you to show text on a dialog box. *  * To use it, you have to extends from the PrintOnScreen class  * and implement their abstract method. *  * The framework provides the PrintOnScreen#print method which  * makes the magic. * */public abstract class PrintOnScreen {	public void print() {		JFrame frame = new JFrame();		JOptionPane.showMessageDialog(frame, textToShow());		frame.dispose();	}	protected abstract String textToShow();}

Now, lets extends the framework:

package ar.cpfw.utilization;import ar.cpfw.whitebox.PrintOnScreen;public class MyApplication extends PrintOnScreen {	@Override	protected String textToShow() {		return printing this text on 				+ screen using PrintOnScreen 				+ white Box Framework;	}}

And finally, instantiate it, and run it:

package ar.cpfw.utilization;public class Main {	public static void main(String args[]) {		MyApplication m = new MyApplication();		m.print();	}}

Some conceptual points to highlight about the PrintOnScreen framework and their usage:

Note that the framework itself is in a different package that the use of the framework. That is what will normally happen in real life if you use a framework developed by other developer. Even if you develop the framework and use it, it is a good practice to separate the classes in packages (modules).

The extension point (hook) is an abstract method. To use and extend the framework I have to inherit from the framework class. That is a key characteristic of a white box framework.

It use inversion of control, the framework method PrintOnScrenn#print calls our method MyApplication#textToShow.

The framework use the Template Method pattern, which is mainly the pattern used to create white box frameworks.

Finally, note that as a developer I would be able to override the PrintOnScreen#print method as is public. That method was not developed for that intention, that is why framework documentation is important for clarifying these things. However, as a developer I might make this mistake. This is a clear drawback of frameworks based on inheritance. Java (but not all Object Oriented languages) provides the final keyword to help framework developers to flag which methods cannot be overridden. If we put the final keyword to the PrintOnScreen#print method, that would be best.

Black Box Framework Example

Here we are going to transform our white box framework into a black box one. Find below the frameworks classes:

package ar.cpfw.blackbox;import javax.swing.JFrame;import javax.swing.JOptionPane;/* This framework allows you to show text on a dialog box. *  * To use it, you have to implement the interface TextToShow.  * Then, create an instance of the class PrintOnScreen passing * your implementation of TextToShow as a constructor param.  *  * The framework provides the PrintOnScreen#print method which  * makes the magic. * */public final class PrintOnScreen {	TextToShow textToShow;		public PrintOnScreen(TextToShow text) {		this.textToShow = text;	}		public void print() {		JFrame frame = new JFrame();		JOptionPane.showMessageDialog(frame, 																			textToShow.text());		frame.dispose();	}}
package ar.cpfw.blackbox;public interface TextToShow {	String text();}

Some points to highlight about the changes made:

We made the PrintOnScreen class final (we dont want our users to inherit from it).

Then, we created an interface called TextToShow, which is the extension point. And compose it as a private member of the PrintOnScreen class (line 16).

After that, we changed the PrintOnScreen#print method to delegate on the TextToShow#text method (line 25).

And finally, we created a constructor method on the PrintOnScreen class that accept a TextToShow instance as a parameter (line 18-20). This is the way our users will inject their instance.

In the black box example, words like compose and delegate are now the important ones over inheritance from the white box example.

We have only left to show how to use our black box framework, let follow their instructions. First we implement the TextToShow interface:

package ar.cpfw.utilization;import ar.cpfw.blackbox.TextToShow;public class MyTextToShow implements TextToShow {	@Override	public String text() {		return printing this text on 				+ screen using PrintOnScreen 				+ black Box Framework;	}}

And finally,

package ar.cpfw.utilization;import ar.cpfw.blackbox.PrintOnScreen;public class Main {	public static void main(String args[]) {		PrintOnScreen m = new PrintOnScreen(new MyTextToShow());		m.print();	}}

That completed our migration from white box to black box and hopefully illustrate the differences.

JQuery: Callback Functions

JQuery is a JavaScript Library, not a framework. However, using it you will notice that provides mechanisms for injecting your own behaviour that will be called by JQuery, hence we have inversion of control. In the JavaScript world, this mechanism or extension point is called callback functions.

To finish this post, I wanted to show how in Web client side development libraries like JQuery, you will find the frameworks concepts described here.

In the html/JavaScript below you will see the use of hide() and show() JQuery functions. Both functions provides the ability to pass as a parameter a callback function, see the lines 8 and 11 below.

!DOCTYPE htmlhtmlheadscript src=https://aserver.com/jquery.min.js/scriptscript$(document).ready(function(){    $(#hide).click(function(){        $(p).hide(myFunction);    });    $(#show).click(function(){        $(p).show(myFunction);    });});function myFunction() {    console.log(This was called by the JQuery library);}/script/headbodypIf you click on the Hide button, I will disappear./pbutton id=hideHide/buttonbutton id=showShow/button/body/html

When a user clicks on the Hide or Show button, after (this is clearly specified in the JQuery documentation) hide or show the paragraph p, it will call myFunction, which drops the This was called by the JQuery library message in the console.

Posted in Design Architecture, Frameworks, Object Oriented Programming Tagged with: Frameworks, Object Oriented Paradigm
Hibernate/JPA Transparent Persistence II Posted on enrique No Comments

I wanted to add another nice example about Transparent Persistence (explained in a previous post), to insist on the beauty of this. This time, adding JPA mappings in the classes that represent the domain model of my application. Additionally, I will mention how Hibernate/JPA behaves in this case, and how to change that if necessary, to ensure your application perform smoothly.

Suppose Im implementing an application that allows you to create different competitions and let people (participants) enrol to them. Participants are allowed to enrol the competition only during a period of time, defined within the competition. It will also need validate if the participant is not already enrolled.

As I have been saying in my other post, implement your business requirements inside your domain model, dont be tempted to put business logic inside Facades, DAOs, Repositories, Controllers, etc. This temptation occurs specially once you have to persist your objects. Think in a way that your memory is persistent, implement your requirements in the domain model and then use Transparent Persistent. Only when the ORM tool you are using does not provide the features to make the transparent persistence perform smoothly, then there is when you are forced to make changes to your objects.

So, lets implement this in the domain model. The domain model with JPA annotations looks like the one below:

@Entitypublic class Competition {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	private String name;	@Column	private LocalDate startDate;	@Column	private LocalDate endDate;	@OneToMany(mappedBy = competition)	private CollectionParticipant participants						= new ArrayList(); 	        	//just for Hibernate	protected Competition() { }	public Competition(String name, LocalDate startDate, 							LocalDate endDate) {		this.name = name;		this.startDate = startDate;		this.endDate = endDate;	}	public void enrol(Participant p) {		checkEnrolInPeriod();		if (!this.participants.contains(p)) {			participants.add(p);			p.setCompetition(this);		}	}	private void checkEnrolInPeriod() {		LocalDate today = LocalDate.now();		if (!(!today.isBefore(this.startDate) 				 !today.isAfter(this.endDate))) {			throw new RuntimeException(You can't 							+ enrol outside the period...);		}	}}@Entitypublic class Participant {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	private String name;		@ManyToOne	@JoinColumn(name = competition_id)	private Competition competition; 		//just for Hibernate	protected Participant() { }		public Participant(String name) {		this.name = name;	}    	...}

Now, in the client code of my domain model, in this case, a Facade that is used by my Front-End, we wrap in a persistent context the following sentences:

	public void enrol(idCompetition, idParticipant) {		//start persistence context		Competition aCompetition = // retrieving from the storage by Id		Participant aParticipant = // retrieving from the storage by Id		aCompetition.enrol(aParticipant);		//close persistence context	}

What happen if we execute the enrol(idCompetition, idParticipant) method ?

The first line will retrieve from the persistent storage the aCompetition instance, executing the following SQL statement:

    select        id,        competition_id,        name,    from        Competition    where        id = idCompetition;

Note that there is no retrieval at all from Participants, which means that the Competition#participants collections is not initialized. This is because by default in JPA the one-to-many relationship is lazy. Lazy means that only if you need somenthing from that collection, then at that point the collection will be initialized.

The second line will retrieve from the persistent storage the aParticipant instance, executing the following SQL statement:

    select         participan0_.id,         participan0_.competition_id,         participan0_.name,        competitio1_.id,        competitio1_.endDateForInscription,        competitio1_.name,        competitio1_.startDateForInscription    from Participant participan0_             left outer join Competition competitio1_ on               participan0_.competition_id = competitio1_.id     where participan0_.id = idParticipant;

Note that there is a join with Competition due to in JPA the many-to-one relationship that exists here between Participant and Competition, is eager by default.

The third (and last) invoke the business method aCompetition.enrol(aParticipant). Looking at the code of that method:The first sentence: checkEnrolInPeriod(); will check if aParticipant is on time to be enrolled in aCompetition. There is no SQL statement generated here as the instances loaded before has everything needed to execute this check.After that, the sentence this.participants.contains(p) will make Hibernate/JPA to initialize the participants collection. This will produce a SQL statement like the following:
    select        name,                id,        competition_id    from        Participant    where        competition_id = idCompetition;

After executing that SQL and initializing the collection, the Collection#contains is executed. This is normal Java behaviour, it will compare instances using the equals method, and with that will decide if aParticipant is already enrolled or not.

Following that, if the condition evaluates to true, then it will add aParticipant to the participants collection. Generating the following SQL statment
    update         Participant    set         competition_id=?,     where         id = idParticipant;

Note that the SQL statement is generating the relationship between Competition and Participant in the relational model.

It is important to highlight, one more time, that our Competition#enrol(Participant) method has been written without thinking in the underlying persistent storage (in this case a relational model). And in a Transparent way, the persistent storage has been modified to accommodate the changes in the objects that belongs to the domain model.

Performance Improvement

As showed before, the sentence this.participants.contains(p) is bringing to memory all the participants from the persistent storage, in order to compare if aParticipant is already enrolled or not. This works perfect for small collections, but for large collections might not work.

Hibernate/JPA provides an additional annotation for this case called Extra Lazy. The extra lazy mapping will produce that the methods Collection#size and Collection#contains wont trigger the initialization. Lets make that addition to our class.

@Entitypublic class Competition {	...	@OneToMany(mappedBy = competition)	@LazyCollection(LazyCollectionOption.EXTRA)	private CollectionParticipant participants						= new ArrayList(); 	        	...}

With this in place, our explanation above about what occurs when this.participants.contains(p) is invoked will change. Now, instead of initialize the collection (bring all the participants into memory), it will perform the next SQL statement to let the persistent storage to answer if aParticipant has been enrolled or not.

        select                  1         from                 Participant         where                 competition_id = idCompetition and                 id = idParticipant;

Looks good right?

This post presented another example or use case where you are allowed to develop Object Oriented software without having to break how you model your objects or without being forced to break your object model due to persistence. Enjoy Transparent Persistence.

Posted in Persistence Tagged with: Hibernate, OOP, Persistence
Lambda Expressions in Java, a Concrete Example Posted on enrique No Comments

Maybe you have read several posts on the web on how Lambda Expressions are used. Most of the ones I have read uses examples for filtering collections with the new Stream API of Java 8. Those examples are good but they are more focused on showing a fancy way of filtering a collection rather than on showing or highlight the code structures that now you dont have to write, in this case, the for loops. Without Lambda Expressions, each time you need to filter data from a collection, you have to iterate the collection (repeating a for loop construction). That is not necessary any more.

In this post I will show a concrete example of removing duplicated code using Lambda Expressions. For the demonstration I will be using JPA (Java Persistence API), following the topics of my previous post.

I believe that showing how to use Lambda Expressions putting the focus on the removal of duplicated code will open your mind on the potential that they have.

Suppose Im asked to write some code to do a simple save, update and retrieve of a specific Entity class, using JPA. To implement that, I will write a class called ADataAccessObject (just to name it somehow). Below you will find what I have written in my first development iteration, the make it work step.

public class ADataAccessObject {	private EntityManagerFactory emf;	public ADataAccessObject(EntityManagerFactory emf) {		this.emf = emf;	}	public void save(AnEntity anEntity) {		EntityManager em = this.emf.createEntityManager();		EntityTransaction tx = null;		try {			tx = em.getTransaction();			tx.begin();			em.persist(anEntity);			tx.commit();		} catch (Exception e) {			if (tx != null) {				tx.rollback();			}			throw new RuntimeException(e);		} finally {			em.close();		}	}	public void update(long id, String aNewPropertyValue) {		EntityManager em = this.emf.createEntityManager();		EntityTransaction tx = null;		try {			tx = em.getTransaction();			tx.begin();			AnEntity anEntity = em.find(AnEntity.class, id);			anEntity.setAProperty(aNewPropertyValue);			tx.commit();		} catch (Exception e) {			if (tx != null) {				tx.rollback();			}			throw new RuntimeException(e);		} finally {			em.close();		}	}	public AnEntity byId(long id) {		EntityManager em = this.emf.createEntityManager();		try {			return em.find(AnEntity.class, id);		} catch (Exception e) {			throw new RuntimeException(e);		} finally {			em.close();		}	}}

Now lets write the client code that use the class above:

public class Main {	public static void main(String arg[]) {		EntityManagerFactory emf = null;		try {			emf = Persistence					.createEntityManagerFactory(a-persistence-name);			ADataAccessObject dao = new ADataAccessObject(emf);			//store anEntity ...			dao.store(new AnEntity(aValuForTheProperty));			//update anEntity ...			dao.update(1l, anotherValueForTheProperty);			//retrieving ...			AnEntity e = dao.byId(1l);		} finally {			emf.close();		}}

What does not look nice from the code above? As you might have noticed, each method seems to be pretty similar. The try/catch/finally block with the creation of the EntityManager, the Transaction#commit, Transaction#rollback and the EntityManager#close, all of these are duplicated.

To clarify a bit more, below are the sentences unique per method:

//from ADataAccessObject#storeem.persist(anEntity);//from ADataAccessObject#updateAnEntity anEntity = em.find(AnEntity.class, id);anEntity.setAProperty(aNewPropertyValue);//from ADataAccessObject#byIdreturn em.find(AnEntity.class, id);

How can we remove that duplicated code? There are some options. You can use Dynamic Proxys or AspectJ. Or incorporate a framework like Spring to handle JPA Transactions for you. Do we have simpler approach? I dont want to incorporate any framework, I would love the language itself provides the syntactical construction to do it.

What if the programming language allows you to pass a block of code as a method parameter? That sounds great, because I can create a private method in my ADataAccessObject class with the try/catch/finally structure and receive each unique block of sentences by parameter.

Before Java 8, this was possible using Anonymous Classes. Lets moving ahead with this approach then.

For implementing this approach we have to create an Interface to specify the signature of the block of code that we need to pass by parameter. Described next:

public interface ABlockOfCode {	AnEntity execute(EntityManager em);}

That Inteface above is the type of my block of code. Each block of code will respond to the execute method, it must receive the EntityManager by parameter and must return AnEntity.

Lets go through the second iteration of my code, the make it better step. I will refactor a bit my ADataAccessObject Class adding some anonymous classes to eliminate duplicated code.

public class ADataAccessObject {	private EntityManagerFactory emf;	public ADataAccessObject(EntityManagerFactory emf) {		this.emf = emf;	}	public void store(AnEntity anEntity) {		transactionExecute(new ABlockOfCode() {			@Override			public AnEntity execute(EntityManager em) {				em.persist(anEntity);				return null;			}		});	}	public void update(long id, String aNewPropertyValue) {		transactionExecute(new ABlockOfCode() {			@Override			public AnEntity execute(EntityManager em) {				AnEntity anEntity = em.find(AnEntity.class, id);				anEntity.setAProperty(aNewPropertyValue);				return null;			}		});	}	public AnEntity byId(long id) {		return transactionExecute(new ABlockOfCode() {			@Override			public AnEntity execute(EntityManager em) {				return em.find(AnEntity.class, id);			}		});	}	private AnEntity transactionExecute(ABlockOfCode aBlockOfCode) {		EntityManager em = this.emf.createEntityManager();		EntityTransaction tx = null;		try {			tx = em.getTransaction();			tx.begin();			AnEntity a = aBlockOfCode.execute(em);			tx.commit();			return a;		} catch (Exception e) {			if (tx != null) {				tx.rollback();			}			throw new RuntimeException(e);		} finally {			em.close();		}	}}

As you can see, I have created a private method called transactionExecute which expects as parameter an instance of ABlockOfCode. In each public method, Im creating these instances, as anonymous classes, implementing the execute method of the ABlockOfCode with the sentences unique per method described before. Then, each method calls transactionExecute, passing these ABlockOfCode instances by parameter. Finally, note that inside the transactionExecute method, there is a call to the execute method of the ABlockOfCode instance, inside the try/catch/finally template.

Not bad right? Lets do it now even better in my third development iteration. Im going to replace the anonymous classes with Lambdas. In Java 8, Lambdas are a prettier way of writing anonymous classes (not the case for functional programming languages, but this is a different talk). They incorporate a syntactic sugar plus a type inference system, which make the code cleaner and easier to read.

The code below starts moving the transactionExecute private method to its own class.

public class TransactionTemplate {	public EntityManagerFactory emf;	public TransactionTemplate(EntityManagerFactory emf) {		this.emf = emf;	}	public AnEntity execute(ABlockOfCode aBlockOfCode) {		EntityManager em = this.emf.createEntityManager();		EntityTransaction tx = null;		try {			tx = em.getTransaction();			tx.begin();			AnEntity returnValue = aBlockOfCode.execute(em);			tx.commit();			return returnValue;		} catch (Exception e) {			if (tx != null) {				tx.rollback();			}			throw new RuntimeException(e);		} finally {			em.close();		}	}}public class ADataAccessObject {	private TransactionTemplate transaction;	public ADataAccessObject(TransactionTemplate transaction) {		this.transaction = transaction;	}	public void store(AnEntity anEntity) {		transaction.execute(			(em) - { em.persist(anEntity);								return null;							});	}	public void update(long id, String aNewPropertyValue) {		transaction.execute(			(em) - { AnEntity anEntity = em.find(AnEntity.class, id);								anEntity.setAProperty(aNewPropertyValue);								return null;							});	}	public AnEntity byId(long id) {		return transaction.execute(			(em) - {								return em.find(AnEntity.class, id);							});	}}

On the highlighted lines you will see the Lambda Expressions. A lambda expression, is composed of two parts, separated by the lexical token -: (parameters) - { block of code }. There is no need to specify the type of the parameter in the lambda expression, it will be inferred from an interface, in this case, the ABlockOfCode. If you look at this interface you will note that each lambda expression receives an instance of the EntityManager as parameter, (em), and must return an instance of AnEntity.

As a final development iteration, I will make this more generic. My ABlockOfCode interface and TransactionTemplate class should support any object type, not only AnEntity. So next I will change the AnEntity type for a generic type T.

Starting with the ABlockOfCode interface:

public interface ABlockOfCodeT {	T execute(EntityManager em);}

I have just replaced AnEntity with the generic type T, and I have declared that type T as a generic type, using the T syntax (on line 1).

Next, I will make the TransactionTemplate#execute method generic:

	public T T execute(ABlockOfCodeT aBlockOfCode) {		EntityManager em = this.emf.createEntityManager();		EntityTransaction tx = null;		try {			tx = em.getTransaction();			tx.begin();			T returnValue = aBlockOfCode.execute(em);			tx.commit();			return returnValue;		} catch (Exception e) {			if (tx != null) {				tx.rollback();			}			throw new RuntimeException(e);		} finally {			em.close();		}	}

On line 1, Im declaring the generic type T, changing the signature of the method returning T and expecting ABlockOfCodeT as parameter. Note also that the return type of the aBlockOfCode.execute(em) sentence, has change from AnEntity to T, on line 8.

With this last change we have made the TransactionTemplate#execute method generic to be used by any instance of ABlockOfCode that requires a JPA transaction context. The ADataAccessObject class does not need to change, because as I explained before, the Lambdas infer their type from the ABlockOfCode interface.

We just went through out some development iterations in order to remove duplicated code. This nature of the duplicated code shown here, is not able to be removed using simple refactoring techniques like extract method or extract class. It requires more powerful language feature to allow passing sentences, or blocks of code, by parameter. That was achieved using anonymous classes first and then with Lambda Expressions. And remember, dont do refactoring iterations without test coverage.

Posted in Design Architecture Tagged with: duplicated code, Java 8, Lambda
Hibernate/JPA Inheritance and Polymorphic Asociations Posted on enrique No Comments

This post is part of a series of post I will be written about Hibernate. In this one, I will be describing how Hibernate and JPA deals with inheritance and polymorphic associations.

Im going to implement a very simple bank domain model to demonstrate how to persist an inheritance hierarchy and deal with polymorphic associations.

Let suppose the bank has clients and accounts. We have two kinds of accounts: SavingsAccount and CheckingAccount. In the SavingsAccount you can do extractions only if you have enough money while in the CheckingAccount you can do extractions until you reach an overdraft set by the bank. In both accounts you can deposit money.

To implement this, Im going to create the following abstract class called BankAccount, with some common behaviour.

public abstract class BankAccount {	protected float amount;	public abstract float extract(float anAmount);	public void deposit(float anAmount) {		this.amount += anAmount;	}	public float getAmount() {		return amount;	}}

And then the SavingsAccount and CheckingAccount classes extending it.

public class SavingsAccount extends BankAccount {	public SavingsAccount(float amount) {		this.amount = amount;	}	@Override	public float extract(float unMonto) {		if (this.amount = unMonto) {			this.amount -= unMonto;			return this.amount;		}		throw new RuntimeException(There is not enough money to do 				+ the extraction...);	}}
public class CheckingAccount extends BankAccount {	private float overdraft;	public CheckingAccount(float amount, float overdraft) {		this.amount = amount;		this.overdraft = overdraft;	}	public float getOverdraft() {		return overdraft;	}	@Override	public float extract(float unMonto) {		if (unMonto = (this.amount + overdraft)) {			this.amount -= unMonto;			return this.amount;		}		throw new RuntimeException(There is not enough money to do 				+ the extraction...);	}}

Now, banks clients might have any number and types of accounts. We should also be able to know the total amount of money each client has. To implement this, the clients will respond to the totalMoney() message.

public class Client {	private String name;	private Set bankAccounts = new HashSet();	public Client(String name) {		this.name = name;	}	public String getName() {		return name;	}	public float totalMoney() {		float total = 0;		for (BankAccount bankAccount : bankAccounts) {			total += bankAccount.getAmount();		}		return total;	}	public void addAccount(BankAccount ba) {		this.bankAccounts.add(ba);	}}

Lets add two test cases before move on:

public class TestClient {	@Test	public void client_with_no_accounts_the_total_is_zero() {		Client client = new Client(aClient);		Assert.assertEquals(0f, client.totalMoney(), 0);	}	@Test	public void client_with_two_accounts_the_total_is_calculated() {		Client client = new Client(aClient);		BankAccount ba1 = new SavingsAccount(350);		BankAccount ba2 = new CheckingAccount(250, 100);		client.addAccount(ba1);		client.addAccount(ba2);		Assert.assertEquals(600f, client.totalMoney(), 0);	}}

So, we have a simple inheritance hierarchy and a Client class with the bankAccounts polymorphic association. Next, we are going to map them into a relational model. I will first add an Id instance variable for entities. Note that the code below will only contain the necessary instance variables and mapping annotations to show our goal (you will also have to add setters and getters and the default constructor as required by Hibernate).

Single Table

I will start showing the way of persisting an inheritance hierarchy in a relational model called Single Table:

@Entity@Inheritance@DiscriminatorColumn(name=account_type)public abstract class BankAccount {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	protected float amount;	...}@Entity@DiscriminatorValue(SA)public class SavingsAccount extends BankAccount {	...}@Entity@DiscriminatorValue(CA)public class CheckingAccount extends BankAccount {	@Column	private float overdraft;	...}

And the Client mapping that follows:

@Entitypublic class Client {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	private String name;	@OneToMany	@JoinColumn(name = client_id, referencedColumnName = id)	private Set bankAccounts = new HashSet();	...}

The bankAccounts mapping is defining a one-to-many association of BankAccounts that can be SavingsAccount or CheckingAccount, hence a polymorphic persisted association.

Note that the beauty here is that my original code did not change after introducing persistence to the model. This is valid for all the ways of persisting inheritance of course. My test remain exactly the same and that should be the case as Im testing business logic and ideally, the addition of persistence should not interfere with that.

This mapping will generate a single table, in this case called: bankaccount, for the entire hierarchy. It is using a column called account_type to distinguish between the two kinds of bank accounts. Based on that value, Hibernate will create the instances appropriately.
As an example, the code below creates two accounts, a client and assign the accounts to the client.

// Code snippet (1)EntityManagerFactory emf = Persistence.		createEntityManagerFactory(bd_name);EntityManager em = null;EntityTransaction tx = null;try {	em = emf.createEntityManager();	tx = em.getTransaction();	tx.begin();	Client client = new Client(aClient);	BankAccount ba1 = new SavingsAccount(350);	BankAccount ba2 = new CheckingAccount(250, 100);	client.addAccount(ba1);	client.addAccount(ba2);	em.persist(ba1);	em.persist(ba2);	em.persist(client);	tx.commit();} catch (Exception e) {	if (tx != null) {		tx.rollback();	}	throw new RuntimeException(e);} finally {	em.close();}

The execution of the code snippet (1) above, will generate a single table like below:

account_typeidamountoverdraftclient_idCAacount1250100client1SAacount2350nullclient1

Suppose the code snippet (2) below that retrieve the client1 from the database and print the total amount of money:

//Code Snippet (2)EntityManagerFactory emf = Persistence.		createEntityManagerFactory(bd_name);EntityManager em = null;EntityTransaction tx = null;try {	em = emf.createEntityManager();	tx = em.getTransaction();	tx.begin();	Client client1 = em.find(Client.class, client1);	System.out.println(client1.totalMoney());	tx.commit();} finally {	if (em != null) {		em.close();	}}

That snippet will provoke the initialization of the bankAccounts collection by executing a sql statement like the following:

    select        cliente_id,        id,        amount,        overdraft,        account_type    from        BankAccount    where        cliente_id = client1

A very simple and best performing sql statement with the drawback of a denormalized relational model with nullable columns.

Joined

For this way of mapping inheritance, each class in the inheritance hierarchy (including abstract classes) will have a table, sharing the primary key which represent the object id. The following code snippet shows how to map the inheritance in this way. Note that the difference in the mapping with the previous way is in the abstract class, in the @Inheritance annotation. The discriminator column is not needed here.

@Entity@Inheritance(strategy = InheritanceType.JOINED)public abstract class BankAccount {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	protected float amount;	...}@Entitypublic class SavingsAccount extends BankAccount {	...}@Entitypublic class CheckingAccount extends BankAccount {	@Column	private float overdraft;	...}

Now executing the code snippet (1) with our classes with the Joined mapping, it will generate the following 3 tables:

bankaccount:

idamountclient_idacount1250client1acount2350client1

savingsaccount:

idacount2

checkingaccount:

idoverdraftacount1100

And executing the code snippet (2), the initialization of the bankAccounts collection will generate a sql statement like the following:

    select        bankaccoun0_.cliente_id,        bankaccoun0_.id,        bankaccoun0_.amount,        bankaccoun0_2_.overdraft,        case            when bankaccoun0_1_.id is not null then 1            when bankaccoun0_2_.id is not null then 2            when bankaccoun0_.id is not null then 0            else -1        end as clazz_1_    from        BankAccount bankaccoun0_    left outer join        SavingsAccount bankaccoun0_1_            on bankaccoun0_.id = bankaccoun0_1_.id    left outer join        CheckingAccount bankaccoun0_2_            on bankaccoun0_.id = bankaccoun0_2_.id    where        bankaccoun0_.cliente_id = 'client1'

We now have a good normalized relational model with an additional cost when retrieving the the polymorphic association, due to the join sql operation that is required.

Table per Concrete Class

In this way of mapping inheritance, there will be a table per concrete class containing all their instance variables plus the ones that belongs to their super classes. It supports polymorphic associations only if the association is bidirectional.

Let see how to map this. In order to make the association bidirectional, the BankAccount class now contains a @ManyToOne association with the Client. The @OneToMany association defined on the Client has the mappedBy attribute to tell Hibernate which is the owning side.

@Entity@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)public abstract class BankAccount {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	protected float amount;	@ManyToOne	@JoinColumn(name = client_id)	private Client client;	...}@Entitypublic class SavingsAccount extends BankAccount {	...}@Entitypublic class CheckingAccount extends BankAccount {	@Column	private float overdraft;	...}@Entitypublic class Client {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	@Column	private String name;	@OneToMany(mappedBy = client)	private Set bankAccounts = new HashSet();	...}

Executing the code snippet (1) will generate two tables, one for CheckingAccount and another for SavingsAccount, as shown next:

checkingaccount:

idamountoverdraftclient_idacount1250100client1

savingsaccount:

idamountclient_idacount2350client1

And when executing the code snippet (2), the initialization of the bankAccounts collection will generate a sql statement like this:

    select        bankaccoun0_.client_id as client_i3_5_0_,        bankaccoun0_.id as id1_0_0_,        bankaccoun0_.id as id1_0_1_,        bankaccoun0_.amount as amount2_0_1_,        bankaccoun0_.client_id as client_i3_0_1_,        bankaccoun0_.overdraft as overdraf1_3_1_,        bankaccoun0_.clazz_ as clazz_1_    from        (select            id,            amount,            client_id,            overdraft,            1 as clazz_        from            checkingaccount        union        all select            id,            amount,            client_id,            nullif(0,            0) as overdraft,            2 as clazz_        from            savingsaccount        ) bankaccoun0_        where                bankaccoun0_.client_id = 'client1'

Note that it is performing a union with the two bank account tables. Union is probably the most expensive operation for a database engine.

I have just presented the three ways of mapping inheritance that supports polymorphic associations. My choice would be the Joined one. Because it generates a normalized relational model. In addition, note that doing operations that require traversing a persisted collection will make the entire collection to be loaded in memory. So, you can do this only if you know that the collection will be small. And if the collection is small the sql joins operation will not be expensive.

Other Way of Persisting Inheritance

The @MappedSupperclass annotation give us another way of persisting inheritance, without supporting polymorphic associations. The @MappedSupperclass is good in case you want to move a bunch of duplicated instance variables into one super class. The following sample code shows how to use it.

@MappedSuperclasspublic abstract class PersistentObject {	@Id	@GeneratedValue(generator = system-uuid)	@GenericGenerator(name = system-uuid, strategy = uuid)	private String id;	protected String getId() {		return id;	}	//needed by Hibernate	private void setId(String id) {		this.id = id;	}}@Entitypublic class SomeEntity extends PersistentObject {	@Column	private String name;	...}@Entitypublic class SomeOtherEntity extends PersistentObject {	@Column	private String otherName;	...}

This mapping will generate a relational model similar to the one that Table per Concrete Class generates. In this case, the tables generated will be:

someentity:

idname

someotherentity:

idothername

Note that the id instance variable, the mapping of it into a column and their get/set methods are only defined in the PersistentObject class. However, the id column will exist in each table generated by each Entity class extending PersistentObject.

Posted in Persistence Tagged with: Hibernate, inheritance, JPA, Persistence, polymorphism
Hibernate/JPA Transparent Persistence Posted on enrique No Comments

This is the first of a series of posts to provide an insight about Object Oriented Persistence, using an Object Relational Mapping tool like Hibernate. We will start with few concepts.

Object Relational Mapping

JPA (Java Persistence API) is the specification created by the Java Community for persisting objects in the Java Programming Language. And Hibernate ORM (Object-Relational Mapping) is an implementation of that specification.

The goal of an ORM is to let you design your application without taking care about a persistent mechanism. Design your domain model, implement it and test it, just persisting it on memory. The ORM, after configured, will take care of persist your model objects in a persistent storage (in this case a relational storage).

Let illustrate the previous sentence with an example. Suppose I have to model Departments and Employees, where each department knows their employees. I would write the following two classes:

public class Department {	private String name;	private Collection employees = new ArrayList();	public Department(String name) {		this.name = name;	}	public void addEmployee(Employee m) {		employees.add(m);	}	public int totalEmployees() {		return employees.size();	}}public class Employee {	private float salary;	private String name;	public Employee(String name, float salary) {		this.name = name;		this.salary = salary;	}	public String name() {		return this.name;	}	public float salary() {		return this.salary;	}}

And a test to cover that piece of functionality:

@Testpublic void a_new_employee_is_added_then_it_increments_the_total() {	Department rockAndRoll = new Department(Rock And Roll);	Employee angus = new Employee(Angus Young, 1239f);	rockAndRoll.addEmployee(angus);	Assert.assertEquals(1, rockAndRoll.totalEmployees());}

And ORM like Hibernate will let you write something like the test above and make the relation between the employee angus and the rockAndRoll department persistent, isnt that great?

You may be asking, I dont have to deal with the JDBC API ? I dont have to write any SQL Statement ? No! you can just write code like this:

	department1.addEmployee(new Employee(José, 10503f));

then José will be persisted and be part of department1.

The real beauty of an ORM is the transparent persistence that provides, which will let you write plain Java objects and make them persistent with little work.

Transparent Persistence

To understand how transparent persistence works, we have to understand the following concepts. The first one is a concept called Persistence Context. The Persistence Context is the place used by the ORM to keep track of your Objects changes in order to persist them at a later point. In JPA this context is managed by the javax.persistence.EntityManager class. Each Java Object in a persistence context will have one of these states:

new, or transient: the object has just been instantiated and is not associated with a persistence context. It has no persistent representation in the persistent storage.persistent: the object is associated with a persistence context and has representation in the persistent storage.detached: the object is no longer associated with a persistence context (usually because the persistence context was closed).removed: the object is associated with a persistence context, however it is scheduled for removal from the persistent storage.

The other important concept is called Persistence by Reachability. Which states that any transient object that gets related to a persistent object, will become persistent too.

These two concepts implemented make the so called Transparent Persistence possible.

Lets put these concepts in code. The following code block defines the persistence context, and illustrate the persistence by reachability.

	EntityManager em = //obtain the EntityManger instance	EntityTransaction tx = null;	try {		tx = em.getTransaction();		tx.begin();		Department dept1 = em.find(Department.class, department1);		dept1.addEmployee(new Employee(José, 10503f));		tx.commit();	} catch (Exception e) {		if (tx != null) {			tx.rollback();		}		throw new RuntimeException(e);	} finally {		em.close();	}

On line 7, Im getting the Department department1 from the persistent storage and on line 8 just append a new employee to it. Due to department1 is in the persistent state, by reachability the transient instance of Employee (José) will be persisted and attached to the department.

A similar scenario that also illustrate the two concepts described above is when having two transient objects, Department and Employee, and the Employee has a relation (or is part of) to the Department. If I persist the Department, then the Employee will be persisted too. Code shown below:

	//start persistence context	...	Department dept1 = new Department(department1);	dept1.addEmployee(new Employee(José, 10503f));	em.persist(dept1);	...	//close persistence context

Below are some more examples that continue demonstrating the beauty of the transparent persistence. Changing the name of a department:

	//start persistence context	...	Department dept1 = new Department(department1);	dept1.setName(anotherDepartmentName);	...	//close end of persistence context

Removing an employee from a department:

	//start persistence context	...	Department dept1 = // retrieving from the storage	dept1.removeEmployee(new Employee(Javier, 4569f));	...	//close end of persistence context

Lets write something a bit richer. Suppose each department gains 5 points each time a woman joins them and 3 points for men and subtract 5 points when an employee leaves them. I would change the Department class in the following way:

public class Department {	...	private int points;	public void addEmployee(Employee e) {		points += e.points();		employees.add(e);	}	public void removeEmployee(Employee e) {		points -=  e.points();		employees.remove(e);	}	...}

Now, if I add an employee to a department:

	//start persistence context	...	Department dept1 = // retrieving from the storage	dept1.addEmployee(new Employee(Julio, 6205f));	...	//close end of persistence context

in addition to persist the new Employee and the relation with the department, it will also persist the new points obtained by adding employees to the department. It will be done executing two SQL statements wrapped in a transaction. Something like:

insert into employees values(Julio, 6205f, department1);update departments set points = ? where id = department1;

That was transparent right? You can visualize all the work done by the ORM for you. This means that you can focus the effort on make a good Object Domain Model (and with good I mean, with business logic inside and not an anemic model), test it on memory, get a high test coverage, and let the ORM to take care of the persistence.

The support of Transparent Persistence is what makes Hibernate an invaluable tool.

Posted in Persistence Tagged with: Hibernate, Java Objects, JPA, ORM, Peristence
Eclipse and PHP Posted on enrique No Comments

After installing LAMP, lets configure Eclipse for PHP development.

1. Install Eclipse

Download Eclipse latest version, from here. You just need the Eclipse Standard version (if you only want to develop PHP Web Applications). At the time of writing this post the latest Eclipse version is Luna. Once downloaded, start it up. If you try to create a new project, you will see that only Java projects are available. Now, lets enable PHP projects.

2. Enable PHP in Eclipse

In Eclipse, go to the Help menu, then Install New Software. On the Work with: input field, type this URL: http://download.eclipse.org/releases/luna. This will display a list of different tools to install. Under the Programming Languages category, you will find PHP Development Tools (PDT), check it and click Next to follow the wizard to install it.

Restart Eclipse and once is up you will note that in the Open Perspective now you have PHP as an option. In addition, in the menu Windows Preferences, you will see a set of PHP options too.

3. Enable Users Home Directory

As PHP runs using Apache, you will need to create the project in a directory that Apache can see. There are many ways of doing this, but one I like is to use the {user.dir}/public_html that Apache supports pretty well and is accessible from a browser using http://localhost/~{user.dir}.

To enable this do the following:

Go to the mods-enable directory in the Apache home directory, usually under /etc/apache2/mods-enable.Run the following commands:sudo ln -s ../mods-available/userdir.loadsudo ln -s ../mods-available/userdir.confLastly, to enable the PHP interpreter under the {user.dir} directory, edit the /etc/apache2/mods-enabled/php5.conf file and comment out, using #, the lines below:IfModule mod_userdir.c
Directory /home/*/public_html
php_admin_flag engine Off
/Directory
/IfModule
restart apache: sudo service apache2 restart

4. Set up a PHP Project
On Eclipse go to File-New-PHP Project. A New PHP Project window will open. On the Contents section, choose the radio button that says: Create Project at Existing Location (from existing source). In the Directory input choose your {home_directory}/public_html/{project_name}, and press finish. An you are done. To test it, just create a PHP file, called test.php, like this:

?php echo bHello World!/b;?

save it, and in the browser go to the following URL: http://localhost/~{user_name}/{project_name}/test.php. If you see Hello World! in bold, then you are done!.

Posted in DevOps Tagged with: Eclipse, PHP
Older posts My book has been published! Recent Posts Understanding React Coding an Architecture Style React: Thinking in Self Contained Components Elegant Objects: Book Review Object Oriented Frameworks: Concepts, White Box and Black Box Examples Hibernate/JPA Transparent Persistence II Lambda Expressions in Java, a Concrete Example Hibernate/JPA Inheritance and Polymorphic Asociations Hibernate/JPA Transparent Persistence Tag CloudAngularJSarchitect rolearchitectureClean Architecturecompilersdebugdesignduplicated codeEclipseFrameworksgradleHexagonalHibernateinheritanceJava 8Java ObjectsJavascriptJPALambdaLAMPlegacy codemanage dependenciesMicroservicesModular ArchitectureObject Oriented ParadigmObject Oriented ProgrammingOODOOPORMpage objectPeristencePersistencePHPpolymorphismPorts and Adaptersprogramming language implementationseleniumSingletontestable codetestingAll Posts September 2021 December 2020 July 2018 July 2017 June 2016 April 2016 November 2015 July 2015 February 2015 January 2015 August 2013 April 2013 December 2012 October 2012 April 2012 March 2012 December 2011 July 2011 June 2011 May 2011 2021 Copy/Paste Is For Word Responsive Theme powered by WordPress

TAGS:Is For Copy Paste Word and more Software 

<<< Thank you for your visit >>>

Websites to related :
Divxtotal OFICIAL | Descargar To

  keywords:
description:Somos DivxTotal, la web OFICIAL donde podrás descargar peliculas torrent, además de series en Castellano y Latino. Los último

Hicks with Sticks

  keywords:
description:
HomeCalendarWeek

Webrate.org - Rate the web

  keywords:
description:
WEBrateAbout UsAccountLog InSign UpPINGTracerouteWhoisGeolocationDNS LookupOnline StatusPunicode converterSSL CheckerHTML Valid

Kataweb.it - Blog - Aromuni (e n

  keywords:irredentismo italiano,Istria italiana,Lingue neolatine dei Balcani,Dalmazia veneziana ed italiana,Venezia Giulia italiana
description:

Fight Gravity Fitness- Rinos fit

  keywords:
description:Fitness Studio located in the Rino Art District of Denver, CO. We offer Personal Training and Small Group Classes such as TRX, C

Trump Golf Links at Ferry Point

  keywords:members, interactive, website
description:Trump Golf Links at Ferry Point is New York City’s premier links style golf course designed by Jac

atproxynet

  keywords:
description:

Cre8ivedesignagency : Cre-8ive D

  keywords:
description:
Web Analysis for Cre8ivedesignagency - cre8ivedesignagency.com

Boutique Hotels in Chiangmai, Th

  keywords:
description:
Boutique Hotels in Chiangmai, ThailandAlmost people around the world love to visit this land. In the north of Thailand, Chiangm

Welcome to Lolitas Lounge... | l

  keywords:
description:
Skip to main content

ads

Hot Websites