Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2021-02-20 23:10:26


Andrzej Krzemienski wrote:
...
> So, I want to apply the Dependency Injection philosophy. I get:
>
> class State
> {
> Rect area;
> Point location;
> // invariant: location is inside area;
> public:
> State(Rect a, Point loc) : area{a}, location{loc} {}
> };
>
> int main()
> {
> State s{Rect{{0, 0}, {2, 2}}, Point{1, 1}};
> }
> ```
>
> Now, I choose to use the DI-library (this is where I have troubles with
> understanding: why would I want to do that?).

You are thinking in C++ (value semantics) but you need to be thinking in
Java (reference semantics, OOP, object DAGs.) Suppose you need to have a
logger object

shared_ptr<ILogger> pl; // new FileLogger( log_file_name fn );

and a database connector object (which uses a logger to log things)

shared_ptr<IDbConn> pdb; // new MysqlDb( mysql_db_info mdi,
shared_ptr<ILogger> pl )

and an abstract configuration query interface, that can use an .ini file, or
a JSON file, or a database

shared_ptr<IConfig> pc; // new DbConfig( shared_ptr<IDbConn> pdb,
shared_ptr<ILogger> pl );

Now when you need to create the config query object, you need to give it a
database connector and a logger, and you also need to give the same logger
to the database connector. So with [NotYetBoost].DI you'll write something
like

auto injector = make_injector(
    bind<log_file_name>.to( "something.log" ),
    bind<ILogger>.to<FileLogger>(),
    bind<>.to( mysql_db_info{ ... } ),
    bind<IDbConn>.to<MysqlDb>(),
    bind<IConfig>.to<DbConfig>()
);

auto cfg = injector.create<IConfig>();

although I don't really know if this will compile or work. :-)

Now imagine that same thing but with 10 objects, or 20 objects. Also imagine
that your day to day vocabulary includes "business logic", "enterprise",
"UML" and "XML".


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk