As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
It's well known fact that static variable cannot be used in
Web Application as it remains static through out application.But,is there any scenario where static variable can be used in Web Application to achieve the functionality?
Thanks
I'm not sure if I understand the question, but there are cases in which using a static variable in a web application is perfectly fine, if one understands the implications. For instance, a common usage in .NET web applications using NHibernate and the "session-per-request" model is to keep a static instance of an ISessionFactory around to create new NHibernate sessions. This is useful since session factories are very heavy objects and generally take a lot of resources to create.
You can store your static information in a number of places...
In a DB
In a cookie
In an Application or Session variable
In a querystring (or even a form variable)
(Or am I misunderstanding the question?)
configuration data, database connection strings, constant data for the application retrieved from a database source.
Anything that doesn't need to change after it's been initialized.
For example, I could get a configuration setting on a page and use if over and over again. In this example once myUrl is initialized it will never have to hit the web.config file again until the web application is restarted.
static public string myUrl = string.Empty
public void SomeRoutine()
{
if ( string.IsNullOrEmpty( myUrl ) )
myUrl = ConfigurationManager.AppSettings[ "myUrl" ].ToString();
...
Response.Redirect( myUrl );
}
You don't mention what web framework you are using, but if you are using ASP.Net, you can assign objects to the Application object or the Session object, which will hold information across the application between requests, and across all requests from an individual user respectively.
If you are asking in a general way, and I suspect you are as this is marked subjective+discussion, then you can try using a cookie to hold the variable across all requests for a user.
As for holding some value for all users, you should have a look at the web framework you are using. You have options such as storing something in a file that is accessible at each request, through to storing something in the equivalent of the Application object of ASP.Net.
I'm sorry if I'm being too pragmatic here, but it's late where I live :).
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it better to use constructors with parameters to initialize the members of a class or do that indirectly using setter functions? I did not get a clear answer on this question so far. Any insights would be appreciated.
It is almost certainly a matter of design choice or sometimes style. I would consider a number of things:
Would constructing an object without setting the member variables leave the class in an invalid state? If so, you'll need your constructor to take valid values for those members. Otherwise, you should be able to provide useful defaults.
Would setting individual members of variables violate a class invariant? If so, they should not have their own setters.
Is the user of this class likely to want to modify individual members? If so, then setters may be appropriate.
Does it make conceptual sense to be able to change individual members of an object? I would argue that it makes no sense to be able to change a Person's date of birth. However, you could argue that changing a Person's name does make sense. It depends. Do you consider a Person whose name has changed to be a different Person in your system?
Can you group setters together to be more useful? Instead of Rectangle::setX(int) and Rectangle::setY(int), does Rectangle::setPosition(int,int) make more sense? Perhaps even Rectangle::setPosition(Point) is better.
In any case, a class whose full set of members are exposed through individual setters and getters is usually a code smell.
The one thing you want to avoid is having an object that isn't complete. If you can supply sensible defaults for every parameter then it's OK to skip setting them in the constructor, otherwise you really should put them there.
Naturally there's no reason you can't do both.
It depends. Certainly use constructor parameters where the object doesn't make sense without a valid class member - for example, scoped smart pointers, or an ofstream's filename.
explicit ofstream ( const char * filename, ios_base::openmode mode = ios_base::out );
Use additional parameters sparingly, and provide default values wherever possible.
However, don't add so many constructor parameters that the order becomes impossible to remember, or if there's a chance of dangerous confusion, such as this.
Person(std::string firstname, std::string lastname, std::string title, std::string occupation,
std::string address, std::string telephone, int age, std::string creditcard, time_t birthday)
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've looked around and haven't found anything specific to my question but that's partially because I'm unsure how to phrase it.
I manage around 20 different C# .NET applications that all do relatively similar things.
I am working on consolidating the common code into a data, business logic, and presentation.
My question is related to the Business Logic layer.
I gather that a business/domain object is one that holds state and sometimes may perform related actions (if you take that approach).
But what would you call an object that is only working through a routine?
For example:
In the presentation layer a button event is fired.
The presentation layer points to this class and calls the "RunJob()"
method.
RunJob() does all the work it needs to do and then finishes. For
example, it may read a table and output it into a CSV (a lot of
these apps are data pushers). It may or may not use internal
fields/properties. These properties may be used to display data in
the interface or to create output.
Is there a name for this or is it just a bad pattern/bad OO in practice? I don't think this qualifies as a business object or helper. I've seen some other topics that hint it might be a "Service" object.
Thanks!
call it WorkerThread for now and see uncle bob's article on naming" http://www.objectmentor.com/resources/articles/Naming.pdf. then change the name to something reasonable.
your class is not necessarily a bad class. most entities usually do not have much behaviour, otoh some helper classes do not have much state.
The name of your objects depend on specifically what work they do. TableImporter and CsvExporter are good names for the tasks you described. The methods should also be appropriately named. It may be the case that you want to abstract an interface Runner and have a generic RunJob method to decouple your presentation and model layers, but it could be more clear and decoupled if you use a controller instead.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Programming languages like C# or Java feature static methods, despite being heavily object oriented.
I'm aware that there are many cases where static methods are used for performance or convenience reasons, but i can't stop wondering if there exist actual coding problems which could not be solved without the use of static methods.
I think that some of the common cases which would be named here could be just "normal" methods, instead of being static, like:
main: The purpose of the main-method is the creation of the very first running thread of the program and starting it. So this might as well just an object derived from a Thread class
Loggers: Logger implementations often use static methods. I don't see the point in that as i might want to exchange a logger for another on with an identical interface
Math: Math functions really seem to be a perfect candidate for static methods at first sight, but there might be cases where you might want to exchange your math library transparently for another one (i.e. if you need more performance on the sin() function you might want to use an implementation with a faster, less precise algorithm if precision is not critical for your application)
Singletons: Are considered bad practice by many. If only one instance is necessary you might think about actually creating only one instance.
So, what might be cases where static methods are really absolutely needed?
IMO, Static methods are needed while defining factories to create objects of different sub types of a given type where the choice of sub type is dependent on the inputs to this static factory method and is hidden from the client.
Your Logger example actually falls under this category where the actual logger is decided based on the package/class it is needed (ofcourse the other factory methods on Logger take other parameters to decide on the appropriate Logger instance to be returned).
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I need to make a CakePHP helper which involves making some HTML dynamically. But the part of the code is to make 1-2 database queries. These queries are very essential for this helper as all the text it populates is inside the database.
According to MVC pattern, i should not be making the DB queries in the View (Helper). I am wondering what the best design would be for this case as i want it to align with PHPUnit testing also.
Any ideas would be welcome...
Since the View job is purely to display the (already available) information passed to it from the Controller, I think it would be something like this:
Your controller:
public function foo() {
$bar = $this->MyModel->find('all');
$this->set(array('bar' => $bar));
}
Your view:
$result = $this->MyHelper->foo($bar);
You can create a component:
/**
* Set data info
* #access public
* #return void
*/
public function setData()
{
$data = $this->Model->find('first', $params);
$this->Controller->set('data', $data);
}
And print the helper in the layout:
echo $this->MyNewHelper->someHtml($data);
If it's something that could be an Element instead of a Helper, you can use CakePHP's RequestAction [details here] to pull the data needed for the Element.
You can then pass any parameters to the Element, and use those to pass to your controller, which does the model call.
This fits very well with MVC, as the Element only displays the view, but it specifies where it should get it's data (still using the model to retrieve it), which makes it very re-usable.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is your perspective on downcasting? Is it ALWAYS wrong, or are there cases where it is acceptable, or even preferable or desired?
Is there some good measure/guideline we can give that tells us when downcasting is "evil", and when it's "ok"/"good"?
(I know a similar question exists, but that question spins out from a concrete case. I'd like to have it answered from a general design perspective.)
No, it's definitely not always wrong.
For example, suppose in C# you have an event handler - that gets given a sender parameter, representing the originator of the event. Now you might hook up that event handler to several buttons, but you know they're always buttons. It's reasonable to cast sender to Button within that code.
That's just one example - there are plenty of others. Sometimes it's just a way around a slightly awkward API, other times it comes out of not being able to express the type within the normal type system cleanly. For example, you might have a Dictionary<Type, object> appropriate encapsulated, with generic methods to add and retrieve values - where the value of an entry is of the type of the key. A cast is entirely natural here - you can see that it will always work, and it's giving more type safety to the rest of the system.
It's never an ideal solution and should be avoided wherever possible - unless the alternative would be worse. Sometimes, it cannot be avoided, e.g. pre-Generics Java's Standard API library had lots of classes (most prominently the collections) that required downcasting to be useful. And sometimes, changing the design to avoid the downcast would complicate it significantly, so that the downcast is the better solution.
An example for "legal" downcasting is Java pre 5.0 where you had to downcast container elements to their concrete type when accessing them. It was unavoidable in that context. This also shows the other side of the question though: if you need to downcast a lot in a given situation, it starts to be evil, so it is better to find another solution without downcasting. That resulted in the introduction of generics in Java 5.
John Vlissides analyzes this issue (aka "Type Laundering") a lot in his excellent book Pattern Hatching (practically a sequel to Design Patterns).