Are typed/generic aspects worth the effort? - spring

I've done a little research on typed/generic aspects. An important fact about aspects is obliviousness. So the concerns of the aspects should be orthogonal to the domain concerns. Nevertheless there are investigations to make AspectJ type safe (StrongAspectJ) / introduce per-type aspects using generics. One paper mentioned an implementation of the Flyweight pattern as an aspect. Now I'm wondering if there are more use cases for generic aspects?

PostSharp is weakly typed, i.e. the advices see arguments and return values as 'objects'. There is some support for generic aspects in PostSharp (aspects can be generic classes), but it is not very useful since the advises are weakly typed.
Note that behind the cover, the glue code generated by PostSharp is strongly typed. But everything is downcast to an object when exposed to aspect code.
I'm considering implementing strongly-typed advised in a next version of PostSharp, possible with support of generic arguments. The reason would be run-time performance, because boxing of value types into an object brings a considerable performance overhead. Note that generics are implemented differently in .NET than in Java, so the point may need to be discussed differently on both platforms.
Feel free to contact me personally if you need any help for your thesis.

Auto-generating some of the boilerplate to make a class callable via RMI is another use case. That example implements some around advice for a bunch of methods.
pointcut callsToServer(Type T):
call(public T Server.*(..)) && this(Client)
T around(Type T): callsToServer(T) {
T obj = null;
try {
obj = proceed();
} catch (java.rmi.RemoteException ex) {}
return obj;
}
Generics allow you to say "we are going to return an object of the same type the method signature says". This is true, of course, if we just return the object. We might be able to do something similar with "after throwing" advice, but we wouldn't be able to manipulate the return value to translate a RemoteException into a null return value.

Related

Confused about the Interface and Class coding guidelines for TypeScript

I read through the TypeScript Coding guidelines
And I found this statement rather puzzling:
Do not use "I" as a prefix for interface names
I mean something like this wouldn't make a lot of sense without the "I" prefix
class Engine implements IEngine
Am I missing something obvious?
Another thing I didn't quite understand was this:
Classes
For consistency, do not use classes in the core compiler pipeline. Use
function closures instead.
Does that state that I shouldn't use classes at all?
Hope someone can clear it up for me :)
When a team/company ships a framework/compiler/tool-set they already have some experience, set of best practices. They share it as guidelines. Guidelines are recommendations. If you don't like any you can disregard them.
Compiler still will compile your code.
Though when in Rome...
This is my vision why TypeScript team recommends not I-prefixing interfaces.
Reason #1 The times of the Hungarian notation have passed
Main argument from I-prefix-for-interface supporters is that prefixing is helpful for immediately grokking (peeking) whether type is an interface. Statement that prefix is helpful for immediately grokking (peeking) is an appeal to Hungarian notation. I prefix for interface name, C for class, A for abstract class, s for string variable, c for const variable, i for integer variable. I agree that such name decoration can provide you type information without hovering mouse over identifier or navigating to type definition via a hot-key. This tiny benefit is outweighed by Hungarian notation disadvantages and other reasons mentioned below. Hungarian notation is not used in contemporary frameworks. C# has I prefix (and this the only prefix in C#) for interfaces due to historical reasons (COM). In retrospect one of .NET architects (Brad Abrams) thinks it would have been better not using I prefix. TypeScript is COM-legacy-free thereby it has no I-prefix-for-interface rule.
Reason #2 I-prefix violates encapsulation principle
Let's assume you get some black-box. You get some type reference that allows you to interact with that box. You should not care if it is an interface or a class. You just use its interface part. Demanding to know what is it (interface, specific implementation or abstract class) is a violation of encapsulation.
Example: let's assume you need to fix API Design Myth: Interface as Contract in your code e.g. delete ICar interface and use Car base-class instead. Then you need to perform such replacement in all consumers. I-prefix leads to implicit dependency of consumers on black-box implementation details.
Reason #3 Protection from bad naming
Developers are lazy to think properly about names. Naming is one of the Two Hard Things in Computer Science. When a developer needs to extract an interface it is easy to just add the letter I to the class name and you get an interface name. Disallowing I prefix for interfaces forces developers to strain their brains to choose appropriate names for interfaces. Chosen names should be different not only in prefix but emphasize intent difference.
Abstraction case: you should not not define an ICar interface and an associated Car class. Car is an abstraction and it should be the one used for the contract. Implementations should have descriptive, distinctive names e.g. SportsCar, SuvCar, HollowCar.
Good example: WpfeServerAutosuggestManager implements AutosuggestManager, FileBasedAutosuggestManager implements AutosuggestManager.
Bad example: AutosuggestManager implements IAutosuggestManager.
Reason #4 Properly chosen names vaccinate you against API Design Myth: Interface as Contract.
In my practice, I met a lot of people that thoughtlessly duplicated interface part of a class in a separate interface having Car implements ICar naming scheme. Duplicating interface part of a class in separate interface type does not magically convert it into abstraction. You will still get concrete implementation but with duplicated interface part. If your abstraction is not so good, duplicating interface part will not improve it anyhow. Extracting abstraction is hard work.
NOTE: In TS you don't need separate interface for mocking classes or overloading functionality.
Instead of creating a separate interface that describes public members of a class you can use TypeScript utility types. E.g. Required<T> constructs a type consisting of all public members of type T.
export class SecurityPrincipalStub implements Required<SecurityPrincipal> {
public isFeatureEnabled(entitlement: Entitlement): boolean {
return true;
}
public isWidgetEnabled(kind: string): boolean {
return true;
}
public areAdminToolsEnabled(): boolean {
return true;
}
}
If you want to construct a type excluding some public members then you can use combination of Omit and Exclude.
Clarification regarding the link that you reference:
This is the documentation about the style of the code for TypeScript, and not a style guideline for how to implement your project.
If using the I prefix makes sense to you and your team, use it (I do).
If not, maybe the Java style of SomeThing (interface) with SomeThingImpl (implementation) then by all means use that.
I find #stanislav-berkov's a pretty good answer to the OP's question. I would only share my 2 cents adding that, in the end it is up to your Team/Department/Company/Whatever to get to a common understanding and set its own rules/guidelines to follow across.
Sticking to standards and/or conventions, whenever possible and desirable, is a good practice and it keeps things easier to understand. On the other side, I do like to think we are still free to choose the way how we write our code.
Thinking a bit on the emotional side of it, the way we write code, or our coding style, reflects our personality and in some cases even our mood. This is what keeps us humans and not just coding machines following rules. I believe coding can be a craft not just an industrialized process.
I personally quite like the idea of turning a noun into an adjective by adding the -able suffix. It sounds very impropper, but I love it!
interface Walletable {
inPocket:boolean
cash:number
}
export class Wallet implements Walletable {
//...
}
}
The guidelines that are suggested in the Typescript documentation aren't for the people who use typescript but rather for the people who are contributing to the typescript project. If you read the details at the begging of the page it clearly defines who should use that guideline. Here is a link to the guidelines.
Typescript guidelines
In conclusion as a developer you can name you interfaces the way you see fit.
I'm trying out this pattern similar to other answers, but exporting a function that instantiates the concrete class as the interface type, like this:
export interface Engine {
rpm: number;
}
class EngineImpl implements Engine {
constructor() {
this.rpm = 0;
}
}
export const createEngine = (): Engine => new EngineImpl();
In this case the concrete implementation is never exported.
I do like to add a Props suffix.
interface FormProps {
some: string;
}
const Form:VFC<FormProps> = (props) => {
...
}
The type being an interface is an implementation detail. Implementation details should be hidden in API:s. That is why you should avoid I.
You should avoid both prefix and suffix. These are both wrong:
ICar
CarInterface
What you should do is to make a pretty name visible in the API and have a the implemtation detail hidden in the implementation. That is why I propose:
Car - An interface that is exposed in the API.
CarImpl - An implementation of that API, that is hidden from the consumer.

When to use Encapsulate Collection?

In the smell Data Class as Martin Fowler described in Refactoring, he suggests if I have a collection field in my class I should encapsulate it.
The pattern Encapsulate Collection(208) says we should add following methods:
get_unmodified_collection
add_item
remove_item
and remove these:
get_collection
set_collection
To make sure any changes on this collection need go through the class.
Should I refactor every class which has a collection field with this pattern? Or it depends on some other reasons like frequency of usage?
I use C++ in my project now.
Any suggestion would be helpful. Thanks.
These are well formulated questions and my answer is:
Should I refactor every class which has a collection field with this
pattern?
No, you should not refactor every class which has a collection field. Every fundamentalism is a way to hell. Use common sense and do not make your design too good, just good enough.
Or it depends on some other reasons like frequency of usage?
The second question comes from a common mistake. The reason why we refactor or use design pattern is not primarily the frequency of use. We do it to make the code more clear, more maintainable, more expandable, more understandable, sometimes (but not always!) more effective. Everything which adds to these goals is good. Everything which does not, is bad.
You might have expected a yes/no answer, but such one is not possible here. As said, use your common sense and measure your solution from the above mentioned viewpoints.
I generally like the idea of encapsulating collections. Also encapsulating plain Strings into named business classes. I do it almost always when the classes are meaningful in the business domain.
I would always prefer
public class People {
private final Collection<Man> people;
... // useful methods
}
over the plain Collection<Man> when Man is a business class (a domain object). Or I would sometimes do it in this way:
public class People implements Collection<Man> {
private final Collection<Man> people;
... // delegate methods, such as
#Override
public int size() {
return people.size();
}
#Override
public Man get(int index) {
// Here might also be some manipulation with the returned data etc.
return people.get(index);
}
#Override
public boolean add(Man man) {
// Decoration - added some validation
if (/* man does not match some criteria */) {
return false;
}
return people.add(man);
}
... // useful methods
}
Or similarly I prefer
public class StreetAddress {
private final String value;
public String getTextValue() { return value; }
...
// later I may add more business logic, such as parsing the street address
// to street name and house number etc.
}
over just using plain String streetAddress - thus I keep the door opened to any future change of the underlying logic and to adding any useful methods.
However, I try not to overkill my design when it is not needed so I am as well as happy with plain collections and plain Strings when it is more suited.
I think it depends on the language you are developing with. Since there are already interfaces that do just that C# and Java for example. In C# we have ICollection, IEnumerable, IList. In Java Collection, List, etc.
If your language doesn't have an interface to refer to a collection regarless of their inner implementation and you require to have your own abstraction of that class, then it's probably a good idea to do so. And yes, you should not let the collection to be modified directly since that completely defeats the purpose.
It would really help if you tell us which language are you developing with. Granted, it is kind of a language-agnostic question, but people knowledgeable in that language might recommend you the best practices in it and if there's already a way to achieve what you need.
The motivation behind Encapsulate Collection is to reduce the coupling of the collection's owning class to its clients.
Every refactoring tries to improve maintainability of the code, so future changes are easier. In this case changing the collection class from vector to list for example, changes all the clients' uses of the class. If you encapsulate this with this refactoring you can change the collection without changes to clients. This follows on of SOLID principles, the dependency inversion principle: Depend upon Abstractions. Do not depend upon concretions.
You have to decide for your own code base, whether this is relevant for you, meaning that your code base is still being changed and has to be maintained (then yes, do it for every class) or not (then no, leave the code be).

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.

Is extracting method parameters as an object a good idea?

http://www.jetbrains.com/idea/webhelp/extract-parameter-object.html
I have always found extracting method parameters as an object a good idea, for methods which have a large number of parameters.
public void Method(A a, B b, C c, D d, E e);
becomes
public class Wrapper {A; B; C; D}
public void Method(Wrapper wrapper);
This allows me to:
Have better readability in my code
Perform validation of these parameters in the Wrapper class and reuse it across layers/components if need be.
Provide less brittle method signatures.
Are there any other advantages/disadvantages you see to this that would help convince someone who's is writing methods with lot of parameters?. I am coding C# 4 if that makes a difference.
The only disadvantage I can think of is having an additional abstraction in your system, requiring you to extract (although trivially) the actual data before access. I'm even not sure whether it can be called a disadvantage.
Most important advantage of parameters encapulation is having a robust well-defined interface which can accommodate future changes.
A deeper advantage is that as you wrap the parameters in a new class, you realize that some behavior can be moved to the new class. This is because the bodies of the methods that modify the parameters are likely to manipulate the parameters similarly. Moving this common behavior into the new class allows you to remove much code duplication. Parameter validation is just one example of a behavior that can be moved into the new class.

Is validation a cross cutting concern?

Some of my coworkers consider validation as an example of a cross cutting concern and think Aspect Oriented Programming is a good way to handle validation concerns. To use PostSharp notation they think something like this is a good idea:
[InRange(20.0, 80.0)]
public double Weight
{
get { return this.weight; }
set { this.weight = value; }
}
My opinion is that validation is an inherent part of an algorithm and there is no need to push it behind the scenes using AOP. However it is much like a gut feeling and I have not a very clear justification for it.
When do you think it is a good idea to handle validation with AOP and when it is better to handle it inline with your main code?
Looks a lot like Microsoft DataAnnotations as used by MVC.
You aren't really "pushing it behind the scenes", since all the relevant information is right there in the attribute constructor. You're just pushing the noisy boilerplate behind the scenes and into its own class. You also no longer need an explicit backing field, and you can just use auto-getters and setters. So now, 8 lines (or more) of code can be reduced to 1 line and 1 attribute.
I think that if your alternative is to put some validation code inside of the setter, and you do that multiple times in your project to where it becomes repetitive boilerplate, then yes, I think it's a valid cross-cutting concern and appropriate for using PostSharp. Otherwise, I don't think one or two places justify bringing in a third party tool just yet.
I'd think that it is a cross cutting concern although i have never implemented it with AOP specifically.
That said, there are many different validation scenarios and I doubt they can all be exactly black or white.
Microsoft Patterns and Practice - Cross cutting concerns

Resources