Abstract class in simultaneous coding - project

In my understanding,abstract class is usually used for some common methods for different class to be implemented differently .
Is there another use for it in a group project,so that one person can use the unfinished method of the other class and will not get an error like function not found?

Yes, using classes and interfaces to refer to the unfinished code (being developed in parallel by other developer) looks cleaner than just having a stub for that code.
This approach also allows easier dependency injection during tests as the testing mock (derived from the abstract class or implementing the agreed interface) can usually be substituted without any specific tricks.

Related

Abstract and interfaces together

I am struggling to understand both abstract and interface approach. Since i get the idea what is the purpose to use one over another is clear. I was trying to found whatever example of using them both in action however all tutorials are how to use interface over abstract or vice versa showing usage either for one or another. I would really love to see practical example which could show both in action best on some real life example. Additional comments why in specific case you used one over another appreciated. Generics are very welcome to see as well in such example.
I'll propose foloowing example. We got some engine to get files from diffrent locations which could be taken using diffrent protocols as follows. I would like to understand on this example how this could be accomplished with both interfaces and abstract.
'As all of protocol has to close and open would it be good to put in abstract?
abstract class Collector
Protected Id
Protected Name
MustInherit Sub OpenConnection
MustInherit Sub CloseConection
End Class
'?
class Ftp : Collector
class Sftp: Collector
class Soap: Collector
'Interface?
Public Interface IRepository(Of T, Tkey)
Function GetAllFiles() As IEnumerable(Of T)
Function GetAllById(Tkey) as IEnumerable(Of T)
End Interface
Some key distinctions:
An abstract class can contain some implementation. An interface cannot.
In .NET, a class can not inherit from multiple base classes.
A class can implement multiple interfaces
The choice of which approach is really up to you. In general, it's a choice between the Composition pattern or Inheritance.
Composition uses Interfaces. Think of an object as having X.
Inheritance uses Classes. Think of an object as being X.
In either case, an abstract class or an interface is just a Type, through which you will access and manipulate them. For example, if you have some code that wants to perform Insert/Update/Delete operations, it doesn't need to know that the object it is operating on is a FTP client--only that the object has the ability to support these operations. (and that is exactly what IRepository specifies)
You definitely can combine both. There's no reason a concrete FtpClient class couldn't inherit from an abstract Protocol class and also implement the IRepository interface. It could even use generics!
Interfaces are great for decoupling your code, and also great for unit test mocks.
There is also a good summary of pros & cons on Wikipedia (Composition_over_inheritance). Pros:
To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, a gas pedal and a wheel share very few common traits, yet are both vital components in a car. What they can do and how they can be used to benefit the car is easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (HAS-A) than extend what it is (IS-A).
Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance. This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model. Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes.
Cons:
One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods. In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only needs to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class.
I don't understand why you want to have an example combining both. Let's just say both are valid ways to build solid software architecture. They're just two tools - like having a kitchen knife and a meat cleaver. You won't necessarily use them together but see the pro's and con's when looking at the dinner you want to serve.
So usually you take abstract/MustInherit classes if you want to provide a common denominator. Sub-classes derive from the abstract one and have to implement the methods just like they would if they implemeted an interface. The good thing here is that abstract classes can provide "base logic" which can be developed centrally and all the sub-classes can make use of that. In the best case, abstract classes provide kind of "hooks" to plug in special logic in the sub-classes.
Interfaces describe what a class has to fulfill. So everything an interface defines has to be implemented in classes implementing the interface. There's no reusable logic built-in in this approach like in abstract base classes but the big "pro" for interfaces is that they don't take away the single base type you can derive from like abstract classes do. So you can derive from anything or nothing and still implement an interface. AND: You can implement multiple interfaces.
One word to the "reusable logic" with interfaces. While this is not really wroing, the .NET framework allows use to write extension methods on types (and interfaces) to attach externally developed code. This allows code reuse with interfaces like having a method implemented in there. So for example, you could write an extension method None() for the interface IEnumerable which is checking whether the enumerable is empty.
public static bool None(this IEnumerable values)
{
return !values.Any();
}
With this, None() can be used on any IEnumerable in your code base having access to the extension method (in fact, Any(), Select(), Where(), etc. are extension methods as well, lying in the System.Linq namespace).

Why have an API and an implementation?

Many times, I've seen single class (Java) implement a single interface. That interface is only used for the single class. No other class implements it. Why do we do this? It seems like to me, we don't need the interface, just the class.
Example: https://github.com/essentials/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/I18n.java
Forget about the language for a sec.
There are many reasons to use interfaces and having just one class implement an interface is absolutely fine.
Imagine you want to write testable code, you want to do all the good stuff, have tests etc.
A good way to write code is to never ever hard-code any dependencies in a class. It makes life a lot easier if you inject dependencies and that is done via an interface or abstract class. So you basically never say hey class, here's a cat implementation, you say hey here's a generic animal, use that.
The interface has that one job to provide a contract and that's what you are using. You are thus decoupling your code from dependencies, so now you're able to test it and you can mock all your dependencies easily. The fact that you have one or more implementation makes no difference whatsoever.

Call another class static method results in coupling

In OOP we don't want coupling of classes. If I want to use an instance of class b within class a I can use dependency injection.
However if I want to use static methods of class b within class a I dont see any option but to "require" or "import" class b in the class a class file. This ends up with coupling between the classes - going against OOP principles. But the alternative is to rewrite the static method of class b as a static method in class a - going against the DRY principle. What is the right way?
This question was flagged as a possible duplicate of How to use Dependency Injection with Static Methods? but I feel that my question is asking from a more generic perspective on using another class' static methods. The think the question and accepted answer in the possible duplicate is more specific to a use case, but would not apply for example to a mere utility static method in the external class. My question aims to seek answer from a general oop perspective.
There are a variety options here and the specific use case is important in deciding what you may want to do. So, the big three would be...
Migrate the static method off Class B and into a shared library class, which is purely a holder for static methods and is never instantiated (in Java you'd make the constructor private and the class final). Then both class A and class B can access the method without depending on each other and without violating the DRY principle and the dependency on the library class is no better nor worse than relying on a static method defined on the same class.
If you're talking about a static method which is really something that best lives on class B then you can hide that method call behind some kind of a provider instance which is dependency injected into class A, with the provider implementation simply calling the static method on B. If you wanted to be really evil then the provider could also be injected into instances of B, but that would probably be overkill.
The static method can be changed to be an instance method on a new class which is dependency injected into both A and B. Sometimes this has a side-benefit of allowing you to hide some state in the instance rather than having to pass parameters into an otherwise stateless method.
Note that static methods in general cause problems in OO terms so only really the third options is a 'clean' one that really decouples classes and properly allow for coding to interfaces.

Is it good practice for every public method to be covered by an interface?

It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.

Interface uses as like this

If interfaces have empty methods (implicit abstract method) then what is its use? Why do we say it reduces the code and provides re-usability? Give me a real life example of using an interface that shows the difference between an abstract class and an interface.
Interface is more like a contract. It doesn't provide any implementation reuse as such. Which actually makes your code de-coupled from implementation. Having a abstract class with ALL the methods abstract provides the same benefit (if we ignore the issue of multiple inheritance).
For a really good example take a look at Java Collections and how things are loosely coupled using interfaces for Collection, Map and Lists.
Because of the terminology you are using, I am going to assume you are talking about Java.
An interface is useful in lieu of an abstract class because a class can only inherit from a single class, but can implement multiple interfaces.
An interface is a contract between parts of the program. It says that one part of the program has certain expectations about classes that implement this interface. As long as those classes uphold that interface contract, the other parts of the program don't care how that contract is implemented, just that it is implemented.
It allows for polymorphism and for the reuse of code. For instance, (with respect to Java), you can take the List interface. You can write code that interfaces with a List object where you don't care about the implementation of the List. Your code then can be used with a LinkedList or an ArrayList or any other type of list that it may deal with, and it should be able to manage well enough. You can write code now that has certain expectations through this List interface contract, and 15 years down the road someone can use the latest technologies to create their own List implementation and your code will be able to use it.
Abstract class lets you describe fields and non abstract methods. It does not limit you to simply describing interface, it involves some logic. Interface on other hand does what it says and has nothing to do with logic. From client code side, you have no worries about implementation and how stuff works. It lets you exchange one interface realization with other without additional code.
On realization code side, interface lets you perform multiple "inheritance".
I like to call these types of features "implied code documentation". Using an interface can communicate a lot of information to other developers who will be working on your project, and this information can help prevent a lot of headaches.
For instance, if a class implements an interface that has 2 methods, and I'm new to the project, that may tell me that the developer who wrote those methods don't want the method signature to change.
Think about the Dog class and the Cat class that both implement the interface Sociable, where there are methods walk(int speed), sit(), layDown(), bite(int degree).
If we have a Dog class and a Cat class that implement these methods and there are dependencies on them, changing the method signature of one could have some negative effects.
Interfaces are a way to help describe a class. In this example, a Sociable Dog and a Sociable Cat have a lot in common.
As far as reusability goes, your classes become reusable because it's harder for others to come in and change the contract defined in the method signature.
Lastly, while a class can only subclass one class, it can implement multiple interfaces. Thus, the advantage of using an interface is that I can have a Dog that implements Big and Sociable, and a Cat that implements Small and Sociable.