Naming Conventions or Directory Strucure - java

I'm PHP programmer, but what I want to discuss is influenced by Java.
After read some articles about Hungarian Notation and Naming Conventions of several Languages, I proved how clear are the Java's Naming Convention for Interfaces, I have one question.
Considering the Object Collections' case, where we have an Abstract Class called AbstractCollection and the concrete class called Lists, how should I name an Interface for Lists?
The question is, in Java's Naming Conventions, there is no prefix nor suffix for Interfaces, such as ListsInterface or InterfaceLists.
Lists IS an Interface name and, obviously, at least in PHP, two files in same directory cannot have the same name of a class or interface.
Not EVERY class needs an Interface, I know, but what if I decide to move to a programming team? The other programmers may use my classes, but they should not open the class files to see what public methods it offers.
Just by reading its Interface, everything is clear.
The Directory Structure point came from the possibility to add a subdirectory with the same name of the Interface and, inside it, the concrete class' file. E.g.:
/
/Collections
/Collections/Lists.php <-- Interface
/Colection/Lists/Lists.php <--- Concrete Class
What now?

You shouldn't give an interface and a class the same name. Never. For your readers sake.
I think your particular problem has little to do with convention, but with a concrete naming problem Lists doesn't sound like an interface at all. List does. But in that case an implementing class would have a more concrete name, like List_DoublyLinked and List_SinglyLinked (or whatever kind of list you are talking about).

I think you should check PHP naming conventions instead of Java.
http://framework.zend.com/manual/en/coding-standard.naming-conventions.html
Zend provides a good one, nearly considering all the cases.
Symfony has another ( http://trac.symfony-project.org/wiki/HowToContributeToSymfony#CodingStandards ), Pear has another ( http://pear.php.net/manual/en/standards.php ) too.
In your case just to show that an interface is an interface, Zend forces you to put a suffix on your interafces. So your dir structure should be like:
Collections/
Collections/ListsInterface.php
Collections/Lists/ListAbstract.php
Collections/Lists/MyList.php
I don't know if this post answers your question but I hope that it helps.

Related

How methods of java.nio.Path works

I have started study about nio.2 in java 8 from java documentation. When I study about java.nio.file.Path, java documentation's first line is
The Path class, introduced in the Java SE 7 release.
which mean Path is a class, but when I look here I found that Path is an interface.
So why java documentation says that it is a class.
My another doubt is if Path is an interface then how Path methods (like getRoot() isAbsolute() and all other) work, because there is no implementation of methods of Path interface.
I know asking two different question in one statement is cumbersome but I have no idea how these two questions can be separated.
Edit: This question can't be duplicate of this, because in this question the questioner asked for implementation of Path interface, but here I'm asking how methods of this interface works, I mean is it internally executed by the JVM or any other mechanism is used to execute them.
Path is an ordinary interface that is implemented like any other interface by a concrete class that declares to implement it and provides concrete methods for the abstract methods of the interface. So there’s nothing special with the methods of Path. As the linked question explains, there are ordinary implementations of this interface.
You shouldn’t get confused because it is called “class” in the documentation. While class in the narrowest sense is a type distinct from interface or enums, these types are all classes in the broadest meaning of the term. This is reflected by the fact that they all are stored within a class file and loaded via an operation name loadClass on a ClassLoader. At these places, no distinction between interfaces and classes is made. From this point of view, interfaces and enums are just classes with special properties (and similar, annotations are interfaces with special properties).
In documentations it makes sense to use the term “class” in the broader sense when the way you use it doesn’t differ, i.e. you are calling methods on a Path instance without having to care about whether the Path type is an interface. A difference has to be emphasized only when the reader is the one who has to implement it.
Path is an interface because the concrete implementation depends on the underlying file system. The methods are in classes which implement the interface, these are platform-dependent.
Note that you never contruct a Path object with new, but use a method like Paths.get, which returns an instance of the appropriate class.
For example, in Oracle's implementation, paths in windows are implemented by sun.nio.fs.WindowsPath (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/sun/nio/fs/WindowsPath.java)

Java - what is a a prototype?

In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods

Java - naming convention for can-do interface as opposed to can-be-done-to

In Java more often than not I have come across interfaces with the suffix -able, e.g. serializable, iterable, etc. This suggests that the object that implements these interfaces has qualities such that certain actions can be done to it, e.g. the object can be serialized or can be iterated over. What if I want to implement an interface that suggests that certain actions can be done by the object rather than to the object.
For example, it makes sense for a human to implement an interface along the lines of CanDrive but does not make sense for a human to implement the interface Drivable, as a human cannot be driven. A car, conversely, should implement Drivable but certainly should not implement CanDrive because no car should ever drive itself.
The name CanDrive sounds remarkable ugly to me as an interface name. Is there a suffix convention for naming an interface that suggests this kind of can-do relationship (as opposed to can-be-done-to)?
It is common to use agent nouns or noun phrases for classes and interfaces that do things to other objects:
Serializer
ClassLoader
I don't think there is much of a naming convention. For instance the done to iterable interface is related to the can-be-done-by iterator interface. Comparable to Comparator etc. It seems to me that if there is such a naming "convention" you'd use -or instead of -able.
End the name in -or or -er (depending on English spelling).
There are lots of examples even in the JDK of interfaces that do things:
Executor
Conparator
DocumentHelper
Tokenizer
Etc.
And in your example of CanDrive, you would use Driver.

Java Interfaces/Implementation naming convention [duplicate]

This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 7 years ago.
How do you name different classes / interfaces you create?
Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.
When this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.
How do you name interfaces and classes in this regard?
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck.
An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc that implements Truck.
When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck. Since only the sub-classes will ever see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No, you see List and ArrayList, and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have a situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface in most cases.
However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.
Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair
I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).
So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.
in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).
Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.
For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).
I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.
The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.
If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List - interface for the "conceptual" object
ArrayList - concrete implementation of interface
LinkedList - concrete implementation of interface
AbstractList - abstract "partial" implementation to assist custom implementations
I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.
I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?
Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I use both conventions:
If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.
But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.
In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).
TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.

Is a Ruby module equivalent to a Java Interface?

As I understand it, an interface is Java is intended to enforce a design by laying out methods for classes implementing the interface to fill in. Is this the idea with a Ruby module also? I see that just like with Interfaces in Java, you can't instantiate a module in Ruby.
The short answer is no.
Here's the reasoning, a Java/C# interface defines the method signatures an implementing class will provide at minimum.
Additionally:
With ruby modules there is no such contract because of the duck-typing.
Modules are just a way to extract out common functionality for easy re-use. The closest relation is C# extension methods, but those aren't an exact match since they exist in a static context.
Modules can add state to an existing class.
Modules can have static methods
Modules can act as namespaces
Example:
module SimpleConversation
class NamespacedExample
def poke
puts "ouch"
end
end
attr_accessor :partner_name
def converse
partner_name ||= "Slowpoke"
speak + "\n#{partner_name}: Yes they are"
end
def self.yay
puts "yay"
end
end
class Foo
include SimpleConversation
attr_accessor :name
def speak
name ||= "Speedy"
"#{name}: tacos are yummy"
end
end
x = Foo.new
x.name = "Joe"
x.partner_name = "Max"
puts x.speak
puts x.converse
y = SimpleConversation::NamespacedExample.new
y.poke
SimpleConversation.yay
I think I'd equate a module to something more akin to an extension method in C#. You're adding functionality to an existing class that is actually defined elsewhere. There isn't an exact analog in either C# or Java, but I definitely wouldn't think of it as an interface because the implementation is derived as well as the interface.
A Module in ruby is a bit of scope/namespace that can be added to other things. They are used for two distinct but related purposes: bundling up a bunch of related things (constants, classes, etc.) that belong together and then adding them into some other scope (like multiple inheritance).
For example, there are modules called things like Comparable and Enumerable and so forth that encapsulate the functionality you'd expect something to have if these adjectives applied. By providing a basic definition (a method that compares two instances for Comparable and an iterator for Enumerable) you can import the module and find yourself with the full interface.
On the other hand there are modules like Net that you would seldom include in a class but which provide a bundle of functionality such as Net::HTTP, Net::FTP, Net::SMTP, and so on.
In the middle there are things like Math and Process which might be used one way or the other.
-- MarkusQ
No. A module in ruby is more akin to a static class. I am not a Java developer, but I am guessing that Java interfaces are similar to C# interfaces, i.e., they define a contract, but not an implementation.
I should not that, while I have experience in ruby, it is in video game creation (RGSS/2). I am sure that I am ignorant of many things a veteran ruby programmer would know.
From formal point of view modules in Ruby implement design
pattern called "mixin".
http://en.wikipedia.org/wiki/Mixin
It can be compared to PHP traits.
http://php.net/manual/en/language.oop5.traits.php
Such architecture is useful in languages that don't allow multiple inheritance, e.g. Ruby, PHP.

Categories

Resources