Passing an interface address through an outer layer and into nested inner layers - oop

I am attempting to create my own OOP event logger. I know TwinCAT had their own, however there is some functionality that I need that TwinCAT's event logger does not have. If I have an interface of I_Logger being inserted into an outer FB, I am needing to pass the address down into my nested FBs so that all my FBs have access to it. The only kicker is that I need the outer class to be dynamic. Since my inner classes are made up of devices and components, and then my outer layer can be a station or a zone, I am working on my framework to cater to this. Devices are the lowest level. Components are grouping of devices, assemblies are groupings of components and devices, stations are groupings of any of the previous, so on and so forth.
I have attempted to use a decorator pattern and chaining methods to try and retrieve the address of the logger but that has not worked. Any help would be appreciated.

Related

Deep class composition and the Law of Demeter

Evening. I'm having trouble finding an appropriate design pattern for some situations of deep composition. Let me present an example.
Let's say we have a class of type Corporation that has many classes of type Subsidiary that have many classes of type Department that in type contain many classes of type Unit that in turn contain many classes of type Employee.
Now, suppose the use case is to count the number of employees for each corporation. I could loop through each corpration, loop again for each subsidiary, and so on and so forth, in something that would result in a nested loop, 4 levels deep. Plus, I would be breaking the Law of Demeter by referencing my class chain several levels below, something that is so tightly couped it would break the very moment I modified my chain.
Another thing I could do is add tons (ok maybe not tons, but a few) of shortcut references. For example, a corporation could itself ALSO contain a list of Employees resulting in never having to walk through the chain to count them. This way, classes are less tightly coupled (but are they?) and the issue now becomes how to keep the Employee list synced for both the Corporation and the Unit. I could use the Observer pattern to keep them updated I suppose but I really feel something's horribly wrong with this idea or, at the very least, I'm not really using the best solution out there.
As I'm pretty sure this is an extremely common domain, could anyone be kind enough as to point me to an appropriate design pattern?
Thanks.
I don't exactly get the second question but I am answering the first question.
As the Law of Demeter states that each entity should have least
knowledge about other units
So using that principle in your design
class Corporation{
//All the stuff about corporation
//Don't ask for what's inside corporation
public int countEmployees(){
//will apply the logic needed to calculate
}
}
Better Client code with Law of Demeter:
corporationInstance.countEmployees(); //let the corporation handle how to count and not expose inner details
Without Law of Demeter
corporationInstace.getSubsidiaries().getSomethingElse()..... //exposing the inner details of class which creates a chain that is bad.
UPDATE:
Using the above stated solution you can go in as many depths as you want by creating the countEmployees() method inside Subsidiaries and in Unit as required. There is no point in breaking the encapsulation or using Observer pattern here.
Apply the Tell Don't ask principle as you have pointed in the comment yourself and delegate the responsibility of calculating the actual employees on the class that contains employees.
Department - > uses count method on subsidiaries to add their count
Subsidiaries - > uses Units to count
Unit - > Uses employees to count
Say you want to email the customer from a link or button. You might write it like customer.getSomeParticularContactInfo(addressType).sendEmail() or customer.sendEmail() which then (inside Customer) calls getSomeParticularContactInfo("primary").sendEmail().
You are on the wrong way. This breaks Single Responsibility, I mean, Customer Object doesn't need to know, how can send E-mail, Customer object is responsible only for how to provide the e-mail address belongs to the customer. So for this functionality, you need to create another Interface like Notifier and an EmailNotifier what implements Notifier. Thereafter you will call EmailNotifier.notify(customer)

How to model OO scenario

I recurrently run into an scenario similar to this:
A container business class that models a hierarchy.
A business class that participates in this hierarchy and is aggregated by the aforementioned class.
Let me give you an example.
A Map has Countries. Now the Map should know where each Country is, since its main responsability besides containing all countries is to know the locations and proximity of each. From this point of view, a functionality such as isNeighbour(Country A, Country B) seems like a correct addition to Map. However, each Country should also offer a method to know if a country is nearby. Say spain.isNeighbour(italy). This is indeed useful. Now, if I don't want to duplicate functionality and responsability, what approach should I take?
The current example I am working on is something for my university, each course requires other courses and also blocks the next level ones. The major is the one that contains all courses and dictates which course precedes which. Say I want to add a dependency of a course over another, e.g to take Calculus 2 you need Calculus 1... Should I go calculus.addRequired(calculus2) and then pass it to the major object, or maybe computerScience.addRequired(calculus1, calculus2)...
I don't want to have both alternatives because to me it seems it can lead to error, but at the same time I want each course to be able to answer what are its requirements. I don't really know how to distribute responsabilities correctly.
First thing is, that there is no problem calling each other.
You can have
boolean Map.isNeighbour(Country A, Country B) { return A.isNeighbour(B); }
or
boolean Country.isNeighbour(Country other) { return map.isNeighbour(this, other); }
Second seems to need reference to global map. First makes Map look like simple facade.
Second thing is that you say it is persisted. There also might be good idea to create a service, that will query DB with related parameters. This can be either Map or some repository service. This will also allow you to query with only identities of entities (eg. countryId) instead of full objects.
I believe neither of the solutions is better or worse. Only point of difference is where other developers expect the methods to be located. But when I think about it, this would mean Map will have all responsibilities of Country, thus breaking SRP, especially if it is not call-through to the country method.
I would put the isNeighbour() method into Country.
Country would contain a map of neighbours. And then the container can call this method on the country instance in question.
This way the logic is maintained by the countries, and the container simply delegates to answer the question to them.
In case of courses it is possible that Course-1 is required for Course-2 in Major-1, but not in Major-2. In this case I would introduce another class, e.g. CourseInMajor that would contain the required courses for a given course in a given Major.

Communication in component-based game engine

For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.
Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.
I can think of several ways to solve this problem:
Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.
Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.
Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).
This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).
The short version
In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?
We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.
However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.
Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.
As for communication:
Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.
Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)
Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?
Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.
Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.
For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:
Store it in the collision component itself.
Make the collision detection code work with the components directly.
So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.
This gives you a couple of benefits:
Leaves collision-specific state out of GameObject.
Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.
If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.
Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).
Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.
[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).
One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.
In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.
During initialization the container will wire up connections between components, and during run-time there will be no additional cost.
This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.
The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.

NHibernate + Paging + Ordering

I'm not quite sure of the most elegant solution for what I am trying to do.
I have a page which lists music listings, there can be thousands of these so they are paged in batches of 20, I also have 4 links at the top of the page to change the way these listings are ordered.
The sort by properties could be located on different entities such as Audio.AudioStats.NumComments or Audio.Artist.NumProfileViews.
I am using the repository pattern, and a service layer. My controllers can only access the service layer, then the service layer accesses my repositories.
I can do the paging fairly easily, i simply pass in my current page, and the page size to my data layer...but how would i safely let the user decide on the ordering of my entities.
I am using S#arp Architecture 1.5.2 if that makes any difference.
Thank you in advance.
You are going to have to map the users' desires to an order by clause somehow.
Presumably you're doing something like skip(n).take(m) which will need an orderby() clause too.
Given that you have a fixed set of (known) possibilities, you can map those to an enum or similar which you then translate to the relevant orderby() call.
This means you don't expose the properties at the UI layer but only pass through the intent to the repository layer (as a Sortby.ArtistProfileViews value or whatever). What how that intent is mapped to the properties on you domain objects is isolated in your repository layer.

Basic question about OOP

I often have the same trouble when I have to design my class for a web application. The requirements are :
- maintainable (no copy-paste for instance)
- layers fully separated (the business layer doesn't have to know which method of the data layer is used)
- high performance : don't load useless data.
First I have a table with all my customers and their addresses :
Code :
Customer
--Id
--Name
--Address
----City
----ZC
----Street
Now I want a table (in another page) with all my customers and the books that they bought, I have a few possibilities :
1/ I create a new class :
Code :
CustomerWithBooks
--Id
--Name
--Books[]
----ID
----name
PRO : I load only the useful data
CONS : I build my class after my UI , and there is copy-paste.
2/ I add Books[] to the first class.
PRO : Everything is in the same class, it's maintainable
CONS : I load the address for nothing. If I don't load the address I can : lazy loading, but I really don't like it, or when I use my class I have to know which method of my DAL i called, and I don't like it.
3/ I use inheritance :
Code :
ClientBase
--ID
--Name
ClientWithBooks : ClientBase
--Books[]
ClientWithAdress : ClientBase
--Address
PRO: really maintenable, and I don't load data for nothing
CONS : What do I do if in one UI I want to show the Books AND the Address ?
4/ ?? I hope there is a perfect solution
You option 1 is close to good, assuming I understand it correctly. A customer and a book are two completely different things. You want that data/functionality separate, and should not inherit from any common base class (that you have made).
As the "Con" you say: I build my class after my UI , and there is copy-paste.
A. If you mock up some UI to help clarify requirements before you settle on your design and code up classes, that's good, not bad.
B. Good arrangement of your domain objects helps eliminate copy/paste, not cause it. If you have some seemingly repetitive code within your well-arranged classes (often data access code) that's typical, don't worry. You can address with with a good data-access layer/tool, good shared logging resources, etc. Repetitive code within your classes just means you have more design improvement to do, not that having separate classes for all your domain realities is bad.
On the page where you need to deal with both customers and books, you will use customer objects and book objects, and probably a books collection object. And depending on how your db/object-model are set up, you might be dealing with other objects to get form customer to the books they bought. For example, the customers probably buy 1 or more books at the same time, and these are tied to an Order object, which has a reference to a customer. So, you'll probably go from a
Customer to an
Orders collection containing all of that customers orders to the individual
Order objects and from there to a corresponding
Books collection containing all the
Book objects that relate to that Order object.
None of these need to inherit from each other. Now, let's say getting all the books bought by a customer is something you do a lot, and you want to streamline that. You then want to have a Books collection directly off of Customer that gives you that, though the sql queries you use to get those books still goes through Orders in the db. You must start with your object model (and tables behind the scenes) reflecting reality accurately. Even if this give you seemingly many classes, it is more simple in the end. You might end up with some inheritance, you might not.
I would to avoid 2 and 3, because it locks you into a restrictive hierarchy that doesn't really meet your needs. As you point out, there could be any combination of things that you want, such as customers and their books, and maybe their address, and maybe their ordering history. Or maybe you'll want a book with it's list of customers. Since your underlying business information is not really hierarchical, you should try to avoid making your object model unnecessarily hierarchical. Otherwise, you will build in restrictions that will cause you a lot of headaches later, because you can't think of all the scenerios now.
I think you're on the right track with 1. I would say to create some basic classes for Customers and Books, and then create a CustomerBook association class that contains an instance both the customer and the book. Then you can have you methods worry about how to load the data into that list for a given scenerio.
I would stick the address into Customer, and have a separate collection of books.
Bookshelf
--Books[]
This way, a Customer doesn't have, but can have, one or more books associated to him. PHP-code example following:
class BookshelfFactory {
public static function getBookshelf(Customer $customer) {
// perform some fetching here
return $bookshelf;
}
}
You're sort of designing backwards from an OOA&D standpoint. It's normal to use data-driven design at the persistence (usually a relational database) layer. But in OOA&D it's more normal to think of the messages an object will send and receive (you model an object's methods not its members). I would think about it this way:
Customer
+getBooks():List<Book>
+getAddress():Address
I think your problem is an issue for the implementation of your data mapping layer.
You can have highly performant queries with JOINS that return you the Customers as well as their Books.
Your mapping layer maps this into the appropriate unique objects and is responsible for creating the right 1-many aggregation for your objects.
In addition you could cater for shallow loading, for display properties to save unnecessary amounts of data to be transferred where you only need a few attributes per object.