when they say static classes should not have state/side effects does that mean:
static void F(Human h)
{
h.Name = "asd";
}
is violating it?
Edit:
i have a private variable now called p which is an integer. It's never read at all throughout the entire program, so it can't affect any program flow.
is this violating "no side effects"?:
int p;
static void F(Human h)
{
p=123;
h.Name = "asd";
}
the input and output is still always the same in this case..
When you say "they", who are you refering to?
Anyways, moving on. A method such as what you presented is completely fine - if that's what you want it to do, then OK. No worries.
Similarly, it is completely valid for a static class to have some static state. Again, it could be that you would need that at some point.
The real thing to watch out for is something like
static class A
{
private static int x = InitX();
static A()
{
Console.WriteLine("A()");
}
private static int InitX()
{
Console.out.WriteLine("InitX()");
return 0;
}
...
}
If you use something along these lines, then you could easily be confused about when the static constructor is called and when InitX() is called. If you had some side effects / state changing that occurs like in this example, then that would be bad practice.
But as far as your actual question goes, those kind of state changes and side effects are fine.
Edit
Looking at your second example, and taking the rule precisely as it is stated, then, yes, you are in violation of it.
But...
Don't let that rule necessarily stop you from things like this. It can be very useful in some cases, e.g. when a method does intensive calculation, memoization is an easy way to reduce performance cost. While memoization technically has state and side-effects, the output is always the same for every input, which is the really important .
Side effects of a static member mean that it change the value of some other members in its container class. The static member in your case does not effect other members of its class and it is not violating the sentence you have mentioned.
EDIT
In the second example you've added by editting your question you are violating it.
It is perfectly acceptable for methods of a static class to change the state of objects that are passed to them. Indeed, that is the primary use for non-function static methods (since a non-function method which doesn't change the state of something would be pretty useless).
The pattern to be avoided is having a static class where methods have side-effects that are not limited to the passed-in objects or objects referenced by them. Suppose, for example, one had an embroidery-plotting class which had functions to select an embroidery module, and to scale, translate, or rotate future graphic operations. If multiple routines expect to do some drawing, it could be difficult to prevent device-selections or transformations done by one routine from affecting other routines. There are two common ways to resolve this problem:
Have all the static graphic routines accept a parameter which will hold a handle to the current device and world transform.
Have a non-static class which holds a device handle and world transform, and have it expose a full set of graphic methods.
In many cases, the best solution will be to have a class which uses the second approach for its external interface, but possibly uses the first method internally. The first approach is somewhat better with regard to the Single Responsibility Principle, but from an external calling standpoint, using class methods is often nicer than using static ones.
Related
So my question is:
I got a static class with a static method called:
static class A() {
public static MethodA() { }
}
and I got another class that will call the MethodA() of the static class multiple times:
static class B() {
public static MethodB1() {
MethodA()
}
public static MethodB2() {
MethodA()
}
public static MethodB3() {
MethodA()
}
public static MethodB4() {
MethodA()
}
}
Is this the right approach or should I do it like this (call internal function, which is the only reference to the static method):
static class C() {
public static MethodC1() {
StaticCaller()
}
public static MethodC2() {
StaticCaller()
}
public static MethodC3() {
StaticCaller()
}
public static StaticCaller() {
MethodA()
}
}
I came up that this is a design or philisophy question but is there any technical advantage, like maintainable or scaleable code?
Edit: Or even performance improvements?
This is considered opinion-based as both methods have their own advantages. Many developers here on SO have their own preference so this is challenging to answer without voiding an opinion.
In class B each call goes directly to method A while in class C the call first has to go through a local method before it can go to method A. This extra step can be considered redundant and thus class B would be preferred.
However, for whatever reason you might have to change the call from method A to method D, from a class you haven't made yet. In that case, you would have to change four methods in class B and just one in class C. Thus class C is easier to maintain and adjust.
Both thus have their pros and cons and class B gives a very minor performance gain. (Literally clock ticks!)
So in general, it really doesn't matter much so my advise is to pick the solution that is best to read for developers. This means adding comments, use proper formatting, use clear method names and try to avoid repeating yourself!
And that latter comment means that both class B and class C are bad practice as each class is repeating a call to some method. You should reconsider reshaping those methods into a single method. Which can be tricky as there might be a lot of differences in these methods.
Wim ten Brink wrote the answer I would have, so at best I can make additions to what he said:
I loathe working with statics. Replacing the call to one static with the call to another is a pain. For that reason I prefer C. It makes it easy to replace.
But I do actually have two other options that may be worth considering:
1st
As I loathe statics, I try to avoid writing them. And all of your classes are still statics, passsing the Problem down. If I need something like this and it has any non-constant field, I would not make it a static. I would instead make it a normal instance-requiring class. And then make a static field that takes a instance of this class. It might not sound like that differnce, but replacing:
static staticsProvider SP = new ImplementationA();
with
static staticsProvider SP = new ImpelentationB();
Allows a quick swap. Also if you ever need two or more different instances for different pieces of codes (SP1 and SP2), this is now just one additional static field and instnatiation away. Those are the two big issues of statics taking care off. And you could still use instances in class or function scope too.
Now the WPF way is "If you can not change it, wrap it into something you can change!". So how about option D:
//I am not a static
public class D{
//I am not either
public void MethodA(){
//But I do call one for you
A.MethodA();
}
}
You can then create a static field:
static public D SP = new D();
If you need more then one static provider? make another field. If you need a different implementation? Extract a Interface (actually a VS IDE Option) or create a abstract baseclass from D. change the variables to said baseclasss/Interface. Then make a class D2, wich inherits/implements from what you just created.
Do not want it to change at runtime? const or readonly modifiers. But actually the abiliy to exchange instance at runtime might be a feature.
2nd
Rather then trying to cut down on calls for static, how about cutting down on versions of MethodBX and MethodCX?
By using delegates you could hand in the code for the "beforeStatic" and "afterStatic" parts as functions.
This is however only adviseable for really small differences. If you got large differences, writing two large delegates for each call would make it less manageable then just writing the mutliple functions you got now.
Function call overhead
There is a cost to calling functions. In effect the CPU has to make a jump. And jumps are still a thing whose cost can be measured. It will propably not mater in the big picture - we are way past the time we pinched CPU cycles. Also, it might be avoided autoamtically:
Native C++ has the inline compiler hint.
Afaik .NET does not allow this control. But it does have the JiT and Compiler Optimisations. And those can totally go and inline for your automatically. And for a function like this:
public static StaticCaller() {
MethodA();
}
Let me just say that if there are any function to be inlined, the ones that look like this have to be on the top of the list.
Perhaps strategy pattern isn't what I'm after. Say my code looks like this (pseudo version):
class Machine
{
private Stack<State> _internals;
public void DoOperation(Thingy x)
{
switch (x.operation)
{
case Op.Foo:
DoFoo();
break;
case Op.Bar:
DoBar();
break;
case Op.Baz:
DoBaz();
}
}
private void DoFoo()
{
// pushing and popping things from _internals, doing things to those States
}
private void DoBar()
{
// similarly large method to foo, but doing something much different to _internals
}
private void DoBaz()
{
// you get the idea...
}
}
Foo, Bar, and Baz are rather complex methods (not extremely long, just deserve separating) so I want to break them into classes with a common interface, a la strategy pattern. The problem is, I can't encapsulate _internals in those classes. I mean, I could pass it into the Execute method on those classes, but that seems like a bad way to go. The internals persist longer than the single operation, so the strategy classes can't "own" the internals themselves. Multiple different operations could be done on this Machine, with different Thingy's passed in.
Is there a different route you can suggest?
edit
This is kind of a state machine, but not in the sense that one operation is only valid in a particular state. _internals is a stack of states instead of just the current state. Any of the three operations can be done at any time.
Your strategy 'strategy' seems sound. Code looks good so far, you need to actually declare an interface, but I think you got that.
I dot't see why you can't pass the _internals. That would be part of the interface definition. That members be able to accept a type of " : _internals_data" or whatever.
You could wrap it up a bit, my defining the interface to be like
Execute
sendinlimitedsubsetofinternals
Returnsmodifiedsubsetofinternals
Then the two data methods could be like just an array of strings or something to really tighten down the interaction. Then you could use a serialization in the middle sometime later or something.
When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed.
Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too.
My question are:
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?
No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation.
#Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx
Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)
Builder pattern.
I think it is OK, but there are implications. If this is an object to be used by others, you need to ensure that an exception is thrown any time a method or property is set or accessed and the initialization should have been called but isn't.
Obviously it is much more convenient and intuitive if you can take care of this in the constructor, then you don't have to implement these checks.
I don't see anything wrong in this. It may be not so convinient, but you can not ALWAYS use initialization in ctor, like you can not alwats drive under green light. These are dicisions that you made based on your app requirements.
It's ok. Immagine if your object, for example, need to read data from TCP stream or a file that ciuld be not present or corrupted. Raise an exception from ctor is baaad.
It's ok. If you think, for example, about some your DSL language compiler, it can looks like:
A) find all global variables and check if there mem allocation sum sutisfies your device requierements
B) parse for errors
C) check for self cycling
And so on...
Hoe this helps.
Answering (1)
Why not? An engine needs the driver because this must enter the key for the car, and later power-on. Will a car do things like detecting current speed if engine is stopeed? Or Will the car show remaining oil without powering-on it?
Some programming goals won't be able to have their actors initialized during its object construction, and this isn't because it's a non-proper way of doing things but because it's the natural, regular and/or semantically-wise way of representing its whole behavior.
Answering (2)
A decent class usage documentation will be your best friend. Like answer to (1), there're some things in this world that should be done in order to get them done rightly, and it's not a problem but a requirement.
Checking objects' state using flags isn't a problem too, it's a good way of adding reliability to your object models, because its own behaviors and consumers of them will be aware about if things got done as expected or not.
First of all, Factory Method.
public class MyClass
{
private MyClass()
{
}
public Create()
{
return new MyClass();
}
}
Second of all, why do you not want another class creating an object for you? (Factory)
public class MyThingFactory
{
IThing CreateThing(Speed speed)
{
if(speed == Speed.Fast)
{
return new FastThing();
}
return new SlowThing();
}
}
Third, why do multiple classes have side effects on new instances of your class? Don't you have declarative control over what other classes have access to your object?
I have a large abstract class that handles weapons in my game. Combat cycles through a list of basic functions:
OnBeforeSwing
OnSwing
OnHit || OnMiss
What I have in mind is moving all combat damage-related calculations to another folder that handles just that. Combat damage-related calculations.
I was wondering if it would be correct to do so by making the OnHit method an extension one, or what would be the best approach to accomplish this.
Also. Periodically there are portions of the OnHit code that are modified, the hit damage formula is large because it takes into account a lot of conditions like resistances, transformation spells, item bonuses, special properties and other, similar, game elements.
This ends with a 500 line OnHit function, which kind of horrifies me. Even with region directives it's pretty hard to go through it without getting lost in the maze or even distracting yourself.
If I were to extend weapons with this function instead of just having the OnHit function, I could try to separate the different portions of the attack into other functions.
Then again, maybe I could to that by calling something like CombatSystem.HandleWeaponHit from the OnHit in the weapon class, and not use extension methods. It might be more appropriate.
Basically my question is if leaving it like this is really the best solution, or if I could (should?) move this part of the code into an extension method or a separate helper class that handles the damage model, and whether I should try and split the function into smaller "task" functions to improve readability.
I'm going to go out on a limb and suggest that your engine may not be abstracted enough. Mind you, I'm suggesting this without knowing anything else about your system aside from what you've told me in the OP.
In similar systems that I've designed, there were Actions and Effects. These were base classes. Each specific action (a machine gun attack, a specific spell, and so on) was a class derived from Action. Actions had an list of one or more specific effects that could be applied to Targets. This was achieved using Dependency Injection.
The combat engine didn't do all the math itself. Essentially, it asked the Target to calculate its defense rating, then cycled through all the active Actions and asked them to determine if any of its Effects applied to the Target. If they applied, it asked the Action to apply its relevant Effects to the Target.
Thus, the combat engine is small, and each Effect is very small, and easy to maintain.
If your system is one huge monolithic structure, you might consider a similar architecture.
OnHit should be an event handler, for starters. Any object that is hit should raise a Hit event, and then you can have one or more event handlers associated with that event.
If you cannot split up your current OnHit function into multiple event handlers, you can split it up into a single event handler but refactor it into multiple smaller methods that each perform a specific test or a specific calculation. It will make your code much more readable and maintainable.
IMHO Mike Hofer gives the leads.
The real point is not whether it's a matter of an extension method or not. The real point is that speaking of a single (extension or regular) method is unconceivable for such a complicated bunch of calculations.
Before thinking about the best implementation, you obviously need to rethink the whole thing to identify the best possible dispatch of responsibilities on objects. Each piece of elemental calculation must be done by the object it applies to. Always keep in mind the GRASP design patterns, especially Information Expert, Low Coupling and High Cohesion.
In general, each method in your project should always be a few lines of code long, no more. For each piece of calculation, think of which are all the classes on which this calculation is applicable. Then make this calculation a method of the common base class of them.
If there is no common base class, create a new interface, and make all these classes implement this interface. The interface might have methods or not : it can be used as a simple marker to identify the mentioned classes and make them have something in common.
Then you can build an elemental extension method like in this fake example :
public interface IExploding { int ExplosionRadius { get; } }
public class Grenade : IExploding { public int ExplosionRadius { get { return 30; } } ... }
public class StinkBomb : IExploding { public int ExplosionRadius { get { return 10; } } ... }
public static class Extensions
{
public static int Damages(this IExploding explosingObject)
{
return explosingObject.ExplosionRadius*100;
}
}
This sample is totally cheesy but simply aims to give leads to re-engineer your system in a more abstracted and maintenable way.
Hope this will help you !
It's generally agreed upon that relying heavily on global stuff is to be avoided. Wouldn't using static classes and methods be the same thing?
Global data is bad. However many issues can be avoided by working with static methods.
I'm going to take the position of Rich Hickey on this one and explain it like this:
To build the most reliable systems in C# use static methods and classes, but not global data. For instance if you hand in a data object into a static method, and that static method does not access any static data, then you can be assured that given that input data the output of the function will always be the same. This is the position taken by Erlang, Lisp, Clojure, and every other Functional Programming language.
Using static methods can greatly simplify multi-threaded coding, since, if programmed correctly, only one thread will have access to a given set of data at a time. And that is really what it comes down to. Having global data is bad since it is a state that can be changed by who knows what thread, and any time. Static methods however allow for very clean code that can be tested in smaller increments.
I know this will be hotly debated, as it flies in the face of C#'s OOP thought process, but I have found that the more static methods I use, the cleaner and more reliable my code is.
This video explains it better than I can, but shows how immutable data, and static methods can produce some extremely thread-safe code.
Let me clarify a bit more some issues with Global Data. Constant (or read-only) global data isn't nearly as big of an issue as mutable (read/write) global data. Therefore if it makes sense to have a global cache of data, use global data! To some extent every application that uses a database will have that, since we could say that all a SQL Database is one massive global variable that holds data.
So making a blanket statement like I did above is probably a bit strong. Instead, let's say that having global data introduces many issues that can be avoid by having local data instead.
Some languages such as Erlang get around this issue by having the cache in a separate thread that handles all requests for that data. This way you know that all requests and modifications to that data will be atomic and the global cache will not be left in some unknown state.
static doesn't necessarely mean global. Classes and members can be static private, hence only applying to the specific class. That said, having too many public static members instead of using appropriate ways to pass data (method calls, callbacks, etc.) is generally bad design.
If you're trying to be purist about your OO development, then statics probably don't fit the mold.
However the real world is messier than theory, and statics are often a very useful way to solve some development problems. Use them when appropriate, and in moderation.
As an addition to whatever else is said, final static variables are just fine; constants are a good thing. The only exception to that is when/if you should just move them to a properties file, to be easier to change.
Mutable static variables are bad because they're just global state. The best discussion I know of about this is here, under the heading "Why Global Variables Should Be Avoided When Unnecessary".
Static methods have several drawbacks that often make them undesirable - the biggest one being that they cannot be used polymorphically.
First, why are the old global variables so bad? Because it is state that is accessible from anywhere, any time. Hard to track.
There are no such problems with static methods.
That leaves static fields (variables). If you declared a public static field in a class, that would truly be a global variable and it would be bad.
But make the static field private and most problems are solved. Or better, they are limited to the containing class and that makes them solvable.
public class Foo
{
private static int counter = 0;
public static int getCounterValue()
{
return counter;
}
//...
public Foo()
{
//other tasks
counter++;
}
}
In the code above you can see that we count how many Foo objects were created. This can be useful in many cases.
The static keyword is not global, it's telling you that it's on class level, which can be very useful in various cases. So, in conclusion, class level things are static, object level things are not static.
Static methods are used to implement traits in Scala. In C#, extension methods (which are static) fulfill that role in part. That could be seen, as the DCI proponents state, as a "higher order form of polymorphism".
Also, static methods can be used to implement functions. This is what F# uses to implement modules. (And also VB.NET.) Functions are useful for (unsurprisingly) functional-programming. And sometimes they're just the way something should be modeled (like the "functions" in the Math class). Again, C# comes close here.
I think the bad thing about global variables is the idea of having global state - variables that can be manipulated anywhere and tend to cause unintended side effects in far-flung areas of a program.
Static data would be similar to global variables in that they introduce a kind of global state. Static methods though are not nearly as bad, assuming they are stateless.
Not entirely. Static actually determines when, where and how often something is instantiated, not who has access to it.