Is a Ruby module equivalent to a Java Interface? - java

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.

Related

Subclasses in clojure

I'm learning Clojure and I was wondering how to deal with OO-like subclasses in Clojure. For example: a master abstract class, two abstract subclasses (each one redefines some functions) and in the 3rd level, final subclasses that creates "objects" that will be used in the functions. No clue how to do this. However, I managed to do it with one abstract class to a child class, with defprotocol and defrecord. But I can't implement a protocol inside another. Thanks
You don't need classes or subclasses. Represent your data as maps with attributes. The "subclasses" might have more attributes.
If you have a function that varies on attribute, then either use conditional logic based on attribute (if, cond, etc) or use polymorphism based on multimethods or protocols if you really need to.
In the words of the Matrix, there is no spoon.
You can do inheritance with protocols like this:
(extend <subtype>
<protocol>
(merge (get-in <protocol> [:impls <basetype>])
<map-of-redefined-methods>))
Multimethods provide direct support for inheritance with derive.
Actual Java subclass relationships can be specified with the :extends keyword to gen-class. This is meant exclusively for Java interop, though.
Generally, it is worth checking whether you really need inheritance. It is usually not the preferred method of modeling in Clojure.

Ruby features vs Java

I am a Java programmer using Ruby for the first time, and I have a few questions about how some features compare between the two languages.
Is the notion of a constructor relevant in Ruby? If yes, how does the behavior compare to Java constructors?
In Java, we generally keep separate .java files for different classes (when not nested). Is there a similar practice in Ruby? Or is each class itself not as important as in Java?
How do you extend a class (or .rb file)? I would like to extend a class and call super inside my local constructor to initialize some items.
How do you access the methods of a class in a .rb file, from a different class in another .rb file?
Are Ruby "gems" equivalent to Java packages?
1) Yes. There is concept of constructor which behaves like Java one. However, the constructor method is called initialize in Ruby, when in Java, the constructor has the same name as of class itself. eg:
class Foo
def initialize
# initialization logic here
end
end
2) Yes, it's rathe considered a best practice to store classes per file - separately, but it is not constrained by language.
3) For inheritance, there is different syntax in Ruby. Please consider following code:
class Parent
end
class Child < Parent
end
4) It is actually quite similar to Java, you use . to indicate method on object:
class Person
def name
"Tester"
end
end
p = Person.new
puts p.name
5) There is not really concept of packages in Ruby, but you might use modules to namespace your classes, eg:
module Foo1
class Biz
end
end
module Foo2
class Biz
end
end
b1 = Foo1::Biz.new
b2 = Foo2::Biz.new
Yes. No big difference.
Yes. More freedom in ruby though. (If you want to you can even define the same class in several files....) Apart from classes there are also modules that can be used as mixin - a sort of multiple inheritance.
The < operator is used for inheriting another class. It is the extends of ruby. In the subclass constructor you can call super just like in Java.
Instance methods are accessed just like in Ruby with a dot. Class methods can be accessed as in Java with a dot after the class name. Or with a double colon.
No. Ruby has no packages. Often modules are used around classes to provide a namespace in order to avoid clashes. Gems in ruby are more like a jar file (a maven dependency for example) in java.
Is constructor a relevant thing in Ruby? If yes, any change in behavior compared to Java?
No, there are no constructors in Ruby. Unlike Java, which has three different kinds of "methods" (instance methods, static methods, and constructors), Ruby has exactly one kind of methods: instance methods.
In Java, we generally keep separate .java files for different classes(if not nested). Is the approach same in Ruby?
No. You would use one file for related concepts. It might be a single class, but then again, it might not. For example, the set.rb file in the Ruby standard library contains both the Set and the SortedSet class.
It might also be that a single class is defined in multiple files. For example, the above-mentioned set.rb not only contains the Set and SortedSet class, it also contains a fragment of the Array class which has a to_set method for turning an array into a set.
Or Class itself is not much relevant?
Ruby is a class-based OO language, classes are very much relevant.
How can i extend one class (or a .rb file)? I would like to extend one class and call the super constructor inside my local constructor to initialize some items.
You can't "extend a file". You can, however extend classes, just like in Java.
How to access the Methods inside a class (.rb file) from another class (.rb file)?
Again, files have nothing to do with this.
You call methods on objects, just like in pretty much every other OO language, including Java. You don't "access methods inside a class".
Is packages in Java and Gems in Ruby are the same thing? We used to have multiple packages in a project for tests, utilities etc.Is the approach same in Ruby as well?
No. Gems are more like Maven artefacts. There is no analog to a Java package in Ruby, although one might use modules that way.

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

Naming Conventions or Directory Strucure

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.

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.

Categories

Resources