Do we really need JQuery validator plugin?

The more I need to do some HTML client side validation the more I am asking myself whether we need a validation framework or not.

Until now I have not used any specific validation framework. But now I have to because I do not want to take care of simple syntax level (number field could accept numbers only, etc.) field validation.

First of all I have used developers best friend: Google . I have found numerous validation framework for JQuery (just have a look at the Google search result in the previous links).

I have check many of them and found that most of them are too complicated to my need (remember, I need simple syntax check because complex validation is made on server side).

The client side I wanted to make something simple and declarative:

  <form:input path="duration.hour" cssClass="form-control" maxlength="2" data-validation-pattern="^([01]?[0-9]|2[0-3])?$"/>

This is a simple Spring MVC input field. I have just introduced a custom data attribute called data-validation-pattern and the value is the regex pattern I want the check actual value test against. This specific example is checking an optional field which is accepting hours (0-23) of a day.

The expected behavior is that when any error happens I do not want to submit the form.

  $('#mrs_form').submit(function(event) {
    var validator = new MeetingValidator('#mrs_form');

    if (!validator.checkValidity()) {
      event.preventDefault();
    }
  });

So far, so good.

Let’s implement the validator:

  function MeetingValidator(form_selector, options) {
    "use strict";
    var DEFAULT_OPTIONS = {
      on_finished : function() {}
    };
    options = $.extend({}, DEFAULT_OPTIONS, options);
    var issues = [];

    /**
     * @return false if there are validation errors
     */
    function checkValidity() {
      checkRegexPattern();
      options.on_finished(issues);
      return _.isEmpty(issues);
    }

    function checkRegexPattern() {
      $('[data-validation-pattern]', form_selector).each(function() {
        var name = $(this).attr('name');
        var patt = new RegExp($(this).data('validation-pattern'));
        var value = $(this).val();
        if (!patt.test(value)) {
          issues.push({
            kind : 'pattern',
            name : name,
            value : value
          });
        }
      });
    }
    MeetingValidator.prototype.checkValidity = checkValidity;
  }

Cool, isn’t it? In function checkRegexPattern there are 4 effective lines of code which is dealing with all what I need.

You could say: “But it is not enough I need to report errors to the user”. And I will say: “Yes, you are right!”

And here is the weakness of many validator plugins. They are not so flexible how to report the error. If you have a look at the code it has an optional input parameter called options with one relevant attribute called on_finished which is intended to be a function and called at the end of the validation process.

Let’s see in practice:

  $('#mrs_form').submit(function(event) {
    var validator = new MeetingValidator('#mrs_form', {
      on_finished : on_validation_finished
    });

    if (!validator.checkValidity()) {
      event.preventDefault();
    }
  });

  function on_validation_finished(issues) {
    _.each(issues, function(issue) {
      $('input[name="' + issue.name + '"]').parents('.form-group').addClass('has-error');
    });
  }

Function on_validation_finished is simply mark the field (using bootstrap styles).

Enjoy it!

Aug 04, 2014

Thinking about - week 31

Stop Unit Testing Database Code

Writing tests that use an actual database is hard.

  • that results from tests against your test system have (almost) no meaning
  • that your tests will not cover some of the most complex aspects of your productive system
  • that you will start spending way too much time on tweaking tests rather than implementing useful business logic

Databases couldn’t be any less stateless. The whole idea of a database is to manage state. And that’s very complicated and completely opposite to what any unit test can ever model

My database unit testing is about testing SQL syntax only.

Flyway and jOOQ for Unbeatable SQL Development Productivity

  1. Database increment
  2. Database migration
  3. Code re-generation
  4. Development

Good combination of tools. I would like to use. But those Oracle DBA guys do not like using tools which are not used to (even if it is more advanced)

TDD != Unit Tests (and vise versa)

The post itself is not about this topic but the reaction on depate made around Test-induced design damage started by DHH.

The “Just In Time” Theory of User Behavior

I’ve long believed that the design of your software has a profound impact on how users behave within your software. But there are two sides to this story:

  • Encouraging the “right” things by making those things intentionally easy to do.
  • Discouraging the “wrong” things by making those things intentionally difficult, complex, and awkward to do.

The purpose of locks, the locksmith said, is to protect you from the 98% of mostly honest people who might be tempted to try your door if it had no lock.

10% of people will never steal, 10% of people will always steal, and for everyone else … it depends.

most people will consistently and reliably cheat “just a little”, to the extent that they can still consider themselves honest people.

Once upon a time I have made a test whether I am a good man. For example a good man does not steal. And first question: Have you ever taken a pen from your workplace for private use? Of course I did….

a simple reminder at the time of the temptation is usually all it takes for people to suddenly “remember” their honesty.

You do it by showing them …

  • the minimum helpful reminder
  • at exactly the right time
Jul 28, 2014

Computer has no brain

Computer has no brain

Jul 21, 2014

foldLeft implementation

foldeLeft (folding in general) is one of the most powerful functional construct. Clean, elegant and generic.

Almost all functional operations can be built on top of the fold functions. So you need to have one. Once you have foldLeft you got a bunch of “operation” in addition (see later).

A few example how foldLeft can be used:

I had a continuous need of implementing some min and max on collection and I wanted to add my functional FIterable . So I did.

  public interface F2<X, Y, Z> {
    public Z f(X p1, Y p2);

    public static interface Simple<T> extends F2<T, T, T> {
    }

    public static interface Collector<V, S> extends F2<V, S, V> {
    }
  }

//....


  public <C> C foldLeft(C init, F2<C, T, C> reducer) {
    for (T i : this.iterable) {
      init = reducer.f(init, i);
    }
    return init;
  }

//...

  @Test
  public void foldLeft() throws Exception {
    Integer res = FIterable(IList(1, 2, 3, 4)).foldLeft(0, new F2.Collector<Integer, Integer>() {
      @Override
      public Integer f(Integer p1, Integer p2) {
        return p1 + p2;
      }
    });
    assertEquals(10, res.intValue());

    String longestString = FIterable(IList("aaaaa", "a", "qqqqqqqqqqq", "bb")).foldLeft("", new F2.Simple<String>() {
      @Override
      public String f(String p1, String p2) {
        return p1.length() > p2.length() ? p1 : p2;
      }
    });
    assertEquals("qqqqqqqqqqq", longestString);
  }
Jul 14, 2014

Inner class for stepdown rule

Inner and nested classes (static or not) are not only for passing as anonymous classes for other component or not to expose special derivatives to the public. It is also useful to organize your code layout to improve readability.

I present two usage of class to improve readability:

Group methods together

One the Clean Coders videos and also in the Clean Code book there is a specific section about functions and the way to organize the layout of them (look for The Stepdown Rule in section Functions).

The summary of this concept is to organize code the following way:

Applying all other rules in Clean Code it is a meaningful advice. For example when considering the rule of a function is doing one thing and a function has one abstraction level only we must have sever (private) method in the class. It is clear that the file can be difficult to review. Such a layout makes easy to identify which lower level function is belonging to which higher level function. So you could skip them if you are not interested in the lower level stuffs.

But modern IDE-s are not supporting this kind of formatting. When let IDE formatting the code all unction will be indented to the same level. Except….

Except we are introducing some kind of extra block which will be indented. And here we can use a nested class.

Before code

  void main(){
    f1();
    f2();
  }
  void f1(){...}
  void f11(){...}
  void f12(){...}
  void f2(){...}

After (introducing only one layer of grouping):

  void main(){
    new F1().f1();
    new F2().f2();
  }

  private class F1{
    void f1(){...}
    void f11(){...}
    void f12(){...}
  }
  private class F2{
    void f2(){...}
  }

Simplifying parameter passing

In service centric code base (like the one easy to make when using Spring , or simply a legacy code to take care ) you might start calling a service method with a small number input parameter which is increasing as we are going deeper and deeper in the call stack.

Example:

  void main(String in){
    ...
    f1(in, new List());
    ...
  }

  void f1(String in, List collector){
    ...
    f2(some_other, collector, Option.WHATEVER);
    ...
  }
  ...

And here it is an other case of using inner classes. Their only purpose is to make parameters class variable and simplify method calls.

  void main(String in){
    ...
    new F1(in, new List()).f1();
    ...
  }

  private class F1{
    String in;
    List collector;
    Object some_other;
    Option whatever = Option.WHATEVER
    // constructor are not included in the sample. 
    
    void f1(){
      ...
      f2();
      ...
    }

  }
  ...
Jul 07, 2014

JUnit IgnoreRest

Given a scenario that you do not want to run all you test in a test case. For whatever reason you want to run only some of them.

For example: when developing and you find a failing test and when investigation you want to avoid the noise what other test runs are generating (e.g. logging output).

Simple, built in solution is to @Ignore all other but the relevant test case

  @Test
  @Ignore
  public void test1(){...  }
  @Test
  @Ignore
  public void test2(){...  }
  @Test
  public void test3(){...  }

Of course it is extremely uncomfortable to do especially when having sever dozens of test methods.

A few days ago I have run into a special annotation called @IgnoreRest in Spock . It simply takes the marked test and executes only that one. All other is ignored.

Of course there is no similar in “standard” JUnit .

How it should look like (identical to the previous sample):

  @Test
  public void test1(){...  }
  @Test
  public void test2(){...  }
  @Test
  @IgnoreRest
  public void test3(){...  }

Without implementation I had to develop myself. There were many options to implement:

There is one single issue which makes this implementation incomplete: ignored test are not marked as ignored.

At the moment in JUnit version 4.11 there is not way to use RunNotifier (that is the way IDEA is able to display ignored test properly). At the moment the official answer is to use Assume. Once an assume exception is raised JUnit is ignoring the result but not calling RunNotifier as in case of @Ignore. So even if the solution is working properly IDEs are not displaying it properly so it is much difficult to notice if you forget to clean up @IgnoreRest.

NB: All source is available on Github in package eu.qualityontime.test

A specific test case

  @Rule
  public IgnoreRestRule rule = new IgnoreRestRule();

  @Test
  public void test1() throws Exception {
    assertTrue(false);
  }

  @Test
  public void test2() throws Exception {
    assertTrue(false);
  }

  @Test
  public void test3() throws Exception {
    assertTrue(false);
  }

  @Test
  @IgnoreRest
  public void test4() throws Exception {
    assertTrue(true);
  }

The marker IgnoreRest

  @Retention(RetentionPolicy.RUNTIME)
  @Target({ ElementType.METHOD })
  public @interface IgnoreRest {}

IgnoreRestRule

  
  import java.lang.reflect.Method;
  import org.junit.Assume;
  import org.junit.rules.TestWatcher;
  import org.junit.runner.Description;
  import org.junit.runners.model.Statement;

  public class IgnoreRestRule extends TestWatcher {

    @Override
    public Statement apply(Statement base, Description description) {
      if (isIgnorable(description)) {
        return new Statement() {
          @Override
          public void evaluate() throws Throwable {
            Assume.assumeFalse("IgnoreRest", true);
          }
        };
      }
      return super.apply(base, description);
    }

    private boolean isIgnorable(Description description) {
      return hasIgnoreRestAnnotation(description) && null == description.getAnnotation(IgnoreRest.class);
    }

    private boolean hasIgnoreRestAnnotation(Description description) {
      Class<?> c = description.getTestClass();
      for (Method m : c.getDeclaredMethods()) {
        if (null != m.getAnnotation(IgnoreRest.class)) {
          return true;
        }
      }
      return false;
    }
  }

Jul 03, 2014

Measure it

We find no sense in talking about something unless we specify how we measure it. A definition by the method of measuring a quantity is the one sure way of avoiding talking nonsense — Sir Hermann Bondi

Jun 30, 2014

Delete your Tests

Tests, like any code, should be deleted when their cost exceeds their value.

TO be deleted:

Unneeded Tests

Documentation and Duplicating Implementation: very declarative code which has little behaviour to test, and with excessively mocked-out code where the tests become a specification of the implementation.

Highly declarative tests are SQL verification tests too.

Tests can also be made redundant by the type system. Simple tests on preconditions or valid inputs to methods can often be replaced by preconditions the type system can enforce. e.g. if you have 3 methods that all expect an argument that is an integer between 1 and 11 why not make them accept an object of a type that can only be between 1 and 11? While you’re at it you can give it a more meaningful name than integer. onChange(VolumeLevel input) is more meaningful than onChange(int volumeLevel) and removes need for tests at the same time.

Is the test testing desired behaviour, or behaviour that’s really just a side effect of the chosen implementation approach? Does the tested behaviour still match what customers and or users want now? Usage patterns change over time as users change, their knowledge of the software changes, and new features are added and removed.

Speed is one of the most important attributes of tests to consider when evaluating their value. Fast tests are valuable because they give us rapid feedback on unanticipated side effects of changes we make

any change you made broke hundreds of tests, regardless of whether it changed any behaviour? These brittle tests impose a significant cost on the development of any new features, performance improvements, or refactoring work.

Non-deterministic tests have a particularly high cost.

Original

Jun 23, 2014

Hogyan csökkentsd felére a reggeli üvöltözést a gyerekekkel? - Tudatos Vezetess

Az egyik a reggeli ellenőrzőlista, ami egy nagy táblán található. Ahogy az egyes családtagok végeztek a reggelente elvégzendő apró feladatokkal a reggelitől a fogmosásig, mindenki kipipálgathatja az egyes tevékenységeket (felhatalmazás, felelősségvállalás, mindenki számára látható visszajelzés a haladásról).

Egy másik gondolat a heti rendszerességű családi megbeszélések (kb. retro-k) rendje, ahol közösen összegyűjtik, mi ment jól azon a héten, mi nem ment jól, és mire szeretnének a következő héten fókuszálni.

Eredeti

Hivatkozott TED

Jun 16, 2014

Functionals - Toolbox

Functionals? Well. Almost.

Current topic is the AppCollections (and its friends) and package eu.qualityontime.functionals.

AppCollections

It is a utility function collection of some collection related fuctions. It can be called helper class.

  1. simple wrapper around existing helper methods (mostly related to functional helpers)
  2. factory methods of certain collection implementations: Map(), IMap() etc.
  3. functional helpers: sort, find, etc.
  4. non existing helpers or null-save helpers: e.g.: isEmpty

Factory methods

Example: Map(), IMap(), List(), IList()

One of the most boring programming task is to write and read something like new ArrayList<Some>(). It is full of noise:

Alternatives: Guava have similar factory methods in Maps, Lists, etc classes. But I do prefer List over newArrayList() and IList(...) over ImmutableList.of(...).

The advantages of using simple factory method is trivial once you are composing them:

  Map<String, Foo>  t1= new HashMap<>();
  t1.put("some", ....);
  List<Some> temp = new ArrayList<Some>();
  temp.add(...)
  ...
  Other o = new Other();
  o.setSomes(temp);
  return o;

vs.

  Other o = new Other();
  o.setSomes(List(Map("some", ...),...));
  return o;

Non-existing helpers

Simplest example: isEmpty

Implementation:

  public static boolean isEmpty(Collection<?> coll) {
    return (coll == null || coll.isEmpty());
  }

There is no trick. There is no any special code behind. It is simply as it is: null save helpers which does not exists in standard JDK.

Alternatives: Commons Collections has similar functionality. But it is possible that you do not want to have certain dependencies when you plan to use a few helper method only.

On the other hand dependencies like Commons Collections , Commons Lang , Guava are never “real” dependencies. They are just extensions on the weak JDK java.util package.

Functional helpers

Once you get used to Functional Programming paradigm you will change your style of code. For more info you must read Guava Explained . Similar implementation is available in Commons Collections too.

But why do I need wrapper?

First of all you do not need it. You should develop a small wrapper around collections and using it. See later in description of package eu.qualityontime.functionals.

If you are not developing any wrapper you still have some advantages over using “plain” libraries. (even if I have reasoned against in the previous section).

Functional package

Package eu.qualityontime.functionals:

F prefix means functional. All these classes are wrapper around the appropriate type and delgate all method call. And as an addition it is extending them by few useful functional stuff.

What does the following code do?

  List<Todo> todos = ...
  Predicate<Todo> completed = ...
  Function<Todo, List<User>> assignedUsers = ...
  Function<User, Long> nationality_id = ...
  Function<User, Map<String, Object>> to_map = ... 
  Function<Long, String> to_string = ...
  ...
  //and the magic
  Map<String, Collection<Map<String,Object>> = FIterable(todos) //FIterable<Todo>
    .filter(completed) //FIterable<Todo>
    .flatMap(assignedUsers) //FIterable<User>
    .groupBy(nationality_id) //FMultimap<Long, User>
    .transformValues(to_map) //FMultimal<Long, Map<String, Object>>
    .asMap() //FMap<Long, Collection<Map<String,Object>>
    .mapKeys(to_string);//FMap<String, Collection<Map<String,Object>>

Do you really have any difficulties to understand (even without comments)? Simply beautifull!

Jun 11, 2014

How To Fix Martin Fowler's Estimating Problem in 3 Easy Steps

Hosszú, de érdekes.


When asked to produce or handed an estimate, respond with the following:

Here’s how to fix this

Second Bullet

Using estimates during development

Here’s how to fix this

Third Bullet

Here’s How to Fix This

Estimating the furture is not about controlling the future, it’s about being prepared to respond to the emerging possibilities of the future

Never use average or allow anyone to speak to us about the average.

Original

Jun 09, 2014

Archives

Links

Cool

RSS