Category Archives: Uncategorized

React.js and MobX: Escape the Redux trap

I have seen React in action for the first time in relatively complex legacy application. There were some attempts to develop new functions using React and, of course, Redux. Because everyone is using that combination. It is the clear, cool way. Hm…

notsure

I fell in love with React quickly but with Redux it was not so hot. Alex Dixon wrote great article about his problems with Redux and functional programming in JavaScript. TLDR:

  • You never know whether you have plain JS object or Immutable.js object under your hands.
  • If you are not using Immutable.js then you still should know whether object you have can be mutated or not.
  • In every file you have to manually import libraries like Immutable or Lodash.

I had those issues plus:

  • It was real pain to describe complex change you would like to perform on immutable state within store. Like add 6th item into array, remove 3 different keys from map, etc.
  • For doing even simple things you have to modify code in multiple files. One often do a hack instead of nice solution.
  • Problems with using multiple stores. I still had feeling that I should not store state of form in global store. Local data should be local, right?
  • Same store is used during navigation without page reload. It is hard to clean everything properly.
  • React-Redux library is doing incredible magic I was never able fully understand.
  • Using Promises just made thing worse.
  • I still had feeling that if I have to reorganize store structure I will got mad.

Then, out of blue sky, I have found MobX. And I realized that I found great React’s partner.

thinking

I can have multiple stores – one that holds application state (selected language, global formatting settings), second that holds form state and handles communication with server, third for caching currency conversions, etc. This stores are available through React context – therefore their presence is checked by React using contextTypes definition. You can freely move components in hierarchy as long as you assure that proper stores are in context.

I still have certain level of immutability because MobX checks that no change is done during processing previous change.

Adding functionality is deadly simple. You have two classes – component and store.

Because store is single purpose and is object of class, it is quite easy to determine what you can do with it. If there is method, try to call it. Compare that with searching for proper Redux action.

Despite I have never use truly functional programming language I highly utilize lambda expressions (Ruby, Java 8, JavaScript), enjoy passing function as parameter and since then my usage of class inheritance dropped by 90% ūüôā In Java I employ Immutables, Jooq and high percentage of methods I write are static ones. So I consider myself open minded in functional programming area. That hopefully gives me some credit to have strong feeling that combination of React and Redux is simply wrong. MobX and React, on the other hand, are just great combination.¬†At least for me ūüėČ

 

 

 

 

Lambda: simplify method calls

There is important part of good programmers skills – ability to detect duplicity. Over years I have developed it for various situations. But recently I have added new situation – duplicity in calling methods with many parameters. And especially with many parameters in local scope. Take a look on following example:

package test;

import java.awt.Graphics;

public class NaiveRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		if (paramA<100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.2);
		} else {
			renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Obviously, there is huge duplicity in renderSubpart calls. Calculation of some parameters is repeated many times. Let’s improve it:

package test;

import java.awt.Graphics;

public class BetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		int calculatedA = paramA+42;
		
		boolean newParamB = !paramB;
		double newParamC = paramC*22.3;
		String newParamD = paramD+" oh";
		
		if (paramA<100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -1.0);
		} else if (paramA<10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, -0.2);
		} else if (paramA==0) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		} else if (paramA>100) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 1.0);
		} else if (paramA>10) {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.2);
		} else {
			renderSubpart(g, newParamB, newParamC, newParamD, calculatedA, 0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

Hm. So we have bloated scope by three new local variables. And we have to name it. Plus there is still problem with many similar calls to the renderSubpart. But only one parameter varies. Let’s improve that:

package test;

import java.awt.Graphics;

public class EvenBetterRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		double calculatedB;
		
		if (paramA<100) {
			calculatedB = -1.0;
		} else if (paramA<10) {
			calculatedB = -0.2;
		} else if (paramA==0) {
			calculatedB = 0.0;
		} else if (paramA>100) {
			calculatedB = 1.0;
		} else if (paramA>10) {
			calculatedB = 0.2;
		} else {
			calculatedB = 0.0;
		}
		
		renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So now we reduced number of added local variables to one. Great, but I don’t like decoupling of condition and method call. Block of condition just set calculatedB which is later used for calling renderSubpart. Can’t we improve that?

I realized that I can wrap parameters into local lambda function like this:

package test;

import java.awt.Graphics;
import java.util.function.Consumer;

public class LambdaRenderer {
	
	public void render(Graphics g, int paramA, boolean paramB, double paramC, String paramD) {
		Consumer<Double> renderSubpartLambda = (calculatedB)->renderSubpart(g, !paramB, paramC*22.3, paramD+" oh", paramA+42, calculatedB);
		
		if (paramA<100) {
			renderSubpartLambda.accept(-1.0);
		} else if (paramA<10) {
			renderSubpartLambda.accept(-0.2);
		} else if (paramA==0) {
			renderSubpartLambda.accept(0.0);
		} else if (paramA>100) {
			renderSubpartLambda.accept(1.0);
		} else if (paramA>10) {
			renderSubpartLambda.accept(0.2);
		} else {
			renderSubpartLambda.accept(0.0);
		}
	}
	
	public void renderSubpart(Graphics g, boolean paramB, double paramC, String paramD, int calculatedA, double calculatedB) {
		//...actual code
	}
}

So I have defined renderSubpartLambda that receives single varying parameter and fill all other parameters that shares value over all calls. This is possible because Lambda function, unlike methods, have access to the local scope (parameters, local variables). Lambda is then executed from exact position withing condition blocks with only with single important parameter.

This technique is usable in all situations where it would be hard to define helper method because number of passed parameters would be too high. Btw. this solution is language independent – I have used it in JavaScript too.

jOOQ & Immutables & Jackson: Great together

I really like Java. But only the plain one. I hate all the enterprise frameworks like Spring, Java EE or Hibernate. I consider them enormous and verbose. It my eyes usage of them leads to corporate applications:

  • Application so complex that it is hard to avoid duplicity in code because everone is afraid to change anything.
  • Applications that does not adapt to company needs so company needs to adapt to applications.
  • Applications that is not possible to maintain and improve any more.

Feels like hell for me ūüôā I prefer small, single purpose libraries. For that reason¬†is Navigo3 using¬†multiple libraries for data.

For building access classes to the database we are using jOOQ. You just point it to database and it will generate code for handling it. We are doing that during every Gradle build. If you then use generated code for data access it is automatically verified by compiler. Compiler will complain¬†if anything is wrong – data type was changed, column removed, etc. Because objects read from database can be basically plain POJOs, they may be directly serialized into JSON and used in REST API. I don’t need to say how easy is to find references to certain object, for example column when compared to SQL strings in code…mainly for fields like ‘createdAt’ which is in all tables.

For effortless data structures (POJOs) we are using Immutables. It is matter of seconds to prepare data class with all necessary access methods or builder. No need to write any getter/setter anymore! This is handy mainly for programmers who like functional programming principles. Data are data and they are shaped by functions. Also since I am using Immutables I use static methods much more than before. The reason is that can create methods that returns complex output easily. Formerly I preferred to keep much richer internal state of objects and methods on that object were modifying it instead returning value. This leads to much easier refactoring Рstatic method is so much easier to move that instance method!

For JSON (de)serialization we are using Jackson. Both jOOQ and Immutables have embedded great support for it. It is even possible to serialize combination of both.

Consider this example: I have REST API method that should return information about person РGET /person-info/12345. But not only that, I would like to return also information about company assigned to person Рfor example to avoid second request during rendering person detail in React.js.

So task is to compose DbPerson and DbCompany classes (generated by jOOQ) into single class that can be (de)serialized. Easy done as nested interface of REST handler:

class Handler {
	@Value.Immutable
	@JsonSerialize(as = ImmutablePersonAndCompany.class)
	@JsonDeserialize(as = ImmutablePersonAndCompany.class)
	public interface PersonAndCompany {
		DbPerson getPerson();
		DbCompany getCompany();
	}

	...
}

So you get generated ImmutablePersonAndCompanyBuilder, fill it with both objects loaded by jOOQ and serialize it using Jackson. Task accomplished.

Using this technique it is easy to add fields into data. For example adding information about address can be done by adding single line.

We also utilize POJO nature of this libraries for documentation. It is quite easy to traverse definition of such classes using reflection and automatically generate documentation from it. Such documentation is always up-to-date without any manual actions.

meta.png

React.js components with embedded styles

You have probably already seen global CSS files with thousands of lines that may influence anything. Change is too dangerous so you just add new rules. To the point everything must be rewritten.

I love React’s ability¬†to build reusable components. Write once, put anywhere you like. This rule does not apply just¬†for JavaScript, it may apply for CSS too. Did you know that you can use¬†post-css with autoprefixer¬†to autoprefix rules from CSS/SASS/LESS file? So every require of such file prepares class names that does not clash with anything else (like style__item___3dKqL).

That way you can prepare components that contains embedded styles that applies only for them. No complex CSS selectors are required – just use plain names:

embedcss

At the same time you can import application wide constants using SASS so you do not lose ability to set colors, sizes, … in single place.

Usage in code is simple:

code

(btw. to avoid join operation you can use classnames lib)

React.js: Build your components catalog

When you design large information system UI it is important to stay uniform. Nobody likes when pages varies in appearance or behavior. Typically it is necessary to write UI/UX design manual that describes allowed tools and techniques.

I was thinking about ways how to prepare list of UI components. So we can pick component when creating new functionality and avoid writing new. I was considering Confluence but it would need extra effort to keep list of components up to date.

Then I got it:¬†We can employ¬†React’s ability to prepare reusable components and easily compose catalog. Here is our:

catalogue

Catalog is embedded in application but visible only to developers. Every component¬†is shown in typical situation (to have concise list) and it may be expanded (Date component above) to be seen in various¬†configurations – error state, different input values, empty, …

We are using physics particles categories for components and each category has own section:

  • Quarks – simplest components that only use passed properties (Button, FormattedInput, …)
  • Atoms – components that call server API or are attached to forms or application state (ContextMenu, CurrencyInput)
  • Molecules – larger function blocks that contains application logic (UserForm, TasksList)
  • Pages – ok, this is not physics category ūüėČ

Each level uses components from upper levels. And each level is harder to instantiate outside its real usage. According to my experience it is quite feasible to have Quarks and Atoms in catalog. I believe that MobX is helping here but I have no long term experience with Redux. Molecules depends too much on API and application data so it would be hard to mock it.

You can also think about catalog as mild form of test. You are testing that:

  1. You can reuse component, there are no hidden dependencies
  2. There is no clash among components when used together
  3. All components basically works

 

Embedding React into legacy web pages

The product I am enthusiastically working on – Navigo3 – was historically written as combination of XSLT and JSP. Do you remember XSLT?

meme

Short time before I joined it it was decided that is should be remade in React.js. It was great decision but transition is not that easy.

Because Navigo3 is in production usage we have to transform from XSLT to React step by step. Some pages are that complex that it would be handy being able to combine XSLT and React on single page. Typically it is required¬†on pages that combine many types of information – dashboards. A few graphs, tables, list of tasks, …¬†It would be hard to rewrite all at glance. But rewrite each one is quite simple.

dashboard.png

At the same time we have new pages which are written completely in React and uses hashtag navigation. In main entry file index.js there is redux-router hierarchy and it expects that it runs on purely React page. This actually does not match with demand to embed some components into JSP/XSLT static page with classical URL navigation, right?

But I would like to share React components between brand new react pages and legacy XSLT pages! And at some moment just compose React page from existing components and abandon legacy ones. So how to do that?

  1. Prepare second entry file (like indexLegacy.js) and prepare build task for it (we use Webpack).
  2. Insert result bundle file via <script src=’bundleLegacy.js’/> into JSP/XSLT pages right before </body> element.
  3. In JSP/XSLT/whatever page put empty DIV tag in place where React components should be rendered and give it nice id or class name – like “hack_legacy_tasks_list”.
  4. In new entry file write logic that basically perform list of IFs that fills prepared DIVs – but only if they exists:
    • Check if desired element with unique name is presented in DOM (we use jQuery for that)
    • If it is presented render desired component into it (using React.render(<MyComponent>, element))
  5. Of course list of IFs can be replaced by some metadata and have generic code that process them.
  6. If component needs some context, you can wrap it. But you have to do it for all of them separately. They do not share tree hierarchy (React instance).
  7. If all components on page needs to share something, it can be instantiated in entry file and passed to all components.

That’s it. Lets sum up some advantages:

  • Components are shared between new shiny React pages and legacy pages.
  • There is single entry bundle for legacy stuff. If your legacy pages includes shared footer file you can place reference to legacy bundle there. Because unique ids/classnames are used for binding, it should not harm any existing content.
  • You may place multiple components per legacy page – insert multiple DIVs.

React.js FTW!

Selenium: Get rid of logs in Eclipse

Selenium for Java by default uses java.utils.logging (JUL) infrastructure for logging. During development I have seen logs like:

Nov 21, 2016 8:16:32 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Nov 21, 2016 8:16:34 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS

I am using log4j2 through slf4j and just creating logger in configuration file did not worked. Solution was:

1. Add Gradle/Maven dependency to log4j-jul

2.¬†As documentation says¬†set system property “java.util.logging.manager” to “org.apache.logging.log4j.jul.LogManager” either via -D parameter or in Main like:

public static void main(String[] args) {
  System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
  ...
}

It must be set BEFORE any call to log4j!!!

3. Define log4j logger:

<Logger name="org.openqa.selenium" level="warn" additivity="false">
 <AppenderRef ref="console"/>
 </Logger>

And unnecessary logs are gone!