Are utility classes allowed with the Single Responsibility Principle (SRP) - tdd

I just answered a question related to SRP which made me think: How does SRP stand on utility classes?
By definition utility classes tend to do a lot of things. I can see how gatering related utilities at a single accesspoint is usefull. By SRP standards you cannot implement the utilities in one class. Does that mean that a utility class is a no-no, or does SRP allow it if it is only a facade for multiple classes, each of them adhering to SRP?

Utility class is considered as anti-pattern:
Violate SRP as you mentioned because it often takes more than one responsibilities.
Most of them are static classes, it is not good for test design ability and cannot be mocked.
The name itself is meaningless, they are often named Helper, Util, Utility or something like that.
To correct:
Devide your utility class to more smaller non-static classes with meaningful-names, each class takes just one responsibility.

Related

classes with CRUD methods violating Single Responsibility principle?

I am trying to understand single responsibility principle. I have following questions.
The Single Responsibility Principle (SRP) states that there should never be
more than one reason for a class to change.
Usually our Resource,Service and Repository classes have
create,read,update and delete method. We are changing each class to
modify code for any any of these operations. Is it violating SRP? Do we need
separate class for each action?
When I run sonar lint, I have seen below message.
Classes should not coupled to too many other classes.
Here I am injecting other classes using spring DI. Is there any limit on
number of dependencies?
I may be missing crux of this concept. Please suggest a good resource for understanding this concept better with examples
The SRP states that the class should only do one thing, like persisting entities in the case of repositories. I guess that you've confused "class" and "object" here: if you have several methods that could change the object's state this could be in accordance with the SRP. However the only reason for a repository class to change should have something to do with its purpose, namely persisting or retrieving entities in this case.
The Wikipedia article about the Single Responsibility Principle puts it very well.
To your second point: there is no such thing as a maximum number of dependencies a class can have, but it could be a sign for a design weakness if there are many of them.
The Single Responsibility Principle (SRP) states that there should
never be more than one reason for a class to change.
The Single Responsibility principle doesn't mean a single method or a single type of action by component/class.
It means a single responsibility in the scope of a matter.
Persistence operations makes part of the same matter.
So putting all of them in a single class doesn't violate necessary the principle.
Now if you have dozen and dozen of specific database operations, it would make sense to divide them into distinct classes having a well defined responsibility such as selecting operations, updating operations, and so for.
Usually our Resource,Service and Repository classes have
create,read,update and delete method. We are changing each class to
modify code for any any of these operations. Is it violating SRP?
These are distinct layers.
If you change the model of a layer, others are very often impacted as data passes between layers.
It is like if you add an information in your database, you necessary need to change your GUIs and your processing if you want see/manipulate them.
Now if you change implementation of layers, other layers should have no or very few consequences.

Traits vs. Interfaces vs. Mixins?

What are the similarities & differences between traits, mixins and interfaces. I am trying to get a deeper understanding of these concepts but I don't know enough programming languages that implement these features to truly understand the similarities and differences.
For each of traits, mixins and interfaces
What is the problem being solved?
Is the definition of the concept consistent across programming languages?
What are the similarities between it and the others?
what are the differences between it and the others?
Every reference type in Java, except Object, derives from one single superclass.
By the way, Java classes may implement zero or more interfaces.
Generally speaking, an interface is a contract that describes the methods an implementing class is forced to have, though without directly providing an implementation.
In other words, a Java class is obliged to abide its contract and thus to give implementation to method signatures provided by the interfaces it declares to implement.
An interface constitutes a type. So you can pass parameters and have return values from methods declared as interface types, requiring that way that parameters and return types implement particular methods without necessarily providing a concrete implementation for them.
This sets the basis for several abstraction patterns, like, for example, dependency injection.
Scala, on its own, has traits. Traits give you all the features of Java interfaces, with the significant difference that they can contain method implementations and variables.
Traits are a smart way of implementing methods just once and - by means of that - distribute those methods into all the classes that extend the trait.
Like interfaces for Java classes, you can mix more than one trait into a Scala class.
Since I have no Ruby background, though, I'll point you to an excerpt from David Pollak's "Beginning Scala" (amazon link):
Ruby has mixins, which are collections of methods that can be mixed into any class. Because Ruby does not have static typing and there is no way to declare the types of method parameters, there’s no reasonable way to use mixins to define a contract like interfaces. Ruby mixins provide a mechanism for composing code into classes but not a mechanism for defining or enforcing parameter types.
Interfaces can do even more than is described in this post; as the topic can be vast, I suggest you to investigate more in each one of the three directions, while if you even have Java background, Scala and therefore traits are affordable to learn.

What is the prefix `I` before class name like IController, IObserver?

I'm learning MVP patter. In some examples, I saw this! Any one could demonstrate why programmers use this name convention?
Usually I is there to indicate an Interface. Without the I is it a class. Personally I am not a fan of this. I think it is more common in dot net. I havent seen it too much in Java
Reasons why I dislike:
IDEs now show icons that indicate whether a class is an interface or not.
If I want to change the interface to an abstract class I then have to rename the class
It hurts readability.
'I' stands for interface. It's a common naming convention to distinguish interfaces from classes / structures.
Interfaces are not classes - they define behaviour and classes provide implementation.
Read this article on MSDN for more info: Choosing Between Classes and Interfaces
An interface defines the signatures for a set of members that
implementers must provide. Interfaces cannot provide implementation
details for the members. For example, the ICollection interface
defines members related to working with collections. Every class that
implements the interface must supply the implementation details for
theses members. Classes can implement multiple interfaces.
It is an artifact from age when Hungarian notation was thought to be a good idea. It lets the user know that the name is for an interface.
Also, it is an extremely stupid practice.
Name of the interface should reflect what sort of contract between classes it signifies. It should not tell you to which class it has been tied to.
It should be class PDF extends Document implements Printable because it lets you know that class implements print() method for some reason (in a real world it would be actually a bad API design, but this is an example) instead of class PDF extends Document implements IDocument .. because this tell you nothing.

What should have HandlerInterceptorAdaptor been called?

In Spring MVC, one can define interceptors that can perform work before and after a particular controller is invoked. This can be used, for example, to do logging, authentication etc.
The programmer who wishes to write a custom interceptor is supposed to implement the HandlerInterceptor interface. To aid this task, the HandlerInterceptorAdaptor abstract base class has been provided, which provides default implementations of all the methods specified in the interface. So, if just wants to do some pre processing, one can just extend HandlerInterceptorAdaptor and #Override public boolean preHandle(...), and not worry about implementing the postHandle function.
My doubt concerns the name. From what I understand of the Adapter pattern, it adapts syntactic impedance mismatches between interfaces.
Is that so? If yes, should the class providing the boilerplate implementations be called HandlerInterceptorDefaultImpl, or something along those lines?
Is there a different nomenclature/pattern for what is happening here?
Is the fact that we need a boilerplate class a code smell, and could be removed by refactoring the HandlerInterceptor interface into two: HandlerPreInterceptor and HandlerPostInterceptor? Or is that overkill?
From GOF book about the Adapter pattern:
Adapters vary in the amount of work they do to adapt Adaptee to the Target Interface. There is a spectrum of possible work, from simple interface conversion-for example,changing the names of operations-to supporting an entirely different set of operations. The amount of work Adapter does depends on how similar the Target interface is to Adaptee's.
The boilerplate class that you are referring to is called skeletal implementation class. This is mentioned in Effective Java by Joshua Bloch. From the book:
You can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export. The interface still defines the type, but the skeletal implementation takes all of the work out of implementing it.
By convention, skeletal implementations are called AbstractInterface, where Interface is the name of the interface they implement. For example, the Collections Framework provides a skeletal implementation to go along with each main collection interface: AbstractCollection, AbstractSet, AbstractList, and
AbstractMap. Arguably it would have made sense to call them SkeletalCollection, SkeletalSet, SkeletalList, and SkeletalMap, but the Abstract convention is now firmly established.

Point of using Dependency Injection (and for that matter an IoC Container) in LISP

I read ESR's essay named "How to become a hacker?" several years ago (link can be found in my profile) and Eric suggested learning LISP. Well I'm learning LISP for quite a while and I like it so much that I decided to write a web application using it.
Since I'm using Spring for a while I think that it's a good idea to write decoupled components and glue them together using an IoC container and depencency injection. I did a power search on google and it turned out that there is no such idea implemented in LISP. Do I miss something? Is there a good implementation of this concept in LISP or there is no point using it for some reason which is not yet clear to me?
'Inversion of control' is widely used in Lisp. It's totally simple, since functions and closures are first class objects.
Dependency injection is trivial. Classes and functions can be configured via symbols and first class classes.
You usually don't need a 'framework' for IoC or DI in Common Lisp, since a lot of functionality to configure and parameterize applications and libraries is built in.
'first class' means that something can be stored in variables, passed as arguments or returned as results.
In a language like Common Lisp, functions and classes are first class objects. Plus for decoupling via late-binding, you can use symbols as their names instead. The Common Lisp Object System knows meta classes and symbols as names for classes. Even generic functions and methods are objects and have meta-classes.
If concurrent-secure-server is a class and default-response is a function, you can do for example:
(make-instance 'web-services
:server-class 'concurrent-secure-server
:default-response-function 'default-reponse)
Above uses the symbol as the name for the class and the function. If the function gets a new version, the web service might call the new one later.
Alternatively:
(make-instance 'web-services
:server-class (find-class 'concurrent-secure-server)
:default-response-function #'default-reponse)
In above case we pass the class object and the function object.
In Common Lisp software modules can have global variables, which you can set with the right information:
(defvar *default-server-class* 'concurrent-secure-server)
Alternatively you can set those in slots of like below.
(defclass server-object ()
((default-response-function
:initarg :default-response-function
:initform *server-default-response-function*)))
(defvar *my-server*
(make-instance 'server-object
:default-response-function 'my-default-response-function))
You can even create objects and later change their class in a configuration phase.
The Common Lisp Object System allows you to change classes and have existing objects to be updated.
If you create an instance, you can be as flexible as you want:
you can pass in the class
you can pass in the arguments
Like this:
(let ((my-class 'foo-class)
(my-args `(:response-function ',*some-reponse-function)))
(apply #'make-instance my-class my-args))
Sometimes you see Lisp libraries which are computing such arguments lists at runtime.
Another thing where you can configure Lisp applications at runtime is via generic functions. Generic functions allow :before, :after and :around methods - they even allow your own custom call schemes. So by using your own classes inheriting from other classes and mixin classes, the generic function gets reconfigured. This is like you have basic mechanisms of Aspect-oriented programming built-in.
For people interested in these more advanced object-oriented concepts, there is some literature by Xerox PARC, where these issues had been researched when CLOS was created. It was called 'Open implementation' then:
http://www2.parc.com/csl/groups/sda/publications.shtml
In the Open Implementation approach, modules allow their clients individual control over the module's own implementation strategy. This allows the client to tailor the module's implementation strategy to better suit their needs, effectively making the module more reusable, and the client code more simple. This control is provided to clients through a well-designed auxiliary interface.
One thing you don't need: XML. Common Lisp is its own configuration language. Writing extensions for easier configuration can for example be done via macros. Loading of these configurations can be easily done via LOAD.
Actually IoC is the building principle of most web-frameworks, not only in Java or Lisp.
Considering DI, as noted by Rammaren, it's an implicit pattern in a dynamic language such as Lisp. You can see that for yourself, if you compare Hello World applications in Spring and Restas (one of the well-supported CL web-frameworks). You'll see, that there's the same pattern, except for the absence of a need for fancy type/class/interface declaration stuff in Lisp.

Resources