Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Coding to an interface is argued to be a good practice, allowing for the possibility to change an object later without affecting program behavior, but why do we need to change something if it does not have an effect? I understand the flexibility that this practice gives, I just do not understand the definition.
They mean you are able to change the implementation of that class and you will be 100% sure the rest of the program isn't broken after the change. Because you do not change a single line outside of that class implementation. Of course you can break the implementation.
Using interfaces doesn't just allow you to change the implementation of a class. It also allows you to change the class itself. Details after the break.
Interfaces also serve to reduce the mental effort needed to develop (and understand) complex code. If you can clearly define the interaction between two parts of your program then work can proceed on both parts without one knowing how the other implements the interface. This happy situation can continue until both parts are ready to be put together, when something called "integration testing" takes place.
Interface, in the sense described above, is quite an abstract concept. The signature of a function, for instance, is an "interface".
Other forms of interfaces are constructs that use the interface keyword (e.g. in Java or C#) or classes with pure virtual methods (in C++). When people say "programming to an interface" they usually refer to these constructs.
Not the best example in the world, but but suppose we have this:
interface ICooking
{
void Chop();
void Grill();
// other cooking functions
}
which is implemented by this class:
class Chef implements ICooking
{
void Chop()
{
...
}
void Grill()
{
...
}
// other cooking functions
}
And now you want to write a function that makes a steak. You will need someone to operate the kitchen (i.e. someone that implements ICooking).
You could write the function like this:
void MakeASteak( Chef ThePersonWhoCooks )
{
...
}
and call it as:
Chef Joe;
MakeASteak( Joe );
or you could write it like this:
void MakeASteak( ICooking ThePersonWhoCooks )
{
...
}
and call it as:
Chef Joe;
MakeASteak( Joe );
You should observe the following:
you call MakeASteak exactly the same in both cases
you can change the implementation of Chef::Grill and, as long as it still "grills" (e.g. you go from medium-rare to medium) you don't need to change the code in MakeASteak
This is one of the benefits of using a clearly defined interface. As long as the Grill method does what it is supposed to do, its callers don't need to know how it does it.
The second version is quite different. This is the one people have in mind when they say "program to an interface". It allows one to add this:
class HomeCook implements ICooking
{
void Chop()
{
...
}
void Grill()
{
...
}
// other cooking functions
}
and call
HomeCook AverageJoe;
MakeASteak( AverageJoe );
So, if the MakeASteak function only uses the methods defined in ICooking then not only does it not care how the ICooking functions are implemented, it also doesn't care what object implements the interface.
You can then also use complex objects:
Class ComplicatedPerson implements ICooking, IWriting, IActing, ISwimming
{
}
and use it just like before:
ComplicatedPerson person;
MakeASteak( person );
Another example would be the std algorithms that use iterators. The library writer only needs to know that the iterator "iterates" and can focus on the algorithm itself. The programmer responsible for writing the iterator code for a vector or for a set can focus on his code without having to worry about the binary search algorithm details. If both programmers do their job properly then the algorithm will be usable no matter what container provides the iterators.
Related
There're likely no more than 2-4 widely used approaches to this problem.
I have a situation in which there's a common class I use all over the place, and (on occasion) I'd like to give it special abilities. For arguments sake, let's say that type checking is not a requirement.
What are some means of giving functionality to a class without it being simply inheritance or member functions?
One way I've seen is the "decorator" pattern in which a sort of mutator wraps around the class, modifies it a bit, and spits out a version of it with more functions.
Another one I've read about but never used is for gaming. It has something to do with entities and power-ups/augments. I'm not sure about the specifics, but I think they have a list of them.
???
I don't need specific code of a specific language so much as a general gist and some keywords. I can implement from there.
So as far as I understand, you're looking to extend an interface to allow client-specific implementations that may require additional functionality, and you want to do so in a way that doesn't clutter up the base class.
As you mentioned, for simple systems, the standard way is to use the Adaptor pattern: subclass the "special abilities", then call that particular subclass when you need it. This is definitely the best choice if the extent of the special abilities you'll need to add is known and reasonably small, i.e. you generally only use the base class, but for three-to-five places where additional functionality is needed.
But I can see why you'd want some other possible options, because rarely do we know upfront the full extent of the additional functionality that will be required of the subclasses (i.e. when implementing a Connection API or a Component Class, each of which could be extended almost without bound). Depending on how complex the client-specific implementations are, how much additional functionality is needed and how much it varies between the implementations, this could be solved in a variety of ways:
Decorator Pattern as you mentioned (useful in the case where the special entities are only ever expanding the pre-existing methods of the base class, without adding brand new ones)
class MyClass{};
DecoratedClass = decorate(MyClass);
A combined AbstractFactory/Adaptor builder for the subclasses (useful for cases where there are groupings of functionality in the subclasses that may differ in their implementations)
interface Button {
void paint();
}
interface GUIFactory {
Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class ApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory());
}
public static GUIFactory createOsSpecificFactory() {
int sys = readFromConfigFile("OS_TYPE");
if (sys == 0) return new WinFactory();
else return new OSXFactory();
}
}
The Strategy pattern could also work, depending on the use case. But that would be a heavier lift with the preexisting base class that you don't want to change, and depending on if it is a strategy that is changing between those subclasses. The Visitor Pattern could also fit, but would have the same problem and involve a major change to the architecture around the base class.
class MyClass{
public sort() { Globals.getSortStrategy()() }
};
Finally, if the "special abilities" needed are enough (or could eventually be enough) to justify a whole new interface, this may be a good time for the use of the Extension Objects Pattern. Though it does make your clients or subclasses far more complex, as they have to manage a lot more: checking that the specific extension object and it's required methods exist, etc.
class MyClass{
public addExtension(addMe) {
addMe.initialize(this);
}
public getExtension(getMe);
};
(new MyClass()).getExtension("wooper").doWoop();
With all that being said, keep it as simple as possible, sometimes you just have to write the specific subclasses or a few adaptors and you're done, especially with a preexisting class in use in many other places. You also have to ask how much you want to leave the class open for further extension. It might be worthwhile to keep the tech debt low with an abstract factory, so less changes need to be made when you add more functionality down the road. Or maybe what you really want is to lock the class down to prevent further extension, for the sake of understand-ability and simplicity. You have to examine your use case, future plans, and existing architecture to decide on the path forward. More than likely, there are lots of right answers and only a couple very wrong ones, so weigh the options, pick one that feels right, then implement and push code.
As far as I've gotten, adding functions to a class is a bit of a no-op. There are ways, but it seems to always get ugly because the class is meant to be itself and nothing else ever.
What has been more approachable is to add references to functions to an object or map.
I've seen this asked before but I still need some clarification on where exactly the functions declared in an interface are fully defined? I understand the interface lays out and explains functions that another contract (contractB) can use but is the interface just a convenience and not a necessity for contractB to use those functions? In my mind I'm confusing delegateCall with interfaces. If we want to call functions from other contracts, why use interfaces rather than delegateCall? If the contract address pointed to by the interface has a function defined but I do not outline it in the interface, can I still use it in contractB?
For example, below I know I can use transfer function in crowdsale but where is transfer? Let's say contract A has function makepovertyhistory() defined but I do not mention it in the interface token...can I still use it in the crowdsale contract?
If I redefine the transfer function inside the interface, does it overwrite the transfer function defined at the address instantiated within crowd sale contract? I'm not sure if I'm thinking about this all correctly so thought I would ask more detailed questions in case anyone else found the generic answers still to general to build a visual of what's going on.
It might be helpful to also distinguish why we would use an interface instead of inheriting a contract directly into my currently being created contract
interface token {
function transfer(address receiver, uint amount);
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
....
....
..
Interfaces in Solidity are really no different than interfaces in any OOP. They allow you to code towards a stub without knowing the underlying implementation. If a new version of a contract that implements the interface is needed, your contract that uses it doesn't need to change.
This allows you to address one of the common problems in smart contracts: upgradable contracts. By using an interface, you can deploy a new version of a contract, then update any existing contracts with the new address.
Simplified example (obviously, this would not pass basic security checks, but you get the idea).
interface I {
someMethod();
}
contract C {
I i;
C(address _addr) {
i = I(_addr);
}
doSomething() {
i.someMethod();
}
upgrade(address _newAddr) {
i = _newAddr;
}
}
Providing this type of separation (and using libraries) makes upgrading contracts much easier and cheaper.
For example, below I know I can use transfer function in crowdsale but
where is transfer? Let's say contract A has function
makepovertyhistory() defined but I do not mention it in the interface
token...can I still use it in the crowdsale contract?
No, it needs to be imported or defined somewhere.
If I redefine the transfer function inside the interface, does it
overwrite the transfer function defined at the address instantiated
within crowd sale contract?
It depends on how you're calling the transfer function. If you're executing it on the address of a deployed contract, then you are using that deployed contract's implementation.
A more in-depth example can be found in this blog post.
I don't quite get the concept of software reuse ... Wikipedia provided "code reuse" & "re-usability" nothing specific about SOFTWARE reuse ... Please, if you could explain the concept clearly, I'd be grateful.
The name is self-explanatory. There is some software that you want to reuse. It is quite simple to understand.
I will use Java to explain reusability so please bear with me.
class Parent{
int[] numbers;
public void supplyNumbers(int[] someNumbers){
this.numbers = someNumbers;
}
public void performSorting(){
for(int i=0;i<numbers.length;i++){
//perform sorting here
}
}
}
So there is a class Parent that has an array of numbers and two methods to supply the numbers and perform some sorting operation on it.
Now, I want to create another class that needs similar such functions. Instead of re-writing the code, all I would do is I would inherit the code as follows:
class Child extends Parent{
}
So where is the code ? Well, I do not need to write anything as it will be automatically provided to me as I have inherited it from the Parent class.
I am reusing what I wrote previously. This is code reusability.
Also, when you make imports in Java, you are reusing the code the devs wrote. :)
This question already has answers here:
What is the point of interfaces in PHP?
(15 answers)
Closed 8 years ago.
From php.net:
Object interfaces allow you to create code which specifies which methods
a class must implement, without having to define how these methods are handled.
Why should I need to do that? Could it be a kind of 'documentation'?
When I'm thinking about a class I have to implement, I know exactly which methods I should code.
What are some situations where interfacing a class is a "best practice"?
Short answer: uniform interfaces and polymorphism.
Longer answer: you can obviously just create a class that does everything and indeed you'd know what methods to write. The problem you have with using just concrete classes, however, is your lack of ability to change. Say you have a class that stores your users into a MySQL database, let's call it a UserRepository. Imagine the following code:
<?php
class UserRepositoryMysql {
public function save( User $user ) {
// save the user.
}
}
class Client {
public function __construct( UserRepositoryMysql $repos ) {
$this->repos = $repos;
}
public function save( User $user ) {
$this->repos->save( $user );
}
}
Now, this is all good, as it would actually work, and save the User to the database. But imagine your application will become populair, and soon, there is a question to support PostgreSQL as well. You'll have to write a UserRepositoryPostgresql class, and pass that along instead of UserRepositoryMysql. Now, you've typehinted on UserRepositoryMysql, plus you're not certain both repositories use the same methods. As an aside, there is little documentation for a potential new developer on how to implement his own storage.
When you rewrite the Client class to be dependent upon an interface, instead of a concrete class, you'll have an option to "swap them out". This is why interfaces are useful, obviously, when applied correctly.
First off, my php object coding is way behind my .net coding, however, the principles are the same. the advantages of using interfaces in your classes are many fold. Take for example the case where you need to return data from a search routine. this search routine may have to work across many different classes with completely different data structures. In 'normal' coding, this would be a nightmare trying to marry up the variety of different return values.
By implementing interfaces, you add a responsibility to the clsses that use them to produce a uniform set of data, no matter how disparate they may be. Another example would be the case where you are pulling data from different 'providers' (for example xml, json, csv etc, etc). By implementing an interface on each class type, you open up the possibilities to extend your data feeds painlessly by adding new classes that implement the interface, rather than having a mash-up of switch statements attempting to figure out what your intentions are.
In a word, think of an interface as being a 'contract' that the class 'must' honour. lnowing that means that you can code with confidence for that given scenario with only the implementation detail varying.
Hope this helps.
[edit] - see this example on SO for a fairly simple explanation:
An interface is a concept in Object Oriented programming that enables polymorphism. Basically an interface is like a contract, that by which classes that implement it agree to provide certain functionality so that they can be used the same way other classes that use the interface
purpose of interface in classes
The first case that comes to my mind is when you have a class that uses certain methods of another class. You don't care how this second class works, but expects it to have particular methods.
Example:
interface IB {
public function foo();
}
class B implements IB {
public function foo() {
echo "foo";
}
}
class A {
private $b;
public function __construct( IB $b ) {
$this->b = $b;
}
public function bar() {
$this->b->foo();
}
}
$a = new A( new B() );
$a->bar(); // echos foo
Now you can easily use different object passed to the instance of class A:
class C implements IB {
public function foo() {
echo "baz";
}
}
$a = new A( new C() );
$a->bar(); // echos baz
Please notice that the same bar method is called.
You can achieve similar results using inheritance, but as PHP does not support multiple inheritance, interfaces are better - class can implement more than one interface.
You can review one of PHP design patterns - Strategy.
Say you're creating a database abstraction layer. You provide one DAL object that provides generic methods for interfacing with a database and adapter classes that translate these methods into specific commands for specific databases. These adapters themselves need to have a generic interface, so the DAL object can talk to them in a standardized way.
You can specify the interface the adapters need to have using an Interface. Of course you can simply write some documentation that specifies what methods an adapter needs to have, but writing it in code enables PHP to enforce this interface for you. It enables PHP to throw helpful error messages before a single line of code is executed. Otherwise missing methods could only be found during runtime and only if you actually try to call them, which makes debugging a lot harder and code much more unreliable.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
This question about unit testing best practices mentions designing classes for dependency injection. This got me thinking as to what exactly that might mean.
Having just started working with inversion of control containers I have some ideas on the issue, so let me throw them against the wall and see what sticks.
The way I see it, there are three basic types of dependencies that an object can have.
Object Dependency - An actual object that will be used by the class in question. For example LogInVerifier in a LogInFormController. These should be injected in through the constructor. If the class is sufficiently high level that it requires more than 4 of these objects in the constructor consider breaking it up or at the very least using a factory pattern. You should also consider providing the dependency with an interface and coding against the interface.
A Simple Setting - For example a threshold or a timeout period. These should generally have a default value and be set via a builder of factory pattern. You can also provide constructor overloads which set them. However in most cases you probably shouldn't be forcing the client to have to set it up explicitly.
A Message Object - An object that is handed off from one class to another which the receiving class presumably uses for business logic. An example would be a User object for a LogInCompleRouter class. Here I find it is often better for the message not to be specified in the constructor as you would then have to either register the User instance with the IoC Container (making it global) or not instantiate the LogInCompleteRouter until after you have an instance of User (for which you couldn't use DI or at least would need an explicit dependency on the Container). In this case it would be better to pass in the message object in only when you need it for the method call (ie. LoginInCompleteRouter.Route(User u); ).
Also, I should mention that not everything should be DI'ed, if you have a simple bit of functionality that was just convenient to factor out to a throw-away class, it is probably ok to instantiate on the spot. Obviously this is a judgement call; if I found it expedient to write a class such as
class PasswordEqualsVerifier {
public bool Check(string input, string actual) { return input===actual;}
}
I probably wouldn't bother dependency injecting it and would just have an object instantiate it directly inside a using block. The corollary being that if it is worth writing unit tests for, then it is probably worth injecting.
So what do you guys think? Any additional guidelines or contrasting opinions are welcome.
The important thing is to try to code to interfaces and the have your classes accept instances of those interfaces rather than create the instances themselves. You can obviously go crazy with this, but it's a general good practice regardless of unit testing or DI.
For example, if you have a Data Access Object, you might be inclined to write a base for all DAOs like this:
public class BaseDAO
{
public BaseDAO(String connectionURL,
String driverName,
String username, String password)
{
// use them to create a connection via JDBC, e.g.
}
protected Connection getConnection() { return connection; }
}
However, it would be better to remove this from the class in favor of an interface
public interface DatabaseConnection
{
Connection getConnection();
}
public class BaseDAO
{
public BaseDAO(DatabaseConnection dbConnection)
{
this.dbConnection = dbConnection;
}
protected Connection getConnection() { return dbConnection.getConnection(); }
}
Now, you can provide multilple imlementations of DatabaseConnection. Even ignoring unit testing, if we assume we are using JDBC, there are two ways to get a Connection : a connection pool from the container, or directly via using the driver. Now, your DAO code isn't coupled to either strategy.
For testing, you can make a MockDatabaseConnection that connects to some embedded JDBC implementation with canned data to test your code.