Use of enums in Java API - enums

Could you point me out to a class, from official Java API that has a good use of enums ?
I could not find any specific class.
Does the Java API incorporates enums in their classes at all?

There are 328 enum classes defined in the JRE 7. I suggest you read the Enum Types tutorial
A simple one I have used is java.nio.AccessMode.
An enum worth understanding is Thread.State
A more interesting one is java.util.concurrent.TimeUnit
An example of a class which IMHO would be an enum but predates them is ByteOrder See Joachim's comment above.

There are few in Collection API which directly use Enum : EnumSet, EnumMap

Related

Code Implementation: Hamcrest Matcher Interface and BaseMatcher abstract class

i have come across these comments in library of hamcrest matcher interface.
It is coded by Stevefreeman and Nat Pryce
Matcher implementations should NOT directly implement this interface.
* Instead, extend the {#link BaseMatcher} abstract class,
* which will ensure that the Matcher API can grow to support
* new features and remain compatible with all Matcher implementations.
What advantage would a abstract class i.e BaseMatcher implementing the matcher interface provide over the specialized class directly implementing matcher. If someone can explain with an example would help . i want to understand best practices for doing framework style code so I am curious to know when should one follow this pattern as i see similar style in Spring as well.
Let's say the Hamcrest designers decide to add a new method in the Matcher interface.
All the classes implementing Matcher directly wouldn't compile anymore.
But if they instead extend an abstract BaseMatcher class, the designers can add a default implementation of the new method in BaseMatcher, and all the existing subclasses would still compile.
Note that since Java 8, they could also add a default implementation directly in the interface. But Hamcrest was created long before Java 8.

What's the difference between a Contract in Laravel and an Interface in PHP?

As far as I can tell, Laravel refers to the interfaces it extends as Contracts because they are used by Laravel. But this seems a bit like circular reasoning. There is no value added in changing the terminology of an existing PHP feature simply because your project uses it.
Is there something more to it? What's the logic behind coining a new term for something that's a standard PHP feature? Or is there some feature of Contracts that are not already in Interfaces?
Edit: To clarify, it's the usage of Contract as a proper noun in the documentation that has me confused, as explained in my comment on Thomas's post
"Contract" isn't some new terminology that Taylor coined. It's a very common term programmers use.
An interface is a contract, but a contract doesn't necessarily have to be an interface. The interface in a nutshell defines the contract that the classes must implement.
An abstract class is also a contract. The difference is that an abstract class can provide actual implementations, state, etc., and as a result, it is (in a sense) a more rigorous contract.
Another key difference is that a child class can only extend 1 abstract class but it can implement multiple interfaces.
So basically, "contract" isn't a new naming convention. It's a common term that Taylor is using.
It's just a nice word to describe the idea of using interfaces.
Laravel contracts are just PHP interfaces so they don't provide any other functionality.
You can read more on this subject in the documentation http://laravel.com/docs/5.1/contracts
As others have said, that is just a fancy word for Interfaces, but I think that Taylor made that decision to make it more personal.
What I mean by personal is that interface it's a very broad/common word on programming language, you have your interfaces, libraries (that you might be using) have their own interfaces and so on.
Contracts you just assume as the Laravel interfaces it's like a wrapper or alias for all the Interfaces that belong to this repo.
Short description: Contract is a term used for interfaces, but also for abstract classes.

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.

Get names of structs that implement an interface or inherit a struct

Is it possible to get a slice of strings that represent the names of all types that implement an interface or inherit from a specific struct in a specific package using reflection?
After some research on the reflect package's doc, I don't think it's possible. That's not the way reflection work in go: the interfaces mechanism not beeing declarative (but duck-typed instead), there is no such list of types.
That said, you may have more luck using the ast package to parse your project, get the list of types, and check wheter or not they implement an interface, then write some code to give you the said slice. That would add a step to compilation, but could work like a charm.
AFAIK, you can't do this with reflect, since packages are kinda out of reflect's scope.
You can do this the same way godoc's static analysis works. That is, using code.google.com/p/go.tools/go/types to parse the package's source code and get the type info.
The go oracle can do this. https://godoc.org/code.google.com/p/go.tools/oracle
Here is the relevant section of the user manual.

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.

Resources