I had this questions since the time I learnt about object-oriented programming. Now, I have got a wonderful forum I thought of asking this.
Lets say we are implementing an employee management application using EJB.
Now, there are 2 ways of doing this.
Normally, we create entities (POJOs) which represent an employee. Then we create an EJB interface 'EmployeeManager' with add, delete, update, retrieve, retrieveAll methods. This way I could use 'employee' entity as a data transfer object.
We call the EJB interface itself 'Employee'. Implementation could be called 'EmployeeImpl' which has fields as well as method implementation (add, delete, update, retrieve, retrieveAll). If I am using a layered approach where my business logic needs access to employee details, I need to pass 'EmployeeImpl' (because it contains values).
Which one do you think is the better way?
I prefer the first one, because it 'looks' fine and does not feel awkward. like
EmployeeMgr empMgr = // JNDI lookup;
Employee emp = new Employee();
empMgr.add(emp);
Employee employees[] = empMgr.retrieveAll();
Where as the second one would look like (though I am not sure),
Employee emp = // JNDI lookup;
emp.setName(); //set the properties
emp.add();
Employee employees[] = emp.retrieveAll();
As you can see, the second one looks awkward.
I request you guys to advise me on this.
Thanks
manju
Of your examples, I would not recommend #2, because it gives the Employee class too many responsibilities.
Although not giving a straight answer, I can cordially recommend Martin Fowler's book Patterns of Enterprise Application Architecture. It has been a great eye-opener for me personally, and describes several different approaches to this.
I also think the open-source Hibernate is a great tool for persisting entities. I'm sure you will find lots of good input there.
The first one is certainly clearer, and clarity should certainly be an aim of your code. However, in terms of the first one, I'll direct you here: Jeff Atwood's take on calling things "SomethingManager" - not recommended.
Strive for appropriate design and not "OO Compliance".
Incidentally, EJB is not Object Oriented at all.
The best practice for using EJB is:
DataContainer classes hold data you got from the DB or the user; "POJOs"
EJBs have methods that operate on your DataContainers
DAOs handle persisting/retrieving DataContainers from the database.
EJBs typically do not have fields unless they are to be deployed as Stateless, which is needed only rarely.
If you are using EJBs that would be the design most people would expect. It is clearly not OO, as the DataContainers contain no real methods and the EJBs/DAOs contain no real data.
This is not a bad thing; it separates concerns and makes your system more changeable and maintainable.
Having separare class for persisting Employee looks more OO. And more flexible, because you potentially may want to have DBEmployeeMrg, FileSystemEmployeeMrg, InMemoryEmployeeMgr and MockEmployeeMgr for testing - all those classes may implement inteface EmployeeMrg in different way.
For your code to be shorter you may want to have employee being able to save itself - employee.save() instead of employeeMrg.save(employee)
I can understand design when employee saves itself, updates and even deletes, but definitely one employee is not needed to load another employee by id and to load list of employees.
Related
I have problem in understanding Single Responsibility Principle . Should SRP be applied at class level or at method level.
Lets say i have Student Class ,i need to create student , update student and delete student.
If I create a service class that has methods for these three actions does this break SRP principle.
SRP is at both at class and method level.So if you ar talking about student class then only responsibility it has in this case to do CRUD on student entity.At the same time when you talk about methods the you should not have an InsertStudent method and do both Update and Insert in it based on ID .That breaks SRP.But if you have InsertStudent which inserts and UpdateStudent which updates it follows SRP
I'd say you have a service class which is responsible for CRUD operations on objects of type Student. I don't see this design to violate SRP at all.
Quoting from http://www.developerfusion.com/article/137636/taking-the-single-responsibility-principle-seriously/
Two methods of the same class (or even different classes) should focus on different aspects. However, two methods in the same class, e.g. a repository, likely will both have to be concerned with the same higher level responsibility, e.g. persistence.
I see CRUD as well-known operations within a single context unless you have some business associated with it. For example you might want to allow some classes to only be able to read data and deny them from making any changes to it. That's when you can make use of another SOLID principle Interface segregation.
You can define an interface with only read method defined to be used in those classes. Or if it makes sense (performance-wise for example), create a separate concrete class that just implements read operation.
Not to criticize because I believe in the principal, but don't follow the advice that says it fits if you can summarize the functionality without using "and". With this kind of logic you could still have an enormous one file application and say its responsibility without using "and". A web browser is a complicated piece of software but you can still describe it in one short statement. And it makes total sense because the thing is like a pyramid and you should always be able to describe the top level regardless of the parts being split or not.
That is precisely what we do everyday with functions. You pick a very simple function name which hides the complexity like "connect" for a socket. You actually don't know from this point of view if it is split afterwards. It could be a giant function.
I am afraid it is still subjective. You don't want to judge your design based on your ability to summarize a functionality with words. You always should be because this is how you pick method names and we all know naming is hard.
My advice is to see the SOLID principals as a whole instead of individual rules and build separation around what you think is going to change, and what is less likely to change. The obvious candidate being dependency. It is still going to be subjective, there is no way around that, but it'll help you.
I personally find it very difficult to do at times, but it is worth it. I don't know if you know Ecto which is an elixir project, but I had a "VoilĂ " moment when I've discovered it. It is not perfect is many ways, but the thing with Ecto and separation of concerns in general is that it seems a lot of indirections at first, but then the things are separated make sense. In its best blissful moments, it feels like a lot of small parts that you can trust.
I used to be in the position where it made sense to me that a model should be so smart that it knows how to save itself to the database, how to validates itself, how to do all sorts of things. But the reality is that as soon as you decide you want to work with another database, or validates differently depending on cases, etc, then it becomes hard to get your way out of this. I am sure some developer never felt this way and it is then fine. But for me it is a challenge.
Lots of simple cases, but you want each class to know as less as possible. You don't want your Mail class to know that the css colour for "urgent" is "#FF0000". And then harder ones like sometimes you don't even want it to know it is "urgent" because it depends on use case facts.
This is not easy. In you specific case, I personally would not bother mixing "create" and "delete" for example, but I would make sure interacting with the database is all it does. It does not know if the thing is valid, if it has callbacks, etc. Pretty much the Repository pattern. Again Ecto is a good example, or at least I find it helpful.
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.
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.
I would like to learn how to persist data to a RDBMS from Objective-C, and I don't really know where to start to learn this. Do I learn a RDBMS? Do I learn data modeling?
I'm wondering are there techniques or special considerations when modeling the data as to not run into any pitfalls? I.e. are there rules of thumb like "don't subclass" or "always encapsulate your attributes."
In my limited experience it has been quite difficult to translate an Objective-C class into a relational database. It would seem that CoreData might get me started off on the right path, but it also seems like CoreData kinda just gives me a lot of things to take for granted (I'm curious to know what's going on under the hood with the SQL calls...). Or am I understanding this framework wrong?
I'm looking for any resources that would get me started down the path of better understanding RDBMSes and how Objective-C model classes typically interact with them for data storage.
EDIT:
In an effort to answer my own curiosity, I've picked up Joe Celko's SQL for Smarties as well as Beginning Database Design by Clare Churcher. Neither of them really give much by way of the interaction between controller classes written in non-SQL languages (in my case Objective-C), SQL, and the database. There's a missing link that I'm just not understanding...
Check out BaseTen https://bitbucket.org/mka/baseten/wiki/Home
Sorry it's taken so long to come back to you. What you are asking is not specific to Objective-C. My first introduction of connecting Object-oriented code to RDBMS was Enterprise Object Frameworks in NextStep. But since then, that idea has been copied in most object-oriented languages including Java and Ruby (see ActiveRecord).
Conceptually, on the programming side there is usually a entity class that is used to represent each row of a table. In some cases, such as CoreData or WebObjects, a map is used to create an interface between the application code and the database. Because of this map, a developer can use instances of the generic entity class to represent the data. Of course, many times that class is subclassed to added methods specific to a particular entity.
For example, say you have a table for contacts, which has a column for first name and a column for last name. Often in an application you want to display the full name. In a subclass of the entity class, one can add a method that returns the first and last name as a single string.
In other frameworks, such as ActiveRecord, I believe you must always have a subclass that represents each table.
Conceptually, I find Object-Oriented programming to align well with RDBMS.
Table (contacts) -> Class (Contact)
Row -> Instance of class (aContact)
Columns (firstName) -> Properties (aka instance variables, attributes) (firstName)
Relationships:
to-one (father) -> Properties (father, an instance of Contact)
to-many (emailAddresses) -> Array (emailAddresses, an array of instances of EmailAddress class)
Hope this answers your question better,
I am currently implementing something similar to an hospital intra site, where doctors can see info about their patients.
Currently, I have a LOT of info regarding each Client: his full name, date of birth, blood type, where he lives, diseases he had, etc.
My first attempt was something of the form:
class Client {
private string fullName;
private Date dateOfBirth;
...
public Get/Set FullName()
public Get/Set DateOfBirth()
...
}
which is basically putting everything together under the same class.
After a while I decided that maybe I should pack together similar concepts into a more general one. For example, I can encapsulate both userName and password into the same concept -- LoginInfo, for example.
If doing this, should I provide all the getters/setters on the Client class that delegate the work to the correct inner concepts, or should I just put getters for the concepts themselves? The first approach would shield the outside world to the Client class implementation, but then maybe, we wouldn't win that much by having all these innner concepts.
Should code outside the Client class even know the different kinds of concepts that'd use inside it?
Any other idea / approach?
I still don't know much about what methods I'll need to have on the Client class. Maybe if there are a lot, it'd be definetely good idea to use small inner concepts to group similar methods in themselves, instead of having such a loose coupled big class.
The data of Client will all be persisted using a standard database, if that makes any difference.
I would say it is useful to pack related pieces of data into common classes. I would only provide delegating getters/setters in Client for very commonly used properties though (if even then - it should be a case by case decision). If a concept makes sense in the problem domain, it is fine to expose it to the outside world too. Your LoginInfo is a marginal detail in this regard, but disease history, health check results etc. etc. are prime candidates for this.
I would also recommend you check out Martin Fowler's excellent Analysis Patterns, which dedicates a chapter to health care patterns; you may probably get some useful ideas out of it.
Something to consider when deciding how to organize data: are there any requirements for tracking history of data. For example, do you need to know what the patient's address was 5 years ago (in addition to knowing their current address, of course)? If so, making that "historically-sensitive" data its own class, will likely make it easier for you down the road. Of course, some data won't be "historically-sensitive" - date of birth for example. :)
Something else to consider: what data will be shared among patients? If you maintain data about family medical history, should that data be shared among siblings? If so, then encapsulating that data in its own object will save you lots of copy/synchronization pain later.
These aren't the only considerations when analyzing your data. But they're definitely part of the puzzle.