What's the Prolog way of adding "annotations" (meta information) to predicates?
A typical example from Java would be:
#Transactional
public List<User> findAll() { ... }
What are the Prolog options for adding Transactional annotation to the predicate:
users(Users) :- ...
There's no (de facto) standard solution. Some systems use predicate directives (e.g. Ciao Prolog, ECLiPSe, ... also Logtalk) that are in some cases user-extensible in the information they can represent. some system use structured comments (e.g. SWI-Prolog). But no matter the solution specifics, the best systems allow that information to be programmatically retrieved using the system reflection API so that we can base developer tools on it.
Related
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.
In many programming languages, fields and methods can be arranged freely, but the order impacts the readabilty of the code. Which ordering strategy do you apply?
Background: We (a group of researchers from the University of Trier) already looked at the code of different open source projects and tried to figure out what strategies are applied. But as you can imagine, it is hard to extract this information from the code. Now, we are interested in the concrete strategies you apply and want to share and discuss this information here. Please find further information on our project page.
private fields first
public fields (if any)
properties (if any, e.g. in C#) or simple Getter/Setter
constructors
public methods
private methods near to their appearance in public methods (in functional programming languages even inside public methods if possible)
Moreover I try to order each of these sections semantically or to their importance for the class. I really try to structure my code so that I can quickly gain an overview of everything important. However in very big classes I have my problems to follow my strategy and then I often use the outliner to get to fields or methods instead of looking for them by scrolling.
I would like my first Aspect in a Roo project to run the advice when a web controller starts up. But I cant get the pointcut to match.
The controllers have a class name starting Cfx. I have tried with the following form:
pointcut setBrand() : initialization(Cfx*.new (..));
before() : setBrand()
{
log.info("xxxxxxxxxxxx setting brand");
}
As well as "initialization" I have tried (from the book AspectJ Cookbook) call(Signature) with new keyword, preinitialization, staticinitialization. What is the formula?
Maybe this is related - the Roo aspects do not have this form - no pointcut for example. How are they working? Where is this documented?
Thanks
PS apologies, this is a re-post. I posted this to the Spring Roo forum but got no response. http://forum.springsource.org/showthread.php?129374-Aspect-to-trap-Controller-creation-how-to
I know next to nothing about Roo or Spring, but some AspectJ, so I am going to answer your question from an AspectJ perspective only, assuming that you are an AOP newbie (sorry if my assumption is incorrect):
If you want to do something when a class is loaded, use a staticinitialization(TypePat) pointcut.
If you want to do something when an object (instance) is created, use something like execution(ConstructorPat). The initialization is for special purposes and preinitialization is needed even more rarely. I am assuming that the first one will do for you, not knowing your exact purpose.
Further assuming that something like execution(Cfx*.new (..)) is basically the thing you want, I suggest you look at possible errors or warnings like "advice defined in ... has not been applied [Xlint:adviceDidNotMatch]", because it might just be a pointcut matching issue. Please note that the type pattern you use assumes the matched constructors are in the same package as the aspect and that they have standard visibility (not public or anything else). So unless there is a class-loading issue, maybe you just want to specify more exactly (or more generally) what you want to match. Examples:
com.bigboxco.my_app.Cfx*.new(..)
com.bigboxco..Cfx*.new(..)
public com.bigboxco..Cfx*.new(..)
!private com.bigboxco..Cfx*.new(..)
* com.bigboxco..Cfx*.new(..)
A good strategy could be trying to match one of your constructors by replicating its exact signature and using its fully qualified class name, then working on from that point to make it more general.
Update: I know you can do a web search by yourself, but anyway here are some useful links:
AspectJ quick reference
AspectJ language semantics with topics about signatures, matching etc.
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.
Wikipedia states that the Specification Pattern is where business logic can be recombined by chaining the business logic together using boolean logic. With respect to selecting filtering objects from lists or collections it seems to me that Dynamic LINQ allows me to accomplish the same thing. Am I missing something? Are there other benefits to the Specification Pattern that should be considered as well?
Edit:
I've found some posts that discuss combining LINQ and the Specification Pattern:
Linq Specifications Project
Implementing the Specification Pattern via Linq by Nicloas Blumhardt (Autofac dude)
Has anyone gone done this road and did it become complicated to maintain?
I'm a C# developper and like to use the specification pattern, because it is closer of my business domain. Moreover, you don't have any surprise with this pattern, if a specification class exists, it should work. With Linq, your underlying provider maybe hasn't implemented some features, and you won't know it until runtime.
But definitively, the biggest advantage of specification over linq is to be closer to the business, it's a mini DSL. LINQ for me is a DSL for collection query, not for the business domain.
LINQ:
var oldMans = Persons.Where(x => x.Sex == SexEnum.Masculine && x.Age > 60).ToList();
Specification:
var oldMans = Persons.Where(x => IsOldManSpecification(x)).ToList();
The business logic is encapsuled in the specification (with a name that reveal what it is).
DRY: you don't repeat that linq over the code, you just use the Specification
I like to use specification when I think that the rule is important enough to be explicit in the code and it doesn't belongs naturally to the entity.
Example:
public class Customer
{
//...
public bool IsAbleToReceiveCredit(decimal creditValue)
{
var secureAge = this.Age > 18 && this.Age < 60;
var personalAssetsGreaterThanCreditValue = this.PersonalAssets.Sum(x => x.Value) > creditValue;
return secureAge && personalAssetsGreaterThanCreditValue;
}
}
Is it from the Customer the responsability to decide if he is able to receive some credit? A bank would ask to the customer if he can receive a loan?
Probably not.
So with specification you can remove that logic from the Customer (it never belonged to it). You can create something like IsAbleToReceiveCreditSpecification and put all logic there. We can go further and combine specifications, for example: you could create a SecureAgeSpecification and a AssetsGreaterThanSpecification and use them to compose the IsAbleToReceiveCreditSpecification.
So I don't think LINQ replaces the Specification. In fact it improves the pattern. There are some implementations of Specification that use LINQ internally with IQueriable<T>, with this you can use the specification inside your ORM queries on the Repository/DataAcess level.
Dynamic LINQ uses string expressions to allow the dynamic query construction. So we do in fact lose the type safety there. Whereas using wrapper patterns like the decorator pattern of it closely related incarnation, the specification pattern, allows us to maintain the type safety in code. I explore using the Decorator Pattern as query wrapper in order to reuse and dynamically build queries. You can find the article on code project at:
Linq Query Wrappers
Or you can check my blog.
I don't know LINQ really, but it seems to me that a declarative query system in general is related to the specification pattern. In particular, implementing a declarative query system by composing objects together in an object-oriented environment. IIRC that's akin to what LINQ does, providing a layer of syntactic sugar.
Whether LINQ completely obsoletes the pattern, I can't tell. Maybe there are corner cases that just can't be expressed in LINQ?