How does this example violate LSP, which then causes violation of OCP? - solid-principles

From Agile Principles, Patterns, and Practices in C# by Robert Martin,
Listing 10-1. A violation of LSP causing a violation of OCP
struct Point {double x, y;}
public enum ShapeType {square, circle};
public class Shape
{
private ShapeType type;
public Shape(ShapeType t){type = t;}
public static void DrawShape(Shape s)
{
if(s.type == ShapeType.square)
(s as Square).Draw();
else if(s.type == ShapeType.circle)
(s as Circle).Draw();
}
}
public class Circle : Shape
{
private Point center;
private double radius;
public Circle() : base(ShapeType.circle) {}
public void Draw() {/* draws the circle */}
}
public class Square : Shape
{
private Point topLeft;
private double side;
public Square() : base(ShapeType.square) {}
public void Draw() {/* draws the square */}
}
DrawShape() violates OCP. It
must know about every possible derivative of the Shape class,
and it must be changed whenever new derivatives of Shape are
created.
The fact that Square and Circle cannot be substituted for Shape is a
violation of LSP. This violation forced the violation of OCP by
DrawShape . Thus, a violation of LSP is a latent violation of OCP.
How does it violate LSP?
(In particular, why can Square and Circle not be substituted for Shape?)
How does violation of LSP cause violation of OCP? (I can see it directly violates OCP, but I can't understand how violation of LSP causes violation of OCP.)

This is not an obvious or typical LSP violation, and one could argue that it isn't an LSP violation at all, but here's my interpretation:
The expectation is that a Shape is described by its type field. When DrawShape receives a Shape object, one of a few things can happen. Depending on the value of the type field, it could try to cast the object to a Square and call its Draw function, or try to cast it to a Circle to the same end. However, this is not guaranteed to work as expected for an arbitrary Shape. Specifically, it will only work if the object's dynamic type actually matches the semantic implication of it's type field. If the type field does not match its dynamic type, an exception will occur when trying to perform the dynamic cast. This is the behavior of DrawShape given a Shape object.
However, given a Square or Circle, there is a different expectation. Specifically, the function is expected to always execute one path or another without an exception, since the semantic implication of the type field will always match the object's dynamic type.
In other words, you could consider the DrawShape function to have four interesting paths of execution for a Shape object: an exception occuring at the dynamic Circle cast, an exception occuring at the dynamic Square cast, or a successful execution of either the Square or Circle draw functions.
When a child is substituted, the first two paths mentioned are no longer possible, and for a given child, only one path is possible.
Alternatively, it could be argued that there is no LSP violation; the function still "acts" in the same way for a child substitution as it would for a parent. Squares and Circles simply have an extra implication, being that the type field will definitely match the dynamic type of the object, restricting the execution results of the function at runtime. While it could be thought of as changing the function expectations, it could also simply be thought of as imposing a pre-condition.
Edit
I suppose I forgot to answer part of the question: The reason this supposed LSP violation "causes" an OCP violation is because the function logic which causes the behavior to be different for Shapes versus Squares and Circles, being the dynamic casting to the children, is the very same logic which forces the Shape class to depend on its children. Thus, by violating the LSP using conditional logic about the subclasses, it in turn violates the OCP.
I don't know if I myself would really call this particular case a situation of "causation" so much as simple event intersection, but perhaps this was the author's intention.

Related

Designation for a function that BOTH manipulates objects AND returns a value, in contrast to functions that either does the former or the latter?

A long time ago, I found out that there were designation for this, but now I forgot it. If the title is misleading, please let me know.
For example, an IEnumerator in C# has a function, MoveNext(), that advances the enumerator to the next element of its collection, you could use it for moving to the next element and/or for checking if there is a next element, since it returns bool.
MoveNext() is not restricted to one use case, like voids that just do something inside their bodies, or functions that just returns a value.
Other methods that have this kind of unconstrained use:
HashSet's Add, which returns a bool if the element already exists but can just be used to try to add the element.
Stack's Pop, which returns the last object and also moves the structure.
Queue's Dequeue, the same for Stack, but returning the first object.
etc.
A little example of the multi-use of such methods:
public class Example
{
Queue<int> testQueue;
public Example()
{
testQueue = new Queue<int>();
testQueue.Enqueue(1);
testQueue.Enqueue(2);
testQueue.Enqueue(3));
testQueue.Enqueue(4);
/// As function:
int v = testQueue.Dequeue(); // I get 1.
/// As method, just to take the elements out.
testQueue.Dequeue();
testQueue.Dequeue();
// The first element is 4.
}
}
Thanks for the help, and excuse me again if the title is somehow ambiguous.
If a function does something else beside returning a value, then it is a function with a side effect. A function without side effects is a pure function.
If a function manipulates any kind of data structure, or object, it is a function with a side effect. A function with side effects does not guarantee that the returned value always will be the same for identical state and for identical parameters, if there is any parameters.
A function without side effects is a pure function. A pure function, in a given state and a given parameter will always return the same value.
To answer your question in full:
A non-void function that changes something is a function with side effects.
A non-void function that only returns something is a pure function.
That leaves us with the function that "does something but doesn't return anything". By the definitions above, such a function would also be a function with side-effects, even if it doesn't return any kind of value.

How to apply the least squares method to built-in models of Levenberg-Marquardt algorithm

I am trying to apply the least squares to my data using the built-in Voigt model from lmfit.
But I have to call the Minimizer class to apply the least squares method, which requires a function.
And I don't have a function since I used the built-in model given by lmfit. There's no simple function I use for Voigt model.
What is your recommendation?
Minimizer class: (http://lmfit.github.io/lmfit-py/fitting.html#module-Minimizer)
I was initially trying to change xtol, ftol and gtol values of the least-square which are 10^-7 by default, and for that I thought I need to call the Minimizer class. However, I could change tol values simply by adding them to model.fit:
output = model.fit(input_y, parameters, x=input_x, \
fit_kws={"ftol":1e-22, "xtol":1e-10, "gtol":1e-22})
Here the output is the model(s) using lmfit.

as3: check if an object is visibly blocked by another object

I'm trying to check if an object is visibly "blocked" by another object at a certain xy spot. The normal hitTest method only states if two objects overlap or not, not which is visibly in front. Is there any way of achieving that, by having the xy-coordinates and two objects? So for example: 2 objects are on stage. Nr. 1 is in front and visibly covers Nr. 2 ... so an xy-hitTest with both objects should only return "true" for object nr. 1.
Thanks in advance :-)
The following function will use hitTestObject and the child indices of the objects to determine if obj1 is "in front of" obj2.
function isInFrontOf(obj1:DisplayObject, obj2:DisplayObject):Boolean{
return obj1.hitTestObject(obj2) && (obj1.parent.getChildIndex(obj1) > obj2.parent.getChildIndex(obj2));
}
Important note: This will only work if both objects have the same parent. You absolutely can rework the function to allow for different parents, but I'll leave that up to you.

AS3 - Displaying points gained above the player

So, I am adding this text field to my container MC whenever a certain condition is met.
In this case, I am trying to display the number of points gained above a playerMC whenever he grabs a coin. Kind of like the old Mario Games whenever you would step on a Goomba and points would appear above the dead Goomba.
I'd like to be able to assign the "points" text field to a "Text.as" file so I could just control the text field's behaviors from there instead of from within my Document Class.
I know how to create a text field from the document class, but I can't seem to create an empty text field on the stage and then convert it into a movie clip so that I can assign it a base class.
Anyone know of a good way to handle this situation? Any ideas you might have.
It's most efficient to just create the textField via code in the contstructor of your Text.as class. However, if you're set on doing it in the flash IDE... create your dynamic text field, give it an instance name, then convert it to a MovieClip with F8. Go to the library and enter you're new movieClip's properties, set the base class to your Text.as file.
Your class (which encapsulates the textField) should then start out looking something like this:
package {
public class Text extends Sprite {
public var myTextFieldInstanceName:TextField;
public function set text(val:String):void { myTextFieldInstanceName.text = val; }
public function get text():String { return myTextFIeldInstanceName.text;}
public function Text(defaultText:String){
text = defaultText;
}
}
}
In order to set the base class, you need to do the same thing that I recommended you do for your Bullet and Impact movieclips. You perform a linkage by selecting "Export to Actionscript". You can tell it what class to look at for its behavior. Then just addChild it to your playerMC (after adjusting x and y values of course).

Find contact normal for sensor in Box2d 2.1a

I am extending the b2ContactListener to find out the normals of my collisions. However, every time I get a contact with a sensor, the normal is always 0,0. How do I get the normal if one of the bodies is a sensor?
override public virtual function BeginContact( contact : b2Contact ) : void
{
var normal : b2Vec = contact.GetFixtureA.GetBody().GetContactList().contact.GetManifold().m_localPlaneNormal;
// normal is always 0,0 if it is a sensor.
}
The normal (and anything else in the contact manifold) is only necessary to calculate what kind of collision response should be applied to push two fixtures apart when they overlap. Since sensors don't have any collision response, this information is not needed and therefore not calculated for them.
One way you could get a normal without the usual collision response is to revert your fixture back to being a non-sensor, and in the PreSolve callback just do contact->SetEnabled(false) for every contact involving that fixture.