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 2 years ago.
Improve this question
Background
When developing an application, my approach (rightly or wrongly) is to separate the logic into a Framework (Kit)
The reason(s) for this are fairly straight forward ..
• I like being able to test the logic in isolation
• I like that it forces me to forget about the UI and any UI assumptions
• I like that I am free to create the app using a separate UI .. depending on device (iPhone, Watch .. Apple TV .. Command Line Utility)
The Problem
because I like the logic in a separate framework .. I have introduced a complexity in terms of access modifiers (Public, Internal, Private) for classes, structs, enums, methods, properties.
What I have most trouble with is properties (and properties of Entities in particular)
I prefer not to expose the setter to the consumer of the Framework (i.e. the UI Application)
Within a Module I would typically use the.
private(set) var nameOfProperty
approach.
However this isn’t an option to me in entities of a framework.
So for a framework, I would much rather return a Protocol describing the interface of an Entity
.. i.e. it’s writable properties, it’s read-only properties and it’s accessible methods
We (Swift Developers) have been encouraged down the route of naming Protocols according to a behaviour .. however,
.. for example, a Football/Soccer Team Selection framework I wouldn’t want to be passing back and forth something that conforms to ‘Player-able’, ‘Manager-able’, ‘Fixture-able’
.. I want to pass back and forth a ‘Player’, ‘Manager’, ‘Fixture’ (as the consumer would rightfully expect)
Question
What should I be naming my Entity (assuming it conforms to a commonly known as Protocol) ?
Understandably, we can not have a Protocol called protocol Player and class Player
Some Suggested Ideas
Idea 1: Use underscoring within the framework (my most likely approach)
e.g.
public protocol Player {
public var name: String { get }
}
public class _Player: Player {
..
}
Idea 2: Don’t use protocols, but use computed properties instead (not preferred)
e.g.
public class Player {
private var _name: String
public var name: String {
get {
return _name
}
}
Idea 3: Don’t use protocols, because you're the only consumer then trust yourself and make everything public 🤪
e.g.
public class Player {
public var name: String
}
Idea 4: Use a substitute name within the framework (a bit like underscoring)
e.g.
public protocol Player {
public var name: String { get }
}
public class PlayerEntity: Player {
..
}
or
public class PlayerImpl: Player {
..
}
or
public class PlayerObj: Player {
..
}
Personally, I'd go with Player: PlayerProtocol, unless you are going to be using the protocol much more often. There are some examples of this in the standard library, such as StringProtocol and IteratorProtocol.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What does this line means "Swift doesn’t require you to create separate interface and implementation files for custom structures and classes."
link
It is referring to the old C-style way of separating interfaces and implementations in separate .h and .c (.m for ObjC/.mm for ObjC++) files.
In Swift, you no longer need to deal with this - interfaces are generated by the compiler.
For example:
public class Loader {
private let resource: URL
init(resource: URL) { self.resource = resource }
public func load {
//..
}
}
Generates an interface (effectively, an API) with only the public members exposed:
public class Loader {
init(resource: URL)
public func load()
}
The key here is, that there no longer needs to be a separate file maintained by the developer. The interfaces are generated (or not) based on the access control levels defined on your types.
In objective C you have different files for interface called .h file and for implementation of that interface you have .m file
but in swift you have .swift file in which you implement the functionality so you don't need to create two separate files in swift
thats what docs are referring to ... hope it helps
happy coding =)
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.
I've been creating a prototype for a modern MUD engine. A MUD is a simple form of simulation and provide a good method in which to test a concept I'm working on. This has led me to a couple of places in my code where things, are a bit unclear, and the design is coming into question (probably due to its being flawed). I'm using model first (I may need to change this) and I've designed a top down architecture of game objects. I may be doing this completely wrong.
What I've done is create a MUDObject entity. This entity is effectively a base for all of my other logical constructs, such as characters, their items, race, etc. I've also created a set of three meta classes which are used for logical purposes as well Attributes, Events, and Flags. They are fairly straightforward, and are all inherited from MUDObject.
The MUDObject class is designed to provide default data behavior for all of the objects, this includes deletion of dead objects. The automatically clearing of floors. etc. This is also designed to facilitate this logic virtually if needed. For example, checking a room to see if an effect has ended and deleting the the effect (remove the flag).
public partial class MUDObject
{
public virtual void Update()
{
if (this.LifeTime.Value.CompareTo(DateTime.Now) > 0)
{
using (var context = new ReduxDataContext())
{
context.MUDObjects.DeleteObject(this);
}
}
}
public virtual void Pause()
{
}
public virtual void Resume()
{
}
public virtual void Stop()
{
}
}
I've also got a class World, it is derived from MUDObject and contains the areas and room (which in turn contain the games objects) and handles the timer for the operation to run the updates. (probably going to be moved, put here as if it works would limit it to only the objects in-world at the time.)
public partial class World
{
private Timer ticker;
public void Start()
{
this.ticker = new Timer(3000.0);
this.ticker.Elapsed += ticker_Elapsed;
this.ticker.Start();
}
private void ticker_Elapsed(object sender, ElapsedEventArgs e)
{
this.Update();
}
public override void Update()
{
this.CurrentTime += 3;
// update contents
base.Update();
}
public override void Pause()
{
this.ticker.Enabled = false;
// update contents
base.Pause();
}
public override void Resume()
{
this.ticker.Enabled = true;
// update contents
this.Resume();
}
public override void Stop()
{
this.ticker.Stop();
// update contents
base.Stop();
}
}
I'm curious of two things.
Is there a way to recode the context so that it has separate
ObjectSets for each type derived from MUDObject?
i.e. context.MUDObjects.Flags or context.Flags
If not how can I query a child type specifically?
Does the Update/Pause/Resume/Stop architecture I'm using work
properly when placed into the EF entities directly? given than it's for
data purposes only?
Will locking be an issue?
Does the partial class automatically commit changes when they are made?
Would I be better off using a flat repository and doing this in the game engine directly?
1) Is there a way to recode the context so that it has separate ObjectSets for each type derived from MUDObject?
Yes, there is. If you decide that you want to define a base class for all your entities it is common to have an abstract base class that is not part of the entity framework model. The model only contains the derived types and the context contains DbSets of derived types (if it is a DbContext) like
public DbSet<Flag> Flags { get; set; }
If appropriate you can implement inheritance between classes, but that would be to express polymorphism, not to implement common persistence-related behaviour.
2) Does the Update/Pause/Resume/Stop architecture I'm using work properly when placed into the EF entities directly?
No. Entities are not supposed to know anything about persistence. The context is responsible for creating them, tracking their changes and updating/deleting them. I think that also answers your question about automatically committing changes: no.
Elaboration:
I think here it's good to bring up the single responsibility principle. A general pattern would be to
let a context populate objects from a store
let the object act according to their responsibilities (the simulation)
let a context store their state whenever necessary
I think Pause/Resume/Stop could be responsibilities of MUD objects. Update is an altogether different kind of action and responsibility.
Now I have to speculate, but take your World class. You should be able to express its responsibility in a short phrase, maybe something like "harbour other objects" or "define boundaries". I don't think it should do the timing. I think the timing should be the responsibility of some core utility which signals that a time interval has elapsed. Other objects know how to respond to that (e.g. do some state change, or, the context or repository, save changes).
Well, this is only an example of how to think about it, probably far from correct.
One other thing is that I think saving changes should be done not nearly as often as state changes of the objects that carry out the simulation. It would probably slow down the process dramatically. Maybe it should be done in longer intervals or by a user action.
First thing to say, if you are using EF 4.1 (as it is tagged) you should really consider going to version 5.0 (you will need to make a .NET 4.5 project for this)
With several improvements on performance, you can benefit from other features also. The code i will show you will work for 5.0 (i dont know if it will work for 4.1 version)
Now, let's go to you several questions:
Is there a way to recode the context so that it has separate
ObjectSets for each type derived from MUDObject? If not how can I
query a child type specifically?
i.e. context.MUDObjects.Flags or context.Flags
Yes, you can. But to call is a little different, you will not have Context.Worlds you will only have the base class to be called this way, if you want to get the set of Worlds (that inherit from MUDObject, you will call:
var worlds = context.MUDObjects.OfType<World>();
Or you can do in direct way by using generics:
var worlds = context.Set<World>();
If you define you inheritance the right way, you should have an abstract class called MUDObjects and all others should iherit from that class. EF can work perfectly with this, you just need to make it right.
Does the Update/Pause/Resume/Stop architecture I'm using work properly
when placed into the EF entities directly? given than it's for data
purposes only?
In this case i think you should consider using a Design Pattern called Strategy Pattern, do some research, it will fit your objects.
Will locking be an issue?
Depends on how you develop the system....
Does the partial class automatically commit changes when they are
made?
Did not understand that question.... Partial classes are just like regular classes, thay are just in different files, but when compiled (or event at Design-Time, because of the vshost.exe) they are in fact just one.
Would I be better off using a flat repository and doing this in the
game engine directly?
Hard to answer, it all depends on the requirements of the game, deploy strategy....
Sorry to ask sich a generic question, but I've been studying these and, outside of say the head programming conveying what member MUST be in a class, I just don't see any benefits.
There are two (basic) parts to object oriented programming that give newcomers trouble; the first is inheritance and the second is composition. These are the toughest to 'get'; and once you understand those everything else is just that much easier.
What you're referring to is composition - e.g., what does a class do? If you go the inheritance route, it derives from an abstract class (say Dog IS A Animal) . If you use composition, then you are instituting a contract (A Car HAS A Driver/Loan/Insurance). Anyone that implements your interface must implement the methods of that interface.
This allows for loose coupling; and doesn't tie you down into the inheritance model where it doesn't fit.
Where inheritance fits, use it; but if the relationship between two classes is contractual in nature, or HAS-A vs. IS-A, then use an interface to model that part.
Why Use Interfaces?
For a practical example, let's jump into a business application. If you have a repository; you'll want to make the layer above your repository those of interfaces. That way if you have to change anything in the way the respository works, you won't affect anything since they all obey the same contracts.
Here's our repository:
public interface IUserRepository
{
public void Save();
public void Delete(int id);
public bool Create(User user);
public User GetUserById(int id);
}
Now, I can implement that Repository in a class:
public class UserRepository : IRepository
{
public void Save()
{
//Implement
}
public void Delete(int id)
{
//Implement
}
public bool Create(User user)
{
//Implement
}
public User GetUserById(int id)
{
//Implement
}
}
This separates the Interface from what is calling it. I could change this Class from Linq-To-SQL to inline SQL or Stored procedures, and as long as I implemented the IUserRepository interface, no one would be the wiser; and best of all, there are no classes that derive from my class that could potentially be pissed about my change.
Inheritance and Composition: Best Friends
Inheritance and Composition are meant to tackle different problems. Use each where it fits, and there are entire subsets of problems where you use both.
I was going to leave George to point out that you can now consume the interface rather than the concrete class. It seems like everyone here understands what interfaces are and how to define them, but most have failed to explain the key point of them in a way a student will easily grasp - and something that most courses fail to point out instead leaving you to either grasp at straws or figure it out for yourself so I'll attempt to spell it out in a way that doesn't require either. So hopefully you won't be left thinking "so what, it still seems like a waste of time/effort/code."
public interface ICar
{
public bool EngineIsRunning{ get; }
public void StartEngine();
public void StopEngine();
public int NumberOfWheels{ get; }
public void Drive(string direction);
}
public class SportsCar : ICar
{
public SportsCar
{
Console.WriteLine("New sports car ready for action!");
}
public bool EngineIsRunning{ get; protected set; }
public void StartEngine()
{
if(!EngineIsRunning)
{
EngineIsRunning = true;
Console.WriteLine("Engine is started.");
}
else
Console.WriteLine("Engine is already running.");
}
public void StopEngine()
{
if(EngineIsRunning)
{
EngineIsRunning = false;
Console.WriteLine("Engine is stopped.");
}
else
Console.WriteLine("Engine is already stopped.");
}
public int NumberOfWheels
{
get
{
return 4;
}
}
public void Drive(string direction)
{
if (EngineIsRunning)
Console.WriteLine("Driving {0}", direction);
else
Console.WriteLine("You can only drive when the engine is running.");
}
}
public class CarFactory
{
public ICar BuildCar(string car)
{
switch case(car)
case "SportsCar" :
return Activator.CreateInstance("SportsCar");
default :
/* Return some other concrete class that implements ICar */
}
}
public class Program
{
/* Your car type would be defined in your app.config or some other
* mechanism that is application agnostic - perhaps by implicit
* reference of an existing DLL or something else. My point is that
* while I've hard coded the CarType as "SportsCar" in this example,
* in a real world application, the CarType would not be known at
* design time - only at runtime. */
string CarType = "SportsCar";
/* Now we tell the CarFactory to build us a car of whatever type we
* found from our outside configuration */
ICar car = CarFactory.BuildCar(CarType);
/* And without knowing what type of car it was, we work to the
* interface. The CarFactory could have returned any type of car,
* our application doesn't care. We know that any class returned
* from the CarFactory has the StartEngine(), StopEngine() and Drive()
* methods as well as the NumberOfWheels and EngineIsRunning
* properties. */
if (car != null)
{
car.StartEngine();
Console.WriteLine("Engine is running: {0}", car.EngineIsRunning);
if (car.EngineIsRunning)
{
car.Drive("Forward");
car.StopEngine();
}
}
}
As you can see, we could define any type of car, and as long as that car implements the interface ICar, it will have the predefined properties and methods that we can call from our main application. We don't need to know what type of car is - or even the type of class that was returned from the CarFactory.BuildCar() method. It could return an instance of type "DragRacer" for all we care, all we need to know is that DragRacer implements ICar and we can carry on life as normal.
In a real world application, imagine instead IDataStore where our concrete data store classes provide access to a data store on disk, or on the network, some database, thumb drive, we don't care what - all we would care is that the concrete class that is returned from our class factory implements the interface IDataStore and we can call the methods and properties without needing to know about the underlying architecture of the class.
Another real world implication (for .NET at least) is that if the person who coded the sports car class makes changes to the library that contains the sports car implementation and recompiles, and you've made a hard reference to their library you will need to recompile - whereas if you've coded your application against ICar, you can just replace the DLL with their new version and you can carry on as normal.
So that a given class can inherit from multiple sources, while still only inheriting from a single parent class.
Some programming languages (C++ is the classic example) allow a class to inherit from multiple classes; in this case, interfaces aren't needed (and, generally speaking, don't exist.)
However, when you end up in a language like Java or C# where multiple-inheritance isn't allowed, you need a different mechanism to allow a class to inherit from multiple sources - that is, to represent more than one "is-a" relationships. Enter Interfaces.
So, it lets you define, quite literally, interfaces - a class implementing a given interface will implement a given set of methods, without having to specify anything about how those methods are actually written.
Maybe this resource is helpful: When to Use Interfaces
It allows you to separate the implementation from the definition.
For instance I can define one interface that one section of my code is coded against - as far as it is concerned it is calling members on the interface. Then I can swap implementations in and out as I wish - if I want to create a fake version of the database access component then I can.
Interfaces are the basic building blocks of software components
In Java, interfaces allow you to refer any class that implements the interface. This is similar to subclassing however there are times when you want to refer to classes from completely different hierarchies as if they are the same type.
Speaking from a Java standpoint, you can create an interface, telling any classes that implement said interface, that "you MUST implement these methods" but you don't introduce another class into the hierarchy.
This is desireable because you may want to guarantee that certain mechanisms exist when you want objects of different bases to have the same code semantics (ie same methods that are coded as appropriate in each class) for some purpose, but you don't want to create an abstract class, which would limit you in that now you can't inherit another class.
just a thought... i only tinker with Java. I'm no expert.
Please see my thoughts below. 2 different devices need to receive messages from our computer. one resides across the internet and uses http as a transport protocol. the other sits 10 feet away, connect via USB.
Note, this syntax is pseudo-code.
interface writeable
{
void open();
void write();
void close();
}
class A : HTTP_CONNECTION implements writeable
{
//here, opening means opening an HTTP connection.
//maybe writing means to assemble our message for a specific protocol on top of
//HTTP
//maybe closing means to terminate the connection
}
class B : USB_DEVICE implements writeable
{
//open means open a serial connection
//write means write the same message as above, for a different protocol and device
//close means to release USB object gracefully.
}
Interfaces create a layer insulation between a consumer and a supplier. This layer of insulation can be used for different things. But overall, if used correctly they reduce the dependency density (and the resulting complexity) in the application.
I wish to support Electron's answer as the most valid answer.
Object oriented programming facilitates the declaration of contracts.
A class declaration is the contract. The contract is a commitment from the class to provide features according to types/signatures that have been declared by the class. In the common oo languages, each class has a public and a protected contract.
Obviously, we all know that an interface is an empty unfulfilled class template that can be allowed to masquerade as a class. But why have empty unfulfilled class contracts?
An implemented class has all of its contracts spontaneously fulfilled.
An abstract class is a partially fulfilled contract.
A class spontaneously projects a personality thro its implemented features saying it is qualified for a certain job description. However, it also could project more than one personality to qualify itself for more than one job description.
But why should a class Motorcar not present its complete personality honestly rather than hide behind the curtains of multiple-personalities? That is because, a class Bicycle, Boat or Skateboard that wishes to present itself as much as a mode of Transport does not wish to implement all the complexities and constraints of a Motorcar. A boat needs to be capable of water travel which a Motorcar needs not. Then why not give a Motorcar all the features of a Boat too - of course, the response to such a proposal would be - are you kiddin?
Sometimes, we just wish to declare an unfulfilled contract without bothering with the implementation. A totally unfulfilled abstract class is simply an interface. Perhaps, an interface is akin to the blank legal forms you could buy from a stationary shop.
Therefore, in an environment that allows multiple inheritances, interfaces/totally-abstract-classes are useful when we just wish to declare unfulfilled contracts that someone else could fulfill.
In an environment that disallows multiple inheritances, having interfaces is the only way to allow an implementing class to project multiple personalities.
Consider
interface Transportation
{
takePassengers();
gotoDestination(Destination d);
}
class Motorcar implements Transportation
{
cleanWindshiedl();
getOilChange();
doMillionsOtherThings();
...
takePassengers();
gotoDestination(Destination d);
}
class Kayak implements Transportation
{
paddle();
getCarriedAcrossRapids();
...
takePassengers();
gotoDestination(Destination d);
}
An activity requiring Transportation has to be blind to the millions alternatives of transportation. Because it just wants to call
Transportation.takePassengers or
Transportation.gotoDestination
because it is requesting for transportation however it is fulfilled. This is modular thinking and programming, because we don't want to restrict ourselves to a Motorcar or Kayak for transportation. If we restricted to all the transportation we know, we would need to spend a lot of time finding out all the current transportation technologies and see if it fits into our plan of activities.
We also do not know that in the future, a new mode of transport called AntiGravityCar would be developed. And after spending so much time unnecessarily accommodating every mode of transport we possibly know, we find that our routine does not allow us to use AntiGravityCar. But with a specific contract that is blind any technology other than that it requires, not only do we not waste time considering all sorts of behaviours of various transports, but any future transport development that implements the Transport interface can simply include itself into the activity without further ado.
None of the answers yet mention the key word: substitutability. Any object which implements interface Foo may be substituted for "a thing that implements Foo" in any code that needs the latter. In many frameworks, an object must give a single answer to the question "What type of thing are you", and a single answer to "What is your type derived from"; nonetheless, it may be helpful for a type to be substitutable for many different kinds of things. Interfaces allow for that. A VolkswagonBeetleConvertible is derived from VolkswagonBeetle, and a FordMustangConvertible is derived from FordMustang. Both VolkswagonBeetleConvertible and FordMustangConvertible implement IOpenableTop, even though neither class' parent type does. Consequently, the two derived types mentioned can be substituted for "a thing which implements IOpenableTop".
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.