Why java services are static and final in WebMethods Integration Server - webmethods

I see all the Java services created are static and final in webmethods Integration Server? If all are static then why they didnt go for C as its procedural. I searched this question in http://techcommunity.softwareag.com and https://empower.softwareag.com but didnt found any answers. Can some make me understand why these static and final.

A static method is simply one that is disassociated from any instance of its containing class. The more common alternative is an instance method, which is a method whose result is dependent on the state of a particular instance of the class it belongs to.
The key difference to understand is that a static method can be called without setting up a proper instance of the class it belongs to.In a sense, it is a stateless method.
you ask qus why they didnt go for C as its procedural?
c not object oriented programming language and whole project or program (online, offline) project not depend on two keywords static and final so they follows oops concept

Related

Castle Windsor - should I reference the container from other classes?

I'm about to embark on a new project using Windsor, but I've been wondering about running into scenarios where a Class A might need to instantiate Class B, but it's not feasible or possible for Windsor to inject an instance of Class B into it. I'm struggling to think of a scenario, but here goes:
Say I have a business entity "Customer" that gets passed to a WCF service. This class has an Ent.Lib self-validation method, which in turn uses a helper class "CustomerValidator". The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies. Nor can I pass my CustomerValidator to the self-validation method as it must follow a particular signature for Ent.Lib. So how could I instantiate the CustomerValidator within this class/method? I still want to utilise Windsor rather than simply doing a "var cv = new CustomerValidator();".
It's not a great example as it could be solved in different ways, e.g. passing the Customer object to a validation method rather than having the validation method in the Customer class, but it offers a possible scenario for discussion.
I could expose my WindsorContainer as a public singleton, accessible by any code that needs it, but that seems to be frowned upon. Any other suggestions?
should I reference the container from other classes?
No. By referencing the container, you add complicated and unnecessary dependency to your class which will complicate testing and increase complexity.
The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies.
I think this is the direction you should go, try to explore if there really isn't any way to take control of deserialization so you can inject dependencies.
If that fails, consider using http://commonservicelocator.codeplex.com/. Its Microsoft's service location implementation with Windsor adapter available. It's basically the same pattern as if you referenced the container but you don't introduce dependency on specific container implementation. Also I think it will be easier to mock for testing.

Does Castle Windsor have a Static Class Similar to StructureMap's ObjectFactory?

I am currently making the move from StructureMap to Castle Windsor.
Using StructureMap, you can bootstrap the framework in one central location, and then call ObjectFactory.GetInstance anywhere in your code to grab an instance using that configuration. So conceptually there is a single container that you configure, and calls to the ObjectFactory use that container.
In the tutorials I've seen for Windsor, the container instance is always created explicitly, and resolution happens via the instance of that container. Is this just a difference in approaches between the two frameworks?
Assuming that's the case, what is the recommended way of handling cases where resolution needs to happen separately from configuration?
(Ideally, a single Resolve() call can be made after the configuration code, and no other references to the container will exist; however, there ARE cases where this isn't possible, like when working with a legacy codebase.)
No, it does not. And will not. If you're coming from Structure Map to Castle Windsor, read this.
re: how to pull at a later point w/o static locator see this.
I am not familiar with Windsor, but if it does not already have its own static facade class, it should be trivial to create your own. Create a static class with a static property that holds the configured container. Add a static method that resolves instances from that container. That is exactly what ObjectFactory does. StructureMap has a Container object that does all the real work - ObjectFactory is just a convenience wrapper.
If you really really need this, use CommonServiceLocator. It has adapters to all major IoC containers.

Besides serialization, what would be the legitimate uses of reflection to access private members?

Reflection can be used to access just about any object's internals, which is kind of not cool. I tried to list the legitimate uses of it, but in the end only serialization came to my mind.
What other (legitimate) uses can you find to using reflection in order to access otherwise inaccessible members?
EDIT I mean stuff you can't do if you don't have reflection.
Unit testing comes to mind. If you want to test a private method but not expose it or use the InternalsVisibleToAttribute.
One is persisting objects to a DB. E.g. Hibernate does use reflection, and in some cases e.g. the object's ID might be a private member, with private setter/getter, because it is of no use in the Java domain. However it is needed in the DB, so Hibernate sets/gets it in the background, and uses it for determining object identity.
Another is writing the initial unit tests for badly designed legacy code, where you can't just start refactoring since you have no unit tests to safeguard yourself. In such cases, if other means (described in Working Effectively with Legacy Code) can't help you, reflection may be the last resort to start working towards maintainable code.
I guess one big area where it is used is in the context of managed environment, that is, when an framework or environment is supposed to provide some facilities and might require to access to private data.
Public/private access modifier is a concern at the application design level and a field shouldn't be turned public for the sake of making a framework happy. Examples include then framework like Hibernate which manages object persistence, dependency injection framework which can inject data in private field, or more generally application server which work regardless of the access modifier.
Even more generally, this fall into the umbrella of meta-programming. Some code inspects and modifies other objects dynamically without knowing their structure upfront.
Profiling or monitoring can be useful reasons to use reflection to private members and functions. For example, if you want to know how often a database connection is actually made, you can monitor access to a private SqlConnection.
This can better be done with AOP, but, if trying to get AOP to be acceptable is too difficult politically, then reflection can help out while you are in development.
You can also use reflection to invoke the methods based upon input type parameter ( like enum), thus essentially replacing a switch statement.
for example:
enter code here
public class Test
{
public enum Status
{
Add,
Delete,
Update
}
public void Save(Status status)
{
//use reflection to obtain corresponding method
MethodInfo method = this.GetType().GetMethod(status.ToString(),BindingFlags.NonPublic | BindingFlags.Instance);
//Invoke method here
}
//you don't want to expose these methods
private void Add()
{
}
private void Delete()
{
}
private void Update()
{
}
}
Debugging and profiling come to mind immediately -- they need to be able to get a more complete view of the internals of objects.
Garbage collection is another -- yes, the JVM has a garbage collector built in, but someone has to write that code and while most JVMs aren't written in java, there's no reason they couldn't be.

How should I refactor my code to remove unnecessary singletons?

I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.
Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.
So: How do I go about removing singletons from existing code?
For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:
Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.
Should I instead:
Create one instance of each object and pass references to every object that needs access to them?
Use globals?
Something else?
Globals would still be bad, but at least they wouldn't be pretending.
I see #1 quickly leading to horribly inflated constructor calls:
someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?
Dependency Injection is your friend.
Take a look at these posts on the excellent Google Testing Blog:
Singletons are pathologic liars (but you probably already understand this if you are asking this question)
A talk on Dependency Injection
Guide to Writing Testable Code
Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.
It's not the Singleton-ness that is the problem. It's fine to have an object that there will only ever be one instance of. The problem is the global access. Your classes that use Store should receive a Store instance in the constructor (or have a Store property / data member that can be set) and they can all receive the same instance. Store can even keep logic within it to ensure that only one instance is ever created.
My way to avoid singletons derives from the idea that "application global" doesn't mean "VM global" (i.e. static). Therefore I introduce a ApplicationContext class which holds much former static singleton information that should be application global, like the configuration store. This context is passed into all structures. If you use any IOC container or service manager, you can use this to get access to the context.
There's nothing wrong with using a global or a singleton in your program. Don't let anyone get dogmatic on you about that kind of crap. Rules and patterns are nice rules of thumb. But in the end it's your project and you should make your own judgments about how to handle situations involving global data.
Unrestrained use of globals is bad news. But as long as you are diligent, they aren't going to kill your project. Some objects in a system deserve to be singleton. The standard input and outputs. Your log system. In a game, your graphics, sound, and input subsystems, as well as the database of game entities. In a GUI, your window and major panel components. Your configuration data, your plugin manager, your web server data. All these things are more or less inherently global to your application. I think your Store class would pass for it as well.
It's clear what the cost of using globals is. Any part of your application could be modifying it. Tracking down bugs is hard when every line of code is a suspect in the investigation.
But what about the cost of NOT using globals? Like everything else in programming, it's a trade off. If you avoid using globals, you end up having to pass those stateful objects as function parameters. Alternatively, you can pass them to a constructor and save them as a member variable. When you have multiple such objects, the situation worsens. You are now threading your state. In some cases, this isn't a problem. If you know only two or three functions need to handle that stateful Store object, it's the better solution.
But in practice, that's not always the case. If every part of your app touches your Store, you will be threading it to a dozen functions. On top of that, some of those functions may have complicated business logic. When you break that business logic up with helper functions, you have to -- thread your state some more! Say for instance you realize that a deeply nested function needs some configuration data from the Store object. Suddenly, you have to edit 3 or 4 function declarations to include that store parameter. Then you have to go back and add the store as an actual parameter to everywhere one of those functions is called. It may be that the only use a function has for a Store is to pass it to some subfunction that needs it.
Patterns are just rules of thumb. Do you always use your turn signals before making a lane change in your car? If you're the average person, you'll usually follow the rule, but if you are driving at 4am on an empty high way, who gives a crap, right? Sometimes it'll bite you in the butt, but that's a managed risk.
Regarding your inflated constructor call problem, you could introduce parameter classes or factory methods to leverage this problem for you.
A parameter class moves some of the parameter data to it's own class, e.g. like this:
var parameterClass1 = new MenuParameter(menuBar, editor);
var parameterClass2 = new StuffParameters(sasquatch, ...);
var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
It sort of just moves the problem elsewhere though. You might want to housekeep your constructor instead. Only keep parameters that are important when constructing/initiating the class in question and do the rest with getter/setter methods (or properties if you're doing .NET).
A factory method is a method that creates all instances you need of a class and have the benefit of encapsulating creation of the said objects. They are also quite easy to refactor towards from Singleton, because they're similar to getInstance methods that you see in Singleton patterns. Say we have the following non-threadsafe simple singleton example:
// The Rather Unfortunate Singleton Class
public class SingletonStore {
private static SingletonStore _singleton
= new MyUnfortunateSingleton();
private SingletonStore() {
// Do some privatised constructing in here...
}
public static SingletonStore getInstance() {
return _singleton;
}
// Some methods and stuff to be down here
}
// Usage:
// var singleInstanceOfStore = SingletonStore.getInstance();
It is easy to refactor this towards a factory method. The solution is to remove the static reference:
public class StoreWithFactory {
public StoreWithFactory() {
// If the constructor is private or public doesn't matter
// unless you do TDD, in which you need to have a public
// constructor to create the object so you can test it.
}
// The method returning an instance of Singleton is now a
// factory method.
public static StoreWithFactory getInstance() {
return new StoreWithFactory();
}
}
// Usage:
// var myStore = StoreWithFactory.getInstance();
Usage is still the same, but you're not bogged down with having a single instance. Naturally you would move this factory method to it's own class as the Store class shouldn't concern itself with creation of itself (and coincidentally follow the Single Responsibility Principle as an effect of moving the factory method out).
From here you have many choices, but I'll leave that as an exercise for yourself. It is easy to over-engineer (or overheat) on patterns here. My tip is to only apply a pattern when there is a need for it.
Okay, first of all, the "singletons are always evil" notion is wrong. You use a Singleton whenever you have a resource which won't or can't ever be duplicated. No problem.
That said, in your example, there's an obvious degree of freedom in the application: someone could come along and say "but I want two stores."
There are several solutions. The one that occurs first of all is to build a factory class; when you ask for a Store, it gives you one named with some universal name (eg, a URI.) Inside that store, you need to be sure that multiple copies don't step on one another, via critical regions or some method of ensuring atomicity of transactions.
Miško Hevery has a nice article series on testability, among other things the singleton, where he isn't only talking about the problems, but also how you might solve it (see 'Fixing the flaw').
I like to encourage the use of singletons where necessary while discouraging the use of the Singleton pattern. Note the difference in the case of the word. The singleton (lower case) is used wherever you only need one instance of something. It is created at the start of your program and is passed to the constructor of the classes that need it.
class Log
{
void logmessage(...)
{ // do some stuff
}
};
int main()
{
Log log;
// do some more stuff
}
class Database
{
Log &_log;
Database(Log &log) : _log(log) {}
void Open(...)
{
_log.logmessage(whatever);
}
};
Using a singleton gives all of the capabilities of the Singleton anti-pattern but it makes your code more easily extensible, and it makes it testable (in the sense of the word defined in the Google testing blog). For example, we may decide that we need the ability to log to a web-service at some times as well, using the singleton we can easily do that without significant changes to the code.
By comparison, the Singleton pattern is another name for a global variable. It is never used in production code.

When should a method be static?

In addition, are there any performance advantages to static methods over instance methods?
I came across the following recently: http://www.cafeaulait.org/course/week4/22.html :
When should a method be static?
Neither reads from nor writes to instance fields
Independent of the state of the object
Mathematical methods that accept arguments, apply an algorithm to those
arguments, and return a value
Factory methods that serve in lieu of constructors
I would be very interested in the feedback of the Stack Overflow community on this.
Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.
You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.
Whether or not a method is static is more of a design consideration than one of efficiency. A static method belongs to a class, where a non-static method belongs to an object. If you had a Math class, you might have a few static methods to deal with addition and subtraction because these are concepts associated with Math. However, if you had a Car class, you might have a few non-static methods to change gears and steer, because those are associated with a specific car, and not the concept of cars in general.
Another problem with static methods is that it is quite painful to write unit tests for them - in Java, at least. You cannot mock a static method in any way. There is a post on google testing blog about this issue.
My rule of thumb is to write static methods only when they have no external dependencies (like database access, read files, emails and so on) to keep them as simple as possible.
Just remember that whenever you are writing a static method, you are writing an inflexible method that cannot have it's behavior modified very easily.
You are writing procedural code, so if it makes sense to be procedural, then do it. If not, it should probably be an instance method.
This idea is taken from an article by Steve Yegge, which I think is an interesting and useful read.
#jagmal I think you've got some wires crossed somewhere - all the examples you list are clearly not static methods.
Static methods should deal entirely with abstract properties and concepts of a class - they should in no way relate to instance specific attributes (and most compilers will yell if they do).
For the car example, speed, kms driven are clearly attribute related. Gear shifting and speed calculation, when considered at the car level, are attribute dependent - but consider a carModel class that inherits from car: at this point theyy could become static methods, as the required attributes (such as wheel diameter) could be defined as constants at that level.
Performance-wise, a C++ static method can be slightly faster than a non-virtual instance method, as there's no need for a 'this' pointer to get passed to the method. In turn, both will be faster than virtual methods as there's no VMT lookup needed.
But, it's likely to be right down in the noise - particularly for languages which allow unnecessary parameter passing to be optimized out.
Here is a related discussion as to why String.Format is static that will highlight some reasons.
Another thing to consider when making methods static is that anyone able to see the class is able to call a static method. Whereas when the mehtod is an instance method, only those who have access to an instance are able to call that method.