How to prevent multiple classes for the same business object? - oop

A lot of the time I will have a Business object that has a property for a user index or a set of indexes for some data. When I display this object in a form or some other view I need the users full name or some of the other properties of the data. Usually I create another class myObjectView or something similar. What is the best way to handle this case?
To further clarify:
If I had a class an issue tracker and my class for an issue has IxCreatedByUser as a property and a collection of IxAttachment values (indexes for attachment records). When I display this on a web page I want to show John Doe instead of the IxCreatedByUser and I want to show a link to the Attachment and the file name on the page. So usually I create a new class with a Collection of Attachment objects and a CreatedByUserFullName property or something of that nature. It just feels wrong creating this second class to display data on a page. Perhaps I am wrong?

The façade pattern.
I think your approach, creating a façade pattern to abstract the complexities with multiple datasources is often appropriate, and will make your code easy to understand.
Care should be taken to create too many layers of abstractions, because the level of indirection will ruin the initial attempt at making the code easier to read. Especially, if you feel you just write classes to match what you've done in other places. For intance if you have a myLoanView, doesn't necessarily you need to create a myView for every single dialogue in the system. Take 10-steps back from the code, and maybe make a façade which is a reusable and intuitive abstraction, you can use in several places.
Feel free to elaborate on the exact nature of your challenge.

One key principle is that each of your classes should have a defined purpose. If the purpose of your "Business object" class is to expose relevant data related to the business object, it may be entirely reasonable to create a property on the class that delegates the request for the lookup description to the related class that is responsible for that information. Any formatting that is specific to your class would be done in the property.

Here's some guidelines to help you with deciding how to handle this (pretty common, IMO) pattern:
If you all you need is a quickie link to a lookup table that does not change often (e.g. a table of addresses that links to a table of states and/or countries), you can keep a lazy-loaded, static copy of the lookup table.
If you have a really big class that would take a lot of joins or subqueries to load just for display purposes, you probably want to make a "view" or "info" class for display purposes like you've described above. Just make sure the XInfo class (for displaying) loads significantly faster than the X class (for editing). This is a situation where using a view on the database side may be a very good idea.

Related

Class with a list of materials: best practice

I've created the custom class ZMaterial that can be instantiated passing an ID to the constructor which sets the properties for a single material using SELECTs and BAPIs. This class is basically used to READ and UPDATE a single material.
Now I need to create a service to return a list of materials. I already have the procedural code for it in a static method (for now actually a function module), but I would like to keep using a full OOP approach and instantiate a list of my custom material object. The first approach I found is to enhance the static method to instantiate a list of my single material object after the selects are executed and I have the data in internal tables, but it does not seem the most OOP.
The second option in my mind is to create a new class ZMaterialList with one property being a list of objects ZMaterial and then a constructor with the necessary input parameters for the database select. The problem I see with this option is that I create a full class just for the constructor.
What do you think is the best way to proceed?
Create a separate class to produce the list of materials. The single responsibility principle says each class should do exactly one thing. In all but the most simple cases, using a thing is a different responsibility than producing it.
Don’t make a ZMaterialList class. A list’s focus would be managing the list items, i.e. adding, removing, iterating, sorting etc. But you should be fine with a regular STANDARD TABLE OF REF TO ZMaterial.
Make a ZMaterialReader, -Repository, -Query or -Factory class or the like, depending on the precise way you want to produce the ZMaterials. Readers read by keys, repositories read and write, queries use varying sets of selection criteria, factories instantiate with possibly different sets of inputs.
You can well let that class use the original FUNCTION underneath. It’s good style to exploit what’s already there. Just make sure you trust that code, put it in a test harness, and keep it afar from the rest of your oo code.
Extract all public interaction of ZMaterial to an interface and use only that interface. That allows you to offer alternative implementations of ZMaterial, ones that differ in the way they are produced or how they store their data.
Split single production from mass production. Reading MARA to retrieve a single material is okay. But you don’t want thousands of ZMaterials reading MARA individually - that wrecks performance.
Now you’ve got the interface, you could offer a second implementation of ZMaterial whose constructor receives all relevant data and relies on it already having been validated to avoid additional SELECTs.
You could also offer an implementation that doesn’t store its data at all but only stores pointers to rows in internal tables somewhere else. See the flyweight pattern for ideas.
If you expect mass updates on the materials, such as “reclassify all of these as B”, consider extracting these list-oriented operations to separate classes as well.

"Visitor" a lot of different type of object

in one application I have a lot of dirrerent object, let´s say : square, circle, etc ... a lot of different shape ---> I´m sorry for the trivial example.
With all this object I want to create a doc of different type : xml, txt, html, etc.. (e.g.: I want to scan all the object (shapes) tree and produce the xml file.
The natural approach I thought is visitor pattern, I tried and it works :-)
- all the objects have one visit method accepting the IVisitor interface.
- I have one concrete visitor for every kind of do I want to create : (XmlVisitor, TxtVisitor, etc). Every visitor has one method "visit" for every kind of object.
My doubt is ... it doesn´t seems scaling well if I have a lot of object ...
from the logic point of view it´s ok, i have just to add the new shape and the method in the concrete Visitor, that´s all.
What do you think ? is an althernative possible ?
I think that you have correctly implemented a visitor pattern and as a result you also have implemented a double dispatching mechanism. If you consider the "not scaling well" as a need to add a bunch of methods in case of adding a new shape and/or visitor, then it is just a side effect of the pattern. Some people consider this "method explosion" as harmful and opt for a different implementation, such as having a "decision matrix" object. For this example in particular I think that the DD approach is the way to go and that actually it does scale well, since you add new methods as you add new requirements (i.e. you add new visit* methods as new shapes are added or you add a new visitor class as new document types are needed).
HTH
It seems to me that what worries you the most is that you are matching against many different kinds of objects, and worry that as more and more object types are added, the performance will suffer. I don't think you need to worry about that, though: The performance of the visitor pattern is not really affected by the potential number of objects or visitors, since it is based on virtual table lookup - the passed object will contain a link to (a link to) the method which should be called.
So the visitor pattern, though relatively expensive in indirect accesses, is scalable in this regard.
I believe you have :
A class hierarchy (Shapes in your example) and
Operations on the class hierarchy (exportXML, exportToHTML etc in your example)
You have to consider what is more likely to change -
You should choose Visitor pattern if the class hierarchy is more or less fixed but you would like to add more operations in future. Visitor pattern will allow you to add more operations (e.g. JSON export) without touching the existing class hierarchy.
OTOH if the operations are more or less fixed, but more Shape objects can be added, then you should use regular inheritance. Define a ShapeExport interface which has methods like exportToXML, exportToHTML etc. Let all Shapes implement that interface. Now you can add new Shape which implements the same interface without touching existing code.

In OOP programming style, why should we hide object's data member from being directly accessed by others

I just don't know why this is the RULE. and what benifit of this rule?
Could you give me a example that we better follow this rule.
It is also called data hiding which helps to maintain the integrity of the object. It saves the data from misuse and outside interference. The data cannot be accessed directly but access controls can be specified in order to obtain the information. The data or object can be made public or private depending on the needs. The data which is private is not accessible outside the scope of the object. When the data is public it can be accessed by the other parts of the program.
"Preventing users of your class misusing it" is often touted as the reason that encapsulation is so important.
I think that has an implication that you are writing classes for other un-trusted developers to use, which I think is rarely the case. The un-trusted clients argument confuses the issue.
Most of the time the users of your class are "you" and members of your team.
The public methods and properties of your class make up the interface point between your class and the rest of your code. The smaller that interface is the easier it is to use and understand.
The reason you encapsulate is to make the interface for your class as small and succinct as possible.
If your classes are highly cohesive and have small interfaces you can easily "forget" about how they work and focus on another part of your program.
Take the example of a class that makes web requests. It may expose a single public method DownloadFile(url). This class could be extremely complicated but it's simple interface means you can forget about the internals of how it works leaving you more room in your head to focus on the problem you are trying to solve.
The counter example would be a web request class that exposed all it's methods publicly. It make have 20 methods, DownloadBegin, DownloadEnd, ChooseProtocol, etc etc. All of those may be used internally but were never intended to be called externally. In order to use the class you then have to know how it works internally before you can know which methods to call.
One of the virtues of data hiding that gets touted a lot is that it helps to protect your class from misuse. You can't trust the users of your class to do the right thing with it, so you make it impossible to do the wrong thing with it. Most of the time giving a user of your class direct access to any of its members opens up the possibility for that member to be set to some invalid or nonsensical value, or set at the wrong time.
One of the more practical reasons is, you can't change the implementation of a data member. If you have, say, a size member that you make publicly accessible, then later you need to have the class actually do something in response to a change of size, you're stuck. If you have accessor methods, then these methods can be as magical as they need to be.
It's also related to the separation of concerns. If you have public interface and the data is not public, you can change the way the data is represented any time, changing only the class that holds the data. If the data is not hidden and you change it, you have to change all of the code that uses the data.

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Design pattern advice: Using an array of custom objects as a singleton

After a lot of studying, I am starting to code my first app.
In my code I have a class called "Measurement". I want to implement an array of Measurements. This array of Measurements needs to be accessible across multiple view controllers, so I have created a custom class called "MeasurementsArray" for the array, and made it into a singleton.
I have done this, and the code works as expected. But now that I have it working, I want to make sure that I have easy to understand code, and that I am following conventional objective-c design patterns.
If it weren't for fact that I need the array of Measurements to be a singleton, it would seem that this array belongs inside the "Measurement" class as a class method. But my understanding is that there can be only one instance of a class when it is a singleton.
But somehow, having a separate class named "MeasurmentsArray" seems a little hacky to me.
My question:
Am I approaching this the right way, or am I missing something?
If I do need the split off the array of Measurements to a separate class in order to have it be a singleton, does "MeasurementsArray" seem like an appropriate class name? If not, please provide a naming convention you would use for this type of situation.
Edit: After some inital answers, some clarification regarding the function of the app might help.
It is a fitness application that records, saves and tracks body fat percentage and body weight. Every time the user records his body fat and weight, it becomes an instance of the class "Measurement". The array of Measurements is needed in order to track changes in weight and body fat over time. A singleton is needed because multiple view controllers need access to the array.
A singleton is needed because multiple
view controllers need access to the
array.
There are other, better ways to share data between objects than to rely on a singleton.
View controllers are usually created either by the application delegate or by another view controller. The application's data model (in this case, that's your measurements array) is often also created ether by the application delegate. So when the app delegate creates a view controller, it can also give that controller a pointer to the data model. If that controller creates any view controllers, it can likewise share its pointer to the data model.
Passing the data model along from app delegate to view controller and from one view controller to the next makes your code easier to maintain, test, reconfigure, and reuse because it avoids depending on some predetermined, globally accessibly object.
Having a singleton at all may be a wrong move. There are times that a singleton is appropriate, but there's usually a better choice.
It sounds like you may already be implementing something resembling the Model-View-Controller pattern, which would be appropriate. In this context, this array of measurements is part of your model, and it may make sense for it to be a separate class, but there's likely no need for it to be a singleton.
The name MeasurementsArray is implementation-specific. I would be more inclined to call it just Measurements or to give it a name reflecting what the measurements are measuring.
In fact I wonder about the name of your Measurement class. What is it measuring? What does it actually represent?
If you post some code, we might be able to provide more specific ideas.
Based on your update and a bit of thinking, you might want to think about The Repository Pattern. Rather than having your controllers hold the array, they have access to the repository from which they can get it.
My thinking here is that your array of measurements might be supplied by a MeasurementRepository and that while now the data might be a single simple array that the repository just holds, it might evolve to something that is stored in a database per user and with variation over time, so that your repository supplies more complex access.
Rather than having this repository be a singleton (though that is certainly sometimes done), it might better be just created once and then injected into everything that needs it. See http://en.wikipedia.org/wiki/Dependency_injection and Uncle Bob's blog
I feel that a separate class is probably overkill unless it has several methods of its own, in which case it might be justified. This problem may just be an artefact of your app's structure not (yet) being well defined. Is data going to be persistent across sessions? If so, will there be a "manager" class on which you could put a property to retrieve the array; something like allMeasurements on the MeasurementStore class? Another option would be to store the array in your app delegate.
I find that if I continue working on an app, it becomes obvious how I should structure it.
Edit: To elaborate, there's nothing "wrong" with your approach; there's probably just nicer ways to do it.
If I understand you correctly, the measurements array represents past measurements of a specific user.
If that is the case- you're not looking for a singleton at all.
remember that a singleton is a single value PER APPLICATION, and what you're looking for here is a single value PER USER.
Don Roby is absolutely right- Measurements is probably a property of the User class. for example (I'm using c# notation, but you get the hang of it...):
public class User
{
public string Name {get; set;}
public int Id {get; set;}
public Measurement[] Measurements {get; set;} //one array per-user...
}