Which is a better design? - oop

I have a team leader object, and have lot of team members object own by team leader.
Both team leader and team members have a function called "writeDB".
So, design 1:
Have a common writeDB function in DBUtility:
teamLeader.writeDB(); //calling DBUtility like this DBUtility.insert(self);
teamMember.writeDB(); //calling DBUtility like this DBUtility.insert(self);
design 2:
Both implementing a writeDB Interface:
teamLeader.writeDB(); //implement the write DB itself;
teamMember.writeDB(); //implement the write DB itself;
design 1 can centralize the writingDB logic into one single class, if there is any problems in writing DB, I only need to change the DBUtility class, also, if I would like change the DB, I only need to change one place.
design 2 can separate the code into two places. If one developer coding about teamLeader logic, he don't need to update the DBUtility, also, if the code move to somewhere else, he don't need to copy the useless function, for example, the DBUtility's teamMember writeDB function is not needed.
What do you think for better maintain? or the design 3 from you. Thank you.

Putting aside my concern that any model level class would have an explicit public method called writeDB, I would go for option 1
Persistence should be considered orthogonal to the core responsibilities of these classes.
The benefit comes in several parts
Cleanly separating the responsibilities will result in a more
object-oriented design. More object-oriented means more comprehensible and easier to manage over time.
In larger teams, you may well have a sub-group working explicitly on the persistence layer and they can have total responsibility for managing and optimising the code.
When you inevitably release that database X is better than database Y (or indeed that SQL is a bad idea), the persistence logic is not scattered across the code base
That pesky writeDB() method
Just to go back to my first point, you shouldn't have a public method called writeDB. You also probably don't want a more generic name such as save. The better design would allow the classes themselves to decide when they need to be persisted

Why do TeamMember and TeamLeader have to know about the database at all? I think this would be better:
DBUtility.write( teamMember );
DBUtility.write( teamLeader );
Better still is if DBUtility is not static, allowing you to see what it really depends on. Static is the same as global. Global puts an assumption in place about only ever doing it one way, and this generally causes problems later.
DBUtility dbUtility = new DBUtility( dbConnection );
dbUtility.write( teamMember );
dbUtility.write( teamLeader );
Then later, you might need to write to disk as XML. You should be able to add this feature without changing your TeamLeader and TeamMember.
XMLUtility xmlUtility = new XMLUtility( stream );
xmlUtility.write( teamMember );
xmlUtility.write( teamLeader );

I prefer to use the second design because it is more object oriented and you will benefit from separating the code.

I should go with design 2 which will force all my classes to have writeDB method, and I will use design1 to provide this functionality.
This way I will have interface for my objects Leader/Member and will have the actions grouped under on class which knows how to do the actions.

It depends. From a Separation-Of-Concerns principle this shouldn't be in the class itself, but having a class which knows about all others violates the Open-Close-Principle.
There is a third option for this kind of operation (e.g. write to DB), that is to use some metadata in the class and then some code which does write the object to the database by using the metadata information.

The second option is definatly mor OO. Eache type implements the writeDB interface.
If it makes sence when writing teamLeader to also write each teamMember then writeDB implomentation for teamLeader can call writeDB on each teamMember.
That would be the most OO solution.
Howerver, this dosen't take into account persistense layer limitations and efficencies.

Related

Why are helperclasses anti pattern

A recent question here made me rethink this whole helper classes are anti pattern thing.
asawyer pointed out a few links in the comments to that question:
Helper classes is an anti-pattern.
While those links go into detail how helperclasses collide with the well known principles of oop some things are still unclear to me.
For example "Do not repeat yourself". How can you acchieve this without creating some sort of helper?
I thought you could derive a certain type and provide some features for it.
But I bellieve that isnt practical all the time.
Lets take a look at the following example,
please keep in mind I tried not to use any higher language features nor "languagespecific" stuff. So this might been ugly nested and not optimal...
//Check if the string is full of whitepsaces
bool allWhiteSpace = true;
if(input == null || input.Length == 0)
allWhiteSpace = false;
else
{
foreach(char c in input)
{
if( c != ' ')
{
allWhiteSpace = false;
break;
}
}
}
Lets create a bad helper class called StringHelper, the code becomes shorter:
bool isAllWhiteSpace = StringHelper.IsAllWhiteSpace(input);
So since this isnt the only time we need to check this, i guess "Do not repeat yourself" is fullfilled here.
How do we acchieve this without a helper ? Considering that this piece of Code isn't bound to a single class?
Do we need to inherit string and call it BetterString ?
bool allWhiteSpace = better.IsAllWhiteSpace;
or do we create a class? StringChecker
StringChecker checker = new StringChecker();
bool allWhiteSpace = checker.IsAllwhiteSpace(input);
So how do we acchieve this?
Some languages (e.g. C#) allow the use of ExtensionMethods. Do they count as helperclasses aswell? I tend to prefer those over helperclasses.
Helper classes may be bad (there are always exceptions) because a well-designed OO system will have clearly understood responsibilities for each class. For example, a List is responsible for managing an ordered list of items. Some people new to OOD who discover that a class has methods to do stuff with its data sometimes ask "why doesn't List have a dispayOnGUI method (or similar such thing)?". The answer is that it is not the responsibility of List to be concerned with the GUI.
If you call a class a "Helper" it really doesn't say anything about what that class is supposed to do.
A typical scenario is that there will be some class and someone decides it is getting too big and carves it up into two smaller classes, one of which is a helper. It often isn't really clear what methods should go in the helper and what methods should stay in the original class: the responsibility of the helper is not defined.
It is hard to explain unless you are experienced with OOD, but let me show by an analogy. By the way, I find this analogy extremely powerful:
Imagine you have a large team in which there are members with different job designations: e.g, front-end developers, back-end developers, testers, analysts, project managers, support engineers, integration specialists, etc. (as you like).
Each role you can think of as a class: it has certain responsibilities and the people fulfilling those responsibilities hopefully have the necessary knowledge to execute them. These roles will interact in a similar way to classes interacting.
Now imagine it is discovered that the back-end developers find their job too complicated. You can hire more if it is simply a throughput problem, but perhaps the problem is that the task requires too much knowledge across too many domains. It is decided to split up the back-end developer role by creating a new role, and maybe hire new people to fill it.
How helpful would it be if that new job description was "Back-end developer helper"? Not very ... the applicants are likely to be given a haphazard set of tasks, they may get confused about what they are supposed to do, their co-workers may not understand what they are supposed to do.
More seriously, the knowledge of the helpers may have to be exactly the same as the original developers as we haven't really narrowed down the actual responsibilities.
So "Helper" isn't really saying anything in terms of defining what the responsibilities of the new role are. Instead, it would be better to split-off, for example, the database part of the role, so "Back-end developer" is split into "Back-end developer" and "Database layer developer".
Calling a class a helper has the same problem and the solution is the same solution. You should think more about what the responsibilities of the new class should be. Ideally, it should not just shave-off some methods, but should also take some data with it that it is responsible for managing and thereby create a solution that is genuinely simpler to understand piece by piece than the original large class, rather than simply placing the same complicated logic in two different places.
I have found in some cases that a helper class is well designed, but all it lacks is a good name. In this case, calling it "Builder" or "Formatter" or "Context" instead of "Helper" immediately makes the solution far easier to understand.
Disclaimer: the following answer is based on my own experience and I'm not making a point of right and wrong.
IMHO, Helper classes are neither good nor bad, it all depends on your business/domain logic and your software architecture.
Here's Why:
lets say that we need to implement the idea of white spaces you proposed, so first I will ask my self.
When would I need to check against white spaces?
Hence, imagine the following scenario: a blogging system with Users, Posts, Comments. Thus, I would have three Classes:
Class User{}
Class Post{}
Class Comment{}
each class would have some field that is a string type. Anyway, I would need to validate these fields so I would create something like:
Class UserValidator{}
Class PostValidator{}
Class CommentValidator{}
and I would place my validation policies in those three classes. But WAIT! all of the aforementioned classes needs a check against null or all whitespaces? Ummmm....
the best solution is to take it higher in the tree and put it in some Father class called Validator:
Class Validator{
//some code
bool function is_all_whitespaces(){}
}
so, if you need the function is_all_whitespaces(){} to be abstract ( with class validator being abstract too) or turn it into an interface that would be another issue and it depends on your way of thinking mostly.
back to the point in this case I would have my classes ( for the sake of giving an example ) look like:
Class UserValidator inherits Validator{}
Class PostValidator inherits Validator{}
Class CommentValidator inherits Validator{}
in this case I really don't need the helper at all. but lets say that you have a function called multiD_array_group_by_key
and you are using it in different positions, but you don't like to have it in some OOP structured place you can have in some ArrayHelper but by that you are a step behind from being fully object oriented.

OOP: How do I deal with objects that have mutual relations?

Let's say there are two classes related to each other via some relations. For example, a Student maintains a list of the Classes he takes, and each Class has a list of Students taking it. Then I am afraid of letting the Student directly being able to modify its set of Classes, because each modification would have to be followed by a similar modification of a Class's list of Students, and vice versa.
One solution is to have a class whose sole purpose is to keep track of Class-Student relations, say Registrar. But then if some method in Student requires knowledge of its Class list, the Student needs to be passed the Registrar. This seems bad. It seems Student shouldn't have access to the Registrar, where it can also access other Students. I can think of a solution, creating a class that acts as a mediator between Student and Registrar, showing the Student only what it needs to know, but this seems possibly like overkill. Another solution is to remove from Student any method that needs to access its classes and put it instead in Registrar or some other class that has access to Registrar.
The reason I'm asking is that I'm working on a chess game in Java. I'm thinking about the Piece-Cell relations and the Piece-Player relations. If in the above example it wasn't OK for a Student to have access to the Registrar, is it OK here for a Piece to have access to the Board, since a Piece needs to look around anyway to decide if a move is valid?
What's the standard practice in such cases?
If relations can be changed - classes should be decoupled as much as possible, so along with each class create an interface, do not introduce tied relations between classes.
High level of separation you can achieve using intermediate services/helpers which encapsulates logic of communication between classes, so in this case you should not inject one class to an other even both are abstracted by interfaces, basically Student does not know anything about Class, and Class does not know anything about Student. I'm not sure whether such complexity is makes sense in your case but anyway you can achieve it.
Here is you may find a useful design pattern Mediator which can encapsulate interaction logic between two decoupled entities, take a look at it.
With the mediator pattern, communication between objects is
encapsulated with a mediator object. Objects no longer communicate
directly with each other, but instead communicate through the
mediator. This reduces the dependencies between communicating objects,
thereby lowering the coupling.
What I think you have found in your pretty nice example and explanation is that OO does not solve all problems well. As long as the responsibility is well shaped and sharp, everything is fine. And as long each responsibility fits in exactly one bucket (the class), it is pretty easy to design. But here you have a tradeoff:
If I define for each responsibility a separate class, I will get a bloated design that is pretty difficult to understand (and sometimes to maintain).
If I include for each separate responsibility at least one interface, I will get more classes and interfaces than I need.
If I decide that one of the two classes is responsible for the relation as well, this one object has more knowledge than usual about the other.
And if you introduce in each case a mediator or something similar, your design will be more complex than the problem.
So perhaps you should ask the questions:
What is the likelihood that the relation between the 2 objects will change?
What is the likelihood that the relation will exist between more 1 type of objects at each end?
Is that part of the system a highly visible part, so that a lot of other parts will interface it (and therefore will be dependent on it)?
Take the simplest solution that could possibly work and start with that. As long as the solution is kept simple, it is only your code (you don't design a library for others), there are chances that you can change the design later without hassle.
So in your concrete case,
the board field should have access to the whole board XOR
the figure on the field should have the responsibility of moving XOR
there should be an object type (ChessGame?) that is responsible for the overall knowledge about moving, blocking, attacking ...
I do think that all are valid, and it depends on your special "business case" which one is the most valid.

Should an Entity ever know anything about its DAO?

I have a chance to introduce NHibernate to my group by using it with some new components that are being added to a legacy application. I'm trying to get my head around using the DAO pattern with NHibernate, and am stumped with an architectural question.
In my fictional example, let's say I have CarDAO and a Car entity:
public interface CarDAO {
Car FindById(int id)
... // everything else
}
public interface Car {
... various properties and methods
}
I have a need to be able to convert a car to right-hand drive. Since this would be a very complex operation, I need to execute a stored procedure. I'm not clear on where the ConvertToRightHandDrive() method should go.
It makes sense to me to put the method on Car, and let it call a method on the CarDAO that will execute the stored procedure. And this is where I'm not clear:
should Car have a reference to the CarDAO and call CarDAO.ConvertToRightHandDrive?
should there be some sort of CarService layer that calls CarDAO.ConvertToRightHandDrive?
what about injecting the CarDAO through the method on Car (Car.ConvertToRightHandDrive(carDAO))
some other option?
Perhaps this is only a religious argument, and people have differing opinions on whether or not an Entity should have a reference to its DAO (or any other DAO, for that matter). I've been searching StackOverflow for some time, and have seen several discussions around this topic; but, I'd be interested in people's opinions in this particular scenario.
The way I was always told to think about it is that Entities should have as little in them as possible and that various objects should perform operations against entities. The entities themselves should not be aware of the DAL or they lose their data storage ignorance
So in this case, a CarManager (or similar) which possibly has a dependency on the CarDAO should have a ChangeToRightHandDrive(Car) method.
Oh and one other advantage to having a CarManager which performs the complex operations is that you're not relying on stored procs - This is almost certainly a religious issue but I prefer to have all the logic in my code rather than relying on SPs (There are a few exceptions but usually only around large sets). This means that if you changed to another DAL (say XML), you wouldn't need to re-implement your SP in your DAL/DAO - Otherwise, you'd end up with business logic embedded in your DAL.
My opinion is that Car should have no knowledge of CarDAO. This keeps your domain model clean and allows you to change your back-end without affecting the Car class.
If you need to call a stored procedure to convert a car to right-hand drive, I like the option of having a CarDAO.ConvertToRightHandDrive(Car car) method and then using something like a CarService class to hide the dependency on CarDAO from any callers (i.e. the CarService class would have an identical method that would just forward the call to CarDAO).
As you mention, people will definitely disagree on this type of thing, but it's always worth carefully considering dependencies and coupling before you start hacking away.

In which class would you put these methods?

If I have a User class, and his account can be suspended by adding an entry to the suspensions table, which of these class/method signatures do you think is more appropriate?
User::suspend($reason, $expiryDate);
Suspension::add($userid, $reason, $expiryDate);
This is a simple example, but I have this kind of situation everywhere throughout my application. On one hand, I'd want to make it a method of the User object, since the action performed is directly related to that user object itself, but on the other hand making it a method on the suspension object seems a bit cleaner.
What do you think?
you suspend a user.
User.Suspend()
In your User.Suspend method, you can actually add them to your "suspension" table, or call your suspension object. This will lead to a cleaner interface since all you have to do is call the one method.
Its definitely up to you. OO design is very subjective. Here, it depends on whether you view suspension as a noun (a suspension) or a verb (to suspend). If the former, it likely becomes its own object with appropriate methods and attributes. If the latter, it becomes a set of related methods and attributes of the User object.
This brings up another issue: are you a minimalist? There are those that try to keep many, light classes as opposed to a few heavy ones.
Personally, I see cohesion/coupling as outweighing all those factors by orders of magnitude. Basically, for me, it would hinge upon whether other system entities need to know about suspensions without having a User object to query with. If so, the Suspension class would be born. If not, I would keep it as a part of the User class.
Well if adding a suspension is the only real action, I would go with the first option and make it an action carried out by the User class.
However, if you intend on making more functionality for Suspensions, I would consider creating a class like:
class SuspensionManager
suspendUser(....)
getSuspendedUser(...)
....
*This is my opinion is 100% debatable given that I don't know your entire code base/intention
I would say neither. But it really depends on how you view OOAD. I consider both User and Suspension classes have a single purpose. The User class has the responsiblity of holding information directly associated with a User (user table), and the Suspension class has the responsibility of holding information directly associated with a Suspension (suspension table). I would suggest making a UserSuspention class that has the responsibility of suspending a user.
This approach to OOAD is related to SOLID design principals. Having either the User or Suspension class be responsible for suspending a user would violate SRP (single responsibility principal)...since each class already has the responsibilty of maintaining information from their respective tables.
Your potential API may look like something below:
public class UserSuspension
{
public void SuspendUser(User user, Suspension suspension) { ... }
public void SuspendUser(Guid userId, string reason, DateTime expiryDate) { ... }
}
From these two options I would vote for Suspension::add(), if in fact this call would add an entry to the suspensions table. That way the effect that this call in the code has, in terms of the code itself (i.e. not the concepts represented by the code), would be clear: if I saw the code User::suspend(), I would expect it to modify a "suspended" flag for the User object, not modify something else in some other object.
On the other hand, in this particular instance, I think User::suspend() is more clear in general, so I would vote for it if it would mean that a suspended flag would be set for that User object, or if it would seem that way from the interface, i.e. if you wouldn't have to care where the suspension is stored since the interface of the User class would make it seem as if it's one of its properties.
This situation is very typical in web application design. It often becomes easier to deal with objects as being disconnected entities, as it saves you from having to retrieve objects to perform an operation for which you didn't really need the object.
The former is nicer from an OOP sense, the question is whether the performance impact of this would bother you:
User user = GetUser($userId); // unnecessary database hit?
user.suspend(reason, expiryDate);
I would be inclined to have an Account which linked the User and the Suspension
It depends.
This could be one of those scenarios where there isn't a definitely right answer. It will depend on how data will move through your system, as to whether it's of more benefit to view this relationship in a data-centric, or a user-centric model.
An old rule-of-thumb is to view objects as nouns and methods as verbs, when you're trying to model things. This would tend to suggest that User is an object, and suspend is an action you might perform.
Simple ? Not really.
Someone else might argue that it made more sense to describe the suspension as an 'AccountAction', and the application of the suspension as a verb. That might lead you to a model where various subclasses of an AccountAction have an applyTo method that acts on other object types.
You may need to apply your objects to an existing database schema, in which case you'll have to take into account how your persitance layer or ORM will interact with existing record structures.
Sometimes it's down to technology. OO can be implemented in subtly different ways across different language families and this too can influence the design. Some systems favour more solid inheritance graphs, other languages emphasise more loosely interconnected objects, passing messages around.
You need to be thinking through your design in terms of how you're going to want to interact with data and state. If you think about objects, as instances of classes, representing states of data, with behaviours that you will wish to invoke, you might find the nouns and verbs pattern falling out of the sentences that you use to describe the system.
As others have stated, it's very subjective.
Personally, I prefer the User::suspend() alternative simply because it allows me to implement (or change the implementation of) suspension whenever I like. It leaves all the suspension logic hidden behind the User interface.
I often times struggle with the same problem and what I do is I ask myself if this would make sense outside of the programming world. Would you ask ,in real life , a user to suspend him/herself? Would you ask a loan application to approve itself? If the answer is no, then there needs to a specialized authority/component/service that handles that and similar scenarios. In case of loan application, the approval should best be a part of loan approval service or loan specialist. If in your case, asking a user to suspend himself makes sense in the domain you're modeling then it should belong to the user. If not then, a service that handles user account suspension and similar user account level services may be a better place.

How to prevent multiple classes for the same business object?

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.