К основному контенту

Programming practices: Query Context Pattern

Good day! Here I want to tell a little about practice that helps me to reduce refactoring time. I call this practice "Query Context Pattern" or just query context.



Often we have several architectural layers in application where data is transit forward and backward. For example if look at DDD it assumes presense of controllers, services, repositories and, possibly,, something else that has to be in your project. Suppose, we have a certain case, implemented in complex business logic. So you have several methods  with certain number of parameters on each architectural layer. In case you need change logic and add\remove\change one or more paramters in one method on the lower layer you ned to change all methods in call stack. The problem is solving trivially. We just need a wrapper object for all parameters used by methods in call stack. This wrapper is treated as Query Context. It contains everything the methods needs to know about runtime context to get things done. Noew if wee ned to do some refatoring we'll do it only in one place. Perfect!

Examples:
Before:
        
@Controller
public class ExampleController {
    @Autowired
    private ExampleService service;
    @RequestMapping(value = "/someurl", method = RequestMethod.GET)
    public String handle(Integer first, Integer second, Integer third) {
        return service.someMethod(first, second, third);
    }
}
//----
@Service
public class ExampleService {
    public String someMethod(Integer first, Integer second, Integer third) {
        return String.format("%d,%d,%d", first, second, third);
    }
}

After:
 
public class ExampleContext {
    private Integer first;
    private Integer sec;
    private Integer third;
// constructors, getters, setters
}
//-----
@Controller
public class ExampleController {
    @Autowired
    private ExampleService service;
    @RequestMapping(value = "/someurl", method = RequestMethod.GET)
    public String handle(ExampleContext ctx) {
        return service.someMethod(ctx);
    }
}

//-----

@Service
public class ExampleService {
    public String someMethod(ExampleContext ctx) {
        return String.format("%d,%d,%d", ctx.getFirst(), ctx.getSec(), ctx.getThird());
    }
}

As you can see final logic doesn't changed. But code became more simple from point of view of refactoring.
I hope this approach will help someone. Thanks for attention, and Goodbye!

Комментарии

Популярные сообщения из этого блога

Apache Tiles: Основы

Здравствуйте! В работе я часто использую фреймворк Apache Tiles. Де-факто он является основной технологией для создания UI в  проектах над которыми я работаю. В связи с этим хотелось бы поделиться наработанным опытом работы с данной технологией. В цикле будет несколько статей, в которых я разберу что такое этот Tiles, как его настраивать, как правильно использовать и как его задружить со Spring MVC.  Первые несколько статей - по сути вольный пересказ  официальной документации с моими примерами, которые можно будет запустить у себя на компьютере, так что если кому нравится работать с первоисточником - милости прошу. Содержание Часть 1. Основы.

Какую версию Jetty я использую?

Jetty 9 - самая свежая версия сервера с большим количеством улучшений по сравнению с предыдущими версиями. Данная документация фокусируется как раз на версии Jetty 9. Мы очень рекомендуем использовать версию 9, так как именно она будет поддерживаться и улучшаться в течении нескольких лет.