Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put application state?

Where in the code do I best put object creation (stateful objects) and where not? In what layers?

For example, I once put an object reference inside a Hibernate DAO class and I was told that this was incorrect because DAO classes are not supposed to have state. State should be inside the 'service layer'.

I have been told that I should not create new objects on recurring method calls such as UpdateCart(). Creation of objects is costly and should not be sitting in your code everywhere. It should be sitting in initialization type methods only. For example, if an e-commerce application needs a cart, put it in the session. If it needs some general main object, put it in the initialization code. Create it once there and let the rest of the application access its instance later. Do not create this instance upon every call.

I'm confused about this whole design principle. The strangest thing I heard is 'an app is not supposed to have state. State should be kept in the data layer where the database is'. Really? I'm quite new to these design concepts and I don't know where to look in order to get more educated on it. GoF? Design Patterns books? The goal is to create qualitative code (i.e. to be used in the business).

Thanks

like image 686
MrStack Avatar asked Sep 23 '12 09:09

MrStack


1 Answers

What is good practice can vary base don the type of project it is.

For most projects, creating objects is not that expensive for the CPU. A cost which is not always articulated well is the cost to the design. It appears your application has a design methodology where all the state and objects need to be managed in a controlled and centralised way. This is often done to improve maintainability and simplify the design. I wouldn't assume you should just know what the design is unless it has been very clearly spelt out to you.

I suspect they rest of the team are used to working a particular way and don't think they should have to document or teach you this methodology, just tell you when you got it "wrong". This is not productive IMHO, but you have to deal with the situation you have and ask them questions when it comes to the placement of state or data structures.

like image 71
Peter Lawrey Avatar answered Oct 06 '22 08:10

Peter Lawrey