The IRepository interface - subsonic3

I am reading the source code of subsonic 3.
in the file IRepository.cs I found the following:
public interface IRepository<T>
{
IQueryable<T> GetAll();
PagedList<T> GetPaged<TKey>(Func<T, TKey> orderBy, int pageIndex, int pageSize);
...many other lines
bool Load<T>(T item, Expression<Func<T, bool>> expression) where T : class, new();
bool Load<T>(T item, string column, object value) where T : class, new();
}
Notice the Load methods are defined as generic and their generic type names are the same as the generic type of the interface, which cause complier warnings.
My questions is: Are the Load methods really intended to be generic or it was a mistake? If the methods were intended to be generic, should we change the type name from "T" to something different like "E" in order to make the compiler happy?

They're not supposed to be different - Load is supposed to work on the repos "type" so you can remove the definition there (I assume that's what you're doing)

They have constraints, unlike the class-level T, so I'd guess they're supposed to be different.

Looks to me like the class and new constraints should be at the class level - not the method level.
Otherwise, yeah - you just defined 2 different T constraints which is just confusing as hell, since I could do this:
IRepository<int> intRepository = new RepositoryImpl<int>();
object o;
intRepository.Load<string>(o, "column", "value");
Having a IRepository<int> Load<string> seems rather odd to me.
It's possible that T must only be a class and new for the Load methods, but not the others. In that case, you may want something like:
interface IRepository<T> {
IQueryable<T> GetAll();
bool Load<TClass>(TClass item, string column, object value) where TClass : class, T, new();
}
which isn't exactly the same, since TClass could just inherit from T - but is the closest constraint I can think of to produce that result.

Related

How can I access a private (non-static) method in C++?

Currently I am working on a project where I want to control a model train for a nice showcase.
I have multiple locomotives which all have a unique address (just think of it as a UUID). Some locomotives have a headlight, some of them have a flashing light, some have both and some of them have none.
My base class is this:
class GenericLocomotive : public Nameable, public Describable {
private:
uint16_t address;
public:
GenericLocomotive(const char* name, const char* description, uint16_t address);
void setFunction(uint8_t command, bool val);
Now I want to have a different class which provides the functionality to enable and disable the headlight:
class HasHeadLight {
public:
void activateHeadlight();
void deactivateHeadlight();
}
My goal is to have a specific class for every locomotive (with different functionality) which looks something like this:
class <SpecificLocomotive> : public GenericLocomotive, public HasHeadlight, public HasFlashlight,... {
...
}
The problem is, that I must have access to the private field 'address' of my GenericLocomotive class and I also have to call the function setFunction(...) from my HasHeadlight class.
I am quite new to C++ and just found out about the concept of friend classes and methods, but I can not quite get it to work, because even with the declaration of the method setFunction(...) as a friend, I can not just call something like
this->setFunction(HEADLIGHT_COMMAND, true);
from my HasHeadlight-class, because the function is not declared in 'this'.
How can I access the method from my other class? Is this friend thing even needed or is there a completely different way to structure my C++ program?
You have misunderstood how class inheritance works:
Inheritance establishes an is-a relationship between a parent and a child. The is-a relationship is typically stated as as a specialization relationship, i.e., child is-a parent.
There are many ways you can tackle what you want to achieve here, but this is not it. You're on the right track as far as treating the different train components as separate objects, and one way to achieve that would be to instead make each component a member of the specialized locomotive:
class HeadLight {
public:
void activateHeadlight();
void deactivateHeadlight();
}
class SpecialLocomotive : public GenericLocomotive {
HeadLight mHeadlight;
Flashlight mFlashlight;
public:
SpecialLocomotive(const char* name, const char* description, uint16_t address)
: GenericLocomotive(name, description, address) {
setFunction(HEADLIGHT_COMMAND, true);
}
void toggleLight(bool on) {
if (on) {
mHeadlight.activateHeadlight();
} else {
mHeadlight.void deactivateHeadlight();
}
}
/* so on and so forth /*
}
There's not enough details to go further with it. If you need to call setFunction from within Headlight, I would consider that a poor design choice, but there are other ways.

Is there a name for this C++ idiom in which a type vends a wrapper that expands its interface?

I have what is essentially a family of types that share a few common properties with each other. I could actually model this relationship fairly decently with C++ class inheritance. However, I also need to pass and store these objects all around my code, and keeping every instance as a polymorphic heap reference is a pain.
Here's the initial situation:
Enumeration type with values for all "subclasses":
enum class PhoneType {
landline,
cell
}
Type that's stored and passed around a lot:
class Phone {
public:
static Phone landline(PhoneNumber number) {
return Phone(PhoneType::landline, number);
}
static Phone cell(PhoneNumber number, optional<AppList> apps) {
return Phone(PhoneType::cell, number, apps)
}
PhoneType type() { return _type; }
PhoneNumber number() { return _number; }
private:
PhoneType _type;
PhoneNumber _number;
optional<AppList> _apps;
Phone(PhoneType type, PhoneNumber number) :
_type(type), _number(number)
{}
Phone(PhoneType type, PhoneNumber number, optional<AppList> apps) :
_type(type), _number(number), _apps(apps)
{}
};
PhoneType enumerates different possible types of Phones, which all have a PhoneNumber and may or may not have an AppList.
The issue is how to go about giving the outside world access to a phone's AppList once the caller is sure that it's dealing with a cell phone. Note that I don't want to simply vend the optional type, as this pushes a lot of error checking code into the calling function(s), which is not what I want (in the majority of cases, the caller knows the PhoneType of the Phone it's being passed without even having to check, so vending an optional<> is just unnecessary pain).
I could just add the extra accessors to the Phone class, and document that they throw/crash/etc. if the receiving Phone doesn't represent a cell phone. However, in the real code there are many more such attributes that would require more accessors, and each of these accessors is not at all clear about its preconditions when read at a call site.
Long story short, after a bit of consideration I ended up with this idiom:
Before the definition of Phone:
class CheckedPhoneRef {
public:
CheckedPhoneRef() = delete;
Phone& phone() const { return * _phone; }
protected:
Phone* _phone;
CheckedPhoneRef(Phone* phone) : _phone(phone) {}
private:
friend class Phone;
};
class LandlineCheckedPhoneRef : public CheckedPhoneRef {
public:
using CheckedPhoneRef::CheckedPhoneRef;
};
class CellCheckedPhoneRef : public CheckedPhoneRef {
public:
using CheckedPhoneRef::CheckedPhoneRef;
AppList apps() const; // accesses private member of referenced Phone
};
In Phone's public section:
// (Comment above declarations in header):
// These assert that this Phone is of the correct PhoneType.
LandlineCheckedPhoneRef landline_ref() {
assert(_type == PhoneType::landline);
return LandlineCheckedPhoneRef(this);
}
CellCheckedPhoneRef cell_ref() {
assert(_type == PhoneType::cell);
return CellCheckedPhoneRef(this);
}
// (Plus const versions)
In Phone's private section:
friend LandlineCheckedPhoneRef;
friend CellCheckedPhoneRef;
Now it is rather clear what assumptions are being made at any given call site: if I say phone.cell_ref() then I'm clearly asserting that this phone is a cell phone, e.g.,
void call(Phone& phone) {
if (phone.type() == PhoneType::cell) {
if (has_facetime(phone.cell_ref())) ...
} else {
...
}
}
bool has_facetime(CellCheckedPhoneRef cell_phone) {
return cell_phone.apps() ...
}
(Dumb example, but you get the point. I know I could use a visitation pattern here, but the real code isn't quite like this.)
I like this design for what I'm doing. Problem is, I don't quite know what to name the vended wrapper types. I'm currently using the pattern of LandlinePhoneLens, CellPhoneLens, etc., but I know that "lens" already has other meaning in programming. Perhaps this isn't a big issue, but I wanted to ask to be sure I'm not missing a more established naming scheme.
Is there an established name for this pattern/idiom in which a type vends a wrapper that expands its interface?
Your intent is unfortunately not fully clear to me.
At first, I thought that you'd just reinvented the decorator pattern, in which you add dynamically some responsibilities (accessor) to an existing object.
But looking more closely, I think that it all just looks like an anti-pattern, a dependency mess, and a flawed design: eveytime that in the base class you need to be friend of derived class, you should have alarm bells starting to ring.
Instead of looking for a name, you'd better engineer a cleaner design. Forget the enum, and go for an abstract Phone base class, with abstract functions corresponding to what every phone shall be able to do. Then create two derived concrete classes: LandLine and CellPhone, both inheriting from Phone.
Now you could consider that getting the list of apps is a common functionality of all kind of phones, and that a LandLine just returns an empty list. All your code would then just use build in polymorphism to do the job in a proper an extensible way:
If tomorrow, someone would invent a TelepathyPhone, you'd just need to impelement the common functions required by the abstract interface, and all the using code would still work unchanged.
In the worst case, if you'd really need to call a very specific class dependent function that was totally unknown in the common interface (e.g. TelepathyPhone::displayBrainWavelength()), you could go for an if using dynamic_cast. At least you'd avoid to create a new enum everytime you invent a new derived class.

Call base class method with enum parameter with "derived" enum

my question looks like a duplicate of about a million questions found on SO but I can't find a satisfying solution.
I'm currently working on a little import/export dll for a specific file format which is build in a block-like structure with different types of blocks referencing each other.
EDIT: Each block type has its own functionality and provides different information with different data types and so on. So they're not just giving aliases for their links. Sorry about that confusion, I broke them down to be as simple as possible to just describe the problem I have.
So every block of data has some information and holds a list of links to other blocks (which may be empty). Links are just 64bit values representing the absolute byte offset inside the file.
A typical case for inheritance: BaseBlock and some derived block types.
As every block can have some links I gave my base class an array of links and implemented a method that returns a link specified by an enum acting as a "named index":
typedef uint64_t LINK;
class BaseClass
{
public:
enum BlockLink;
LINK getLink(BlockLink link) {
if(m_link_count < link) {
return m_links[link];
}
return 0;
}
private:
LINK* m_links;
uint64_t m_link_count;
}
In every derived class I would then define this enum just like:
Class ABlock: public virtual BaseBlock
{
public:
enum BlockLink {
link_to_f_block = 0,
link_to_another_f_block = 1,
...
link_to_d_block = 5
}
}
Class BBlock: public virtual BaseBlock
{
public:
enum BlockLink {
link_to_nice_a_block = 0,
link_to_evil_h_block = 1,
...
link_to_strange_t_block = 5
}
}
That would make accessing a link elegant by just using:
ABlock* aBlock;
...
/* some stuff that initializes aBlock */
...
LINK linkToDBlock = aBlock->getLink(ABlock::link_to_d_block);
The user would see there is an enum for accessing links and he doesn't need to know the index or stuff, while I wouldn't need to implement a method for each link in every derived block to get a self explaining way to access them.
Unfortunately this doesn't work as these enums are not compatible. So doing this I'm getting something like
The argument of type "ABlock::BlockLink" is not compatible with parameter of type "BaseBlock::BlockLink"
So, is there an elegant way of doing something like that? Something like a "named access" or whatever you would call it?

Common interface for all derived classes

I have base class Item which store some data and grant access to it by accessors, like:
class Item{
(...)
public:
int get_value();
double get_weight();
ItemMaterial get_material();
(...)
}
Then I've got derived classes like Weapon, Armor which add some additional data:
class Weapon : public Item {
(...)
public:
int get_dmg();
(...)
}
I store these Items in some container:
std::vector<Item*> inventory;
And here comes the problem with interface - how to get access to derived class data? I was thinking, and got 3 ideas:
1. Separate interfaces
Each derived class adds its data, like it is shown above, and then use dynamic_cast:
Item *item = new Weapon;
int dmg = dynamic_cast<Weapon*>(item)->get_dmg();
2. Common interface class
Make an interface class with all accessors:
ItemInterface{
public:
virtual int get_value() = 0; //Item interface
virtual double get_weight() = 0;
(..)
virtual int get_dmg() = 0; //Weapon interface
(...)
}
And then something like this:
Item : public ItemInterface{ (...) }
and
Weapon : public Item { (...) }
and finally we can access the data:
Item *item = new Weapon;
int dmg = item->get_dmg();
3. Combination with templates and enums
This idea is maybe a little weird :-) but:
implement enum with all item data:
enum class ItemData{
Value,
Weight,
Material, //Item data
(...)
Damage, //Weapon data
(...)
Defense, //armor data etc.
(...)
Null
}
and in base class some template function like this:
template<typename T>
T get_data(ItemData data){
switch(data){
case ItemData::Value: return _value; break;
case ItemData::Damage: return _dmg; break;
(...)
}
}
and access data like:
Item *item = new Weapon;
ind dmg = item->get_data<int>(ItemData::Damage);
===
How do you think it should be done? I will be grateful for any advices!
Regards.
Your second and third option is obviously not the way to go - whenever you add a new type of item, you will also have to change the base class or the enum - that is definitely not what you want to if you need any basic form of maintainability in your code.
And here comes the problem with interface - how to get access to derived class data
First you have to think of "where will your code do this"? Most of your code dealing with the whole inventory should only use the content as Item*, using only functions from the Item class.
If you have code specificially dealing with Weapon objects, the place where the Weapon objects are created (and inserted into the inventory), may also add them to another variable, maybe a weapons list in form of a
std::vector<Weapon*> weapons;
or to a member variable Weapon* of a class Warrior or something like that (but beware, you now will have two pointers to the same objects, so you have to think about ownership). So the code dealing only with weapons (for example, a member function of Warrior) does not access the inventory to get a Weapon object, it will always use the Weapon* directly.
If, for some reasons, you have to write some code which does something for all weapons from your inventory, then write a single function which extracts all Weapon objects using the dynamic_cast (or even better: make it an iterator function), and reuse this function whenever you need to get access to all weapons. So you don't clutter your code all over with dynamic casts, but keep this in just one place.
EDIT: another alternative (avoiding the dynmic cast) is using the visitor pattern, see this post. But I don't really like the answer of that post, in the presented form it will imply a cyclic dependency "Base -> Visitor -> Derived -> Base", which is IMHO a bad design.
ValueType Weapon::getProprtyValue( PropertyType id ) {
switch( id ) {
case kWeaponProperty01: return m_weaponProperty01;
...
default: return Item::getPropertyValue( id );
}
}
You can make some kind of universal accessor method, though it have some limitations, it could be quite handy, especially in case of content editors, serialization etc.

A better design pattern than factory?

In the code I am now creating, I have an object that can belong to two discrete types, differentiated by serial number. Something like this:
class Chips {
public:
Chips(int shelf) {m_nShelf = shelf;}
Chips(string sSerial) {m_sSerial = sSerial;}
virtual string GetFlavour() = 0;
virtual int GetShelf() {return m_nShelf;}
protected:
string m_sSerial;
int m_nShelf;
}
class Lays : Chips {
string GetFlavour()
{
if (m_sSerial[0] == '0') return "Cool ranch";
else return "";
}
}
class Pringles : Chips {
string GetFlavour()
{
if (m_sSerial.find("cool") != -1) return "Cool ranch";
else return "";
}
}
Now, the obvious choice to implement this would be using a factory design pattern. Checking manually which serial belongs to which class type wouldn't be too difficult.
However, this requires having a class that knows all the other classes and refers to them by name, which is hardly truly generic, especially if I end up having to add a whole bunch of subclasses.
To complicate things further, I may have to keep around an object for a while before I know its actual serial number, which means I may have to write the base class full of dummy functions rather than keeping it abstract and somehow replace it with an instance of one of the child classes when I do get the serial. This is also less than ideal.
Is factory design pattern truly the best way to deal with this, or does anyone have a better idea?
You can create a factory which knows only the Base class, like this:
add pure virtual method to base class: virtual Chips* clone() const=0; and implement it for all derives, just like operator= but to return pointer to a new derived. (if you have destructor, it should be virtual too)
now you can define a factory class:
Class ChipsFactory{
std::map<std::string,Chips*> m_chipsTypes;
public:
~ChipsFactory(){
//delete all pointers... I'm assuming all are dynamically allocated.
for( std::map<std::string,Chips*>::iterator it = m_chipsTypes.begin();
it!=m_chipsTypes.end(); it++) {
delete it->second;
}
}
//use this method to init every type you have
void AddChipsType(const std::string& serial, Chips* c){
m_chipsTypes[serial] = c;
}
//use this to generate object
Chips* CreateObject(const std::string& serial){
std::map<std::string,Chips*>::iterator it = m_chipsTypes.find(serial);
if(it == m_chipsTypes.end()){
return NULL;
}else{
return it->clone();
}
}
};
Initialize the factory with all types, and you can get pointers for the initialized objects types from it.
From the comments, I think you're after something like this:
class ISerialNumber
{
public:
static ISerialNumber* Create( const string& number )
{
// instantiate and return a concrete class that
// derives from ISerialNumber, or NULL
}
virtual void DoSerialNumberTypeStuff() = 0;
};
class SerialNumberedObject
{
public:
bool Initialise( const string& serialNum )
{
m_pNumber = ISerialNumber::Create( serialNum );
return m_pNumber != NULL;
}
void DoThings()
{
m_pNumber->DoSerialNumberTypeStuff();
}
private:
ISerialNumber* m_pNumber;
};
(As this was a question on more advanced concepts, protecting from null/invalid pointer issues is left as an exercise for the reader.)
Why bother with inheritance here? As far as I can see the behaviour is the same for all Chips instances. That behaviour is that the flavour is defined by the serial number.
If the serial number only changes a couple of things then you can inject or lookup the behaviours (std::function) at runtime based on the serial number using a simple map (why complicate things!). This way common behaviours are shared among different chips via their serial number mappings.
If the serial number changes a LOT of things, then I think you have the design a bit backwards. In that case what you really have is the serial number defining a configuration of the Chips, and your design should reflect that. Like this:
class SerialNumber {
public:
// Maybe use a builder along with default values
SerialNumber( .... );
// All getters, no setters.
string getFlavour() const;
private:
string flavour;
// others (package colour, price, promotion, target country etc...)
}
class Chips {
public:
// Do not own the serial number... 'tis shared.
Chips(std::shared_ptr<SerialNumber> poSerial):m_poSerial{poSerial}{}
Chips(int shelf, SerialNumber oSerial):m_poSerial{oSerial}, m_nShelf{shelf}{}
string GetFlavour() {return m_poSerial->getFlavour()};
int GetShelf() {return m_nShelf;}
protected:
std::shared_ptr<SerialNumber> m_poSerial;
int m_nShelf;
}
// stores std::shared_ptr but you could also use one of the shared containers from boost.
Chips pringles{ chipMap.at("standard pringles - sour cream") };
This way once you have a set of SerialNumbers for your products then the product behaviour does not change. The only change is the "configuration" which is encapsulated in the SerialNumber. Means that the Chips class doesn't need to change.
Anyway, somewhere someone needs to know how to build the class. Of course you could you template based injection as well but your code would need to inject the correct type.
One last idea. If SerialNumber ctor took a string (XML or JSON for example) then you could have your program read the configurations at runtime, after they have been defined by a manager type person. This would decouple the business needs from your code, and that would be a robust way to future-proof.
Oh... and I would recommend NOT using Hungarian notation. If you change the type of an object or parameter you also have to change the name. Worse you could forget to change them and other will make incorrect assumptions. Unless you are using vim/notepad to program with then the IDE will give you that info in a clearer manner.
#user1158692 - The party instantiating Chips only needs to know about SerialNumber in one of my proposed designs, and that proposed design stipulates that the SerialNumber class acts to configure the Chips class. In that case the person using Chips SHOULD know about SerialNumber because of their intimate relationship. The intimiate relationship between the classes is exactly the reason why it should be injected via constructor. Of course it is very very simple to change this to use a setter instead if necessary, but this is something I would discourage, due to the represented relationship.
I really doubt that it is absolutely necessary to create the instances of chips without knowing the serial number. I would imagine that this is an application issue rather than one that is required by the design of the class. Also, the class is not very usable without SerialNumber and if you did allow construction of the class without SerialNumber you would either need to use a default version (requiring Chips to know how to construct one of these or using a global reference!) or you would end up polluting the class with a lot of checking.
As for you complaint regarding the shared_ptr... how on earth to you propose that the ownership semantics and responsibilities are clarified? Perhaps raw pointers would be your solution but that is dangerous and unclear. The shared_ptr clearly lets designers know that they do not own the pointer and are not responsible for it.