Adapter Pattern: Class Adapter vs Object Adapter - oop

I have a few questions about the Adapter pattern. I understand that the class adapter inherits from the adaptee while the object adapter has the adaptee as an object rather than inheriting from it.
When would you use a class adapter over an object adapter and vice versa? Also, what are the trade-offs of using the class adapter and the trade-offs of the object adapter?

I can see one advantage for the object adapter, depending on your programming language: if the latter does not support multiple inheritance (such as Java, for instance), and you want to adapt several adaptees in one shot, you'll be obliged to use an object adapter.
Another point for object adapter is that you can have the wrapped adaptee live his life as wanted (instantiation notably, as long as you instantiate your adapter AFTER your adaptee), without having to specify all parameters (the part for your adapter AND the part for your adaptee because of the inheritance) when you instantiate your adapter. This approach appears more flexible to me.

Prefer to use composition, over inheritance
First say we have a user;
public interface IUser
{
public String Name { get; }
public String Surname { get; }
}
public class User : IUser
{
public User(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
}
Now, imagine that for any reason, youre required to have an adapter for the user class, we have then two aproaches, by inheritance, or by composite;
//Inheritance
public class UserAdapter1 : User
{
public String CompleteName { get { return base.Name + " " + base.Surname } }
}
//Composition
public class UserAdapter2
{
private IUser user;
public UserAdapter2(IUser user)
{
this.user = user;
}
public String CompleteName { get { return this.user.Name + " " + this.user.Surname; } }
}
You are totally ok, but just if the system don't grow... Imagine youre required to implement a SuperUser class, in order to deal with a new requirement;
public class SuperUser : IUser
{
public SuperUser(String name, String surname)
{
this.Name = name;
this.Surname = surname;
}
public String Name { get; private set; }
public String Surname { get; private set; }
public Int32 SupernessLevel { get { return this.Name.Length * 100; } }
}
By using inheritance you would not be able to re-use your adapter class, messing up your code (as your would have to implement another adapter, inheriting from SuperUser that would do ECXATLY the same thing of the other class!!!)... Interface usage is all about uncopling, thats the main reason that I'm 99% likely to use them, of course, if the choice is up to me.

Class Adapter is plain old Inheritance, available in every object-oriented language, while Object Adapter is a classic form of an Adapter Design Pattern.
The biggest benefit of Object Adapter compared to Class Adapter ( and thus Inheritance ) is loose coupling of client and adaptee.

A class adapter uses multiple inheritance to adapt one interface to another: (depending on your programming language: Java & C# does not support multiple inheritance)
An object adapter depends on object composition:
Images Source: Design Pattern (Elements of Reusable Object-Oriented Software) book

class adapters adapts Adaptee to Target by committing to a specific Adapter class will not work when we want to adapt a class and its subclasses.
object adapters lets a single Adapter work with many Adaptees (the Adaptee and all adaptees hierarchy)

In addition to what renatoargh has mentioned in his answer I would like to add an advantage of class adapter.
In class adapter you can easily override the behavior of the adaptee if you need to because you are just subclassing it. And it is harder in Object adapter.
However advantages of object adapter usually outweighs this tiny advantage of class adapter.

Related

Connection String retrieved from one DB to be used in a Class Library to access a 2nd DB...Suggestions?

Environment:
.Net, SQL Server, WinForms Desktop
Control Database (db1)
Customer Databases (db2, db3, db4, etc.)
Background:
Each of our customers requires their own database. It's a contractual obligation due to compliance with standards in certain industries. Certain users of our application only have access to specific databases.
Scenario:
The application user's username gets passed into our control database (db1) from the app on load. There's a lookup in there that determines what customer this user has access to and returns connection string info for connecting to the database of the determined customer (db2 or db3 or db4 or etc.) to be used for the life of the runtime. All of my business logic is in a DAL, as it should be, in a .Net class library.
Suggestions on the best way/ways to get the connection string information into the DAL WITHOUT passing into every constructor/method that is called on the DAL.
I came up with one possible solution, but want to pick your brains to see if there's another or better way.
Possible Solutions:
A Global module in the DAL that has public fields like "dbServer" and "dbName".
Set those and then use the DAL as needed. They would need to be set each time the DAL is used throughout the application, but at least I don't have to make the signature of every single constructor and method require connection string information.
A settings file (preferably XML) that the app writes to after getting the connection info and the DAL reads from for the life of the runtime.
Thoughts and/or suggestions? Thanks in advance.
A set up like this might help. If you are going the IoC way, then you can remove the parameterized constructor and make Connection object a dependency too. However, you will need to feed your dependency injection provider in code since connection string comes from database.
public class User
{
public string ConnectionString
{
get; set;
}
}
public class SomeBusinessEntity
{
}
public class CallerClass
{
public IBaseDataAccess<SomeBusinessEntity> DataAccess
{
get;
set;
}
public void DoSomethingWithDatabase(User user)// Or any other way to access current user
{
// Either have specific data access initialized
SpecificDataAccess<SomeBusinessEntity> specificDataAccess = new SpecificDataAccess<SomeBusinessEntity>(user.ConnectionString);
// continue
// have dependency injection here as well. Your IoC configuration must ensure that it does not kick in until we get user object
DataAccess.SomeMethod();
}
}
public interface IBaseDataAccess<T>
{
IDbConnection Connection
{
get;
}
void SomeMethod();
// Other common stuff
}
public abstract class BaseDataAccess<T> : IBaseDataAccess<T>
{
private string _connectionString;
public BaseDataAccess(string connectionString)
{
_connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
return new SqlConnection(_connectionString);
}
}
public abstract void SomeMethod();
// Other common stuff
}
public class SpecificDataAccess<T> : BaseDataAccess<T>
{
public SpecificDataAccess(string connectionString) : base(connectionString)
{
}
public override void SomeMethod()
{
throw new NotImplementedException();
}
public void SomeSpecificMethod()
{
using (Connection)
{
// Do something here
}
}
}
Create a ConnectionStringProvider class that will provide you the connection string
public class ConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider
// uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Using ConnectionStringProvider in your DAL
public class MyCustomerDAL
{
private ConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
_connectionStringProvider = new ConnectionStringProvider();
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
Setting/changing the connection string
new ConnectionStringProvider()
.SetCustomerConnectionString(connString);
Note
The reason i chose to use method instead of a get/set property in ConnectionStringProvider is because maybe in the future you decide to read/write these from a file, and while you could read/write from file in a property it's misleading to your consumer who thinks that a property will be a simple performance-less hit.
Using a function tells your consumer there might be some performance hit here, so use it wisely.
A little abstration for unit testing
Here is a slight variation that will enable you to abstract for unit testing (and eventually IoC)
public class MyCustomerDAL
{
private IConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
//since not using IoC, here you have to explicitly new it up
_connectionStringProvider = new ConnectionStringProvider();
}
//i know you don't want constructor, i included this to demonstrate how you'd override for writing tests
public MyCustomerDAL(IConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
// this interface lives either in a separate abstraction/contracts library
// or it could live inside of you DAL library
public interface IConnectionStringProvider
{
string GetCustomerConnectionString();
void SetCustomerConnectionString(string connectionString);
}
public class ConnectionStringProvider : IConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Appendix A - Using IoC and DI
Disclaimer: the goal of this next piece about IoC is not to say one way is right or wrong, it's merely to bring up the idea as another way to approach solving the problem.
For this particular situation Dependency Injection would make your solving the problem super simple; specifically if you were using an IoC container combined with constructor injection.
I don't mean it would make the code more simple, that would be more or less the same, it would make the mental side of "how do I easily get some service into every DAL class?" an easy answer; inject it.
I know you said you don't want to change the constructor. That's cool, you don't want to change it because it is a pain to change all the places of instantiation.
However, if everything were being created by IoC, you would not care about adding to constructors because you would never invoke them directly.
Then, you could add services like your new IConnectionStringProvider right to the constructor and be done with it.

Simple Injector Property Injection

How do you perform property injection with Simple Injector.
The with Ninject you do is as per bellow:
[Inject]
public IUnitOfWork UnitOfWork { get; set; }
How can I do the equivalent to this with Simple Injector. I tried finding a solution online but had no luck.
Why do I want to use Property Injection?
I want to use property injection to set up unit of work in my base controller so that it will create a new unit of work OnActionExecuting and commit the changes OnResultExecuted. It also means I don't have to pass in the UoW with each new controller I create through the constructor.
Another option is to use the RegisterInitializer method:
container.RegisterInitializer<BaseControllerType>(controller =>
{
controller.UnitOfWork = container.GetInstance<IUnitOfWork>();
}
It keeps all configuration in your composition root and does not pollute your code base with all kinds of attributes.
Update: (as promised)
While this is a direct answer to your question I have to provide you with a better option, because the usage of a base class for this is a IMO not the correct design, for multiple reasons.
Abstract classes can become real PITA classes as they tend to grow towards a god class which has all kinds of cross cutting concerns
An abstract class, especially when used with property injection, hides the needed dependencies.
With focus on point 2. When you want to unit test a controller which inherits from the base controller, you have no way of knowing that this controller is dependent on IUnitOfWork. This you could solve by using constructor injection instead of property injection:
protected abstract class BaseController : Controller
{
protected readonly IUnitOfWork uoW;
protected BaseController (IUnitOfWork uoW)
{
this.uoW = uoW;
}
}
public class SomeController : BaseController
{
public SomeController(IUnitOfWork uoW) : base(uoW) { }
}
While this solves point 2, point 1 is still lurking. The main reason you're wanting this, as you say, is because you do not want to commit your changes in every Action method. Changes must just be saved by the context when the request is done. And thinking about design in this way is a good thing, because Saving changes is, or can be seen as a cross cutting concern and the way you're implementing this is more or less known as AOP.
If it's comes to AOP, especially if you're working with atomic actions in the action methods of your controllers, there is a far better, more SOLID and more flexible design possible which deals with this very nicely.
I'm referring to the Command/Handler pattern which is described in great detail here (also read this for the query part of your application).
With this patterns you don't inject a generic IUnitOfWork abstraction, but inject the specific needed ICommandHandler<TCommand> abstractions.
The action methods would fire the responsible commandhandler for this specific action. All commandhandlers can simple be decorated by a single open-generic SaveChangesCommandHandlerDecorator, 'ValidationDecorator', 'CheckPermissionsDecorator', etc...
A quick example:
public class MoveCustomerCommand
{
public int CustomerId;
public Address NewAddress;
}
public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
// retrieve customer from database
// change address
}
}
public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decoratee;
private readonly DbContext db;
public SaveChangesCommandHandlerDecorator(
ICommandHandler<TCommand> decoratee, DbContext db)
{
this.decoratee = decoratee;
this.db = db;
}
public void Handle(TCommand command)
{
this.decoratee.Handle(command);
this.db.SaveChanges();
}
}
// Register as
container.Register(typeof(ICommandHandler<>), new []{Assembly.GetExecutingAssembly() });
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(SaveChangesCommandHandlerDecorator<>));
// And use in controller as
public ActionResult MoveCustomer(int customerId, Address address)
{
var command = new MoveCustomerCommand
{ CustomerId = customerId, Address = address };
this.commandHandler.Handle(command);
return View(new ResultModel());
}
This keeps your controllers clean and let it do what it must do, namely be the layer between the business logic (the commandhandler implementation in this case) and the view.
Need to create the following:
First create the attribute class
[System.AttributeUsage(System.AttributeTargets.Property]
public class Inject : Attribute
{
}
Then create a custom property behavior
class PropertySelectionBehavior<TAttribute> : IPropertySelectionBehavior
where TAttribute : Attribute
{
public bool SelectProperty(Type type, PropertyInfo prop)
{
return prop.GetCustomAttributes(typeof(TAttribute)).Any();
}
}
Finally tell the container to use custom behavior
container.Options.PropertySelectionBehavior = new PropertySelectionBehavior<Inject>();
All that is left to do is decorate the property with the attribute
[Inject]
public IUnitOfWork UnitOfWork { get; set; }

How to do logic based on object ID

Suppose I have a game, where there are buildings sorted by type. Each type is represented as a separate class, but sometimes I have to do some uncommon logic for the buildings of the same type. How could one implement this kind of behaviour?
For example, I can identify buildings by ID, so I can have a giant switch or command pattern inside the building type class. But I think that something is not right with this approach.
Another approach is to have different class for any divergent logic. But this proposes a lot of small classes.
This is what polymorphism aims to solve, and one of the big differences between procedural and oop programming. You can achieve it through extending a base class, or by implementing an interface. Here is extending a base class:
public abstract class Building {
abstract void destroy();
}
public BrickBuilding extends Building {
#Override
public void destroy() {
bricks.fallToGround();
}
}
public HayBuilding extends Building {
#Override
public void destroy() {
straw.blowInWind();
}
}
In places in your code where you would have used a switch statement to switch on building type, just hold a reference to the abstract Building type, and call method destroy() on it:
public class BuildingDestroyer {
public void rampage() {
for(Building building : allTheBuildings) {
// Could be a BrickBuilding, or a HayBuilding
building.destroy();
}
}
}
Or, to address your concern about having a lot of small types, you can 'inject' a destroy behaviour you want into a common building type, like so...albeing, you will end up with a lot of different destroy behaviour classes too...so, this might not be a solution.
public interface DestroyBehaviour {
void destroy(Building building);
}
public class Building {
private int id;
public DestroyBehaviour destroyBehaviour;
public Building(int id, DestroyBehaviour destroyBehaviour) {
this.id = id;
this.destroyBehaviour = destroyBehaviour;
}
public void destroy() {
destroyBehaviour.destroy(this); // or something along those lines;
}
}
You can get rid of the giant switch by having a BuildingFactory class which exposes a registerBuildingType(typeName, instanceCreatorFunc) method, that each building class calls (from a static initialize method for example) and that gets called with a unique string for that class (class name would suffice) and a static "create" method that returns a new instance.
This approach also has the advantage of being able to load new buildings from dynamically linked libraries.

What design choice use in this scenario to avoid violating the LSP?

I'm refactoring a few applications (scrapers) I've created into one single application. There are a few scrapers, like TwitterScraper, FacebookScraper, etc. The names are just for explaining better the problem.
Let's suppose I want to retrieve people using those scrapers. We could search using different ways in each scraper. For example, in Facebook we could search by Name, Age, etc.... or simply get all the users in some specific group, which means we have two ways of searching there. The same can happen to Twitter, and others...
I thought about having the following design:
public interface IScraper {
IEnumerable<User> Search(IParameter parameters);
}
and then have:
public class FacebookGroupsScraper : IScraper {
public IEnumerable<User> Search(IParameter parameters) {
//... search here using the group url, etc.
}
}
public class FacebookOtherScraper : IScraper {
public IEnumerable<User> Search(IParameter parameters) {
//... search here using the name, age, country, or whatever...
}
}
but I'm definitely violating the Liskov Substitution Principle, since I would have to do something like this in each method:
public class FacebookOtherScraper : IScraper {
public IEnumerable<User> Search(IParameter parameters) {
var p = parameters as FacebookOtherParameter;
//We can only work here with the expected parameters
//(FacebookOtherParameter class in this case)
}
}
What would be a good way to design it?
It looks like the difference between implementations are the types of parameters they take.
Therefore, in order to adhere to the LSP I think it is better to change your interface to either have separate methods or to have separate interfaces, each with a different method that take different types of parameters:
//... search here using the group url, etc.
public interface GroupScrapper{
IEnumerable<User> SearchByGroup(IGroupParameter parameters...);
}
//... search here using the name, age, country, or whatever...
public interface UserInfoScrapper{
IEnumerable<User> SearchByInfo(IInfoParameter parameters...);
}
or as a single interface:
public interface IScraper {
IEnumerable<User> SearchByGroup(IGroupParameter parameters...);
IEnumerable<User> SearchByInfo(IInfoParameter parameters...);
}
This way every implementation will meet the contract of one of the methods.
The problem with this approach is you would have to have a pretty static parameter set that is fully known ahead of time. If you have to keep adding new types of parameters then the number of methods and/or interfaces will explode.
I usually do generic for this case. (please note the code below may not compile)
public interface IScraper<T> where T : IParameter
{
IEnumerable<User> Search(T parameters);
}
public class FacebookParameter : IParameter{
public string GroupUrl{ get; set; }
}
public class FacebookGroupsScraper : IScraper<FacebookParameter> {
public IEnumerable<User> Search(FacebookParameter parameters) {
//... search here using the group url, etc.
}
}
However I forgot about how to use it at consumer level though.

.NET Dynamic Decision to Call Similar Classes?

C# on .NET 4.5:
public Interface IMyInterface
{
public string DoSomething( string input1 )
}
public MyClass1 : IMyInterface
{
public string DoSomething( string input1 )
{
return "1";
}
}
public MyClass2 : IMyInterface
{
public string DoSomething( string input1 )
{
return "2";
}
}
At runtime, I want to detect the hosting environment, set some kind of "global", and then based on the global always instance and use MyClass1 or MyClass2. I do not want to have a single "MyClass" and then do lots of case logic inside it to detect the environment.
What is a good pattern or practice to do that? Is this actually a good place for Dynamics?
Thanks.
Seems like you need to use Factory. Create a method in Factory class to return MyClass object. Keep the return type of the method as IMyInterface. Within the method, you can execute your hosting logic and depending upon the output of hosting logic, instantiate proper class and return the reference to the object.