How Law of Demeter and Vector interacts? - oop

So i have this code:
Public class Worker{
private String gender;
...
public Boolean isMale(){
return gender=="Male";
}
}
Public class Business{
private Vector<Worker> vWorkers;
...
public void showMaleWorkers(){
for(Integer I=0; I<vWorkers.size();I++){
if(vWorkers.elementAt(I).isMale()){
...
}
}
}
}
Is the "if" breaking the law of demeter and if yes how could I solve it?

It does. Both technically and conceptually.
It's not your code though. The culprit is the Vector which gives out internal state, instead of thinking ahead and implementing behavior.
The behavior in the vector's domain that it should implement for us would be "iterating" and "filtering". Something like this:
public void showMaleWorkers() {
vWorkers
.filter(_.isMale())
.forEach(...);
}
This does not violate LoD while doing the exact same thing. At no point are we calling methods on things that we don't have access to directly. This is sometimes called "functional style", because filter() and map() etc. were first prevalent in functional languages. Curiously this is actually more object-oriented too.

Related

How to make interface implementors that are not sub classes of its abstract class behave like abstract class of that interface?

I want to explain my question with an example. Lets say that i have an interface:
interface IActionPerformer
{
bool IsReadyToExecuteAction();
void Action();
IActionImplementor GetImplementor();
}
And an implementor for Action() method. I don't know if it is the right or wrong way to do so, but anyways, keep reading i will explain my purpose. Implementor:
interface IActionImplementor
{
void Action();
}
And an abstract class that implements IActionPerformer:
abstract class ActionPerformerBase: IActionPerformer
{
private IActionImplementor _implementor;
public abstract bool IsReadyToExecuteAction();
public IActionImplementor GetImplementor()
{
return _implementor;
}
public void Action()
{
if (IsReadyToExecuteAction())
{
GetImplementor().Action();
}
}
protected ActionPerformerBase(IActionImplementor implementor)
{
this._implementor = implementor;
}
}
Now sub classes which inherit from this abstract class, execute the actual action only if it is ready to execute.
But let's say that i have an object in my software, that inherits from a different super class. But at the same time, this object must behave like an IActionPerformer. I mean this object must implement IActionPerformer interface, like:
class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
At this point, i want to execute Action() method with controlling if it is ready to execute.
I thought invoking method with another object might be a solution. I mean, a controller or handler object gets interface as a parameter and invokes method the way i want. Like:
IActionInvoker.Invoke(IActionPerformer performer)
{
if (performer.IsReadyToExecuteAction())
{
performer.Action();
}
}
Or every IActionPerformer implementor has a IActionPerformer or ActionPerformerBase(it feels better) object which handles the real control like:
class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
{
ActionPerformerBase _realHandler;
public bool IsReadyToExecuteAction()
{
return _realHandler.IsReadyToExecuteAction();
}
public void Action()
{
_realHandler.Action();
}
.
.
.
}
//This is the one get the job done actually.
class RealHandlerOfSomething : ActionPerformerBase
I might not be that clear trying to explain my question. I'm new to concepts like abstraction, design patterns and sort of stuff like that. And trying to figure out them. This one looks like a decorator, it is a IActionPerformerand it has a IActionPerformer. But when i study decorator pattern, i saw it is like going from shell to the core, i mean every object executes its method and the wrapped objects method. It is a bit different in my example, i mean question. Is this what we call as "encapsulation"? Or do i have big issues understanding the concepts?
I hope i explained myself clearly. Thanks for everyone reading, trying to help.
Have a nice day/night.
As Design Patterns states in chapter one:
Favor object composition over class inheritance
This was in 1994. Inheritance makes things complicated. The OP is another example.
In the following, I'll keep IActionPerformer and ActionPerformerBase as is. Since inheritance is isomorphic to composition, everything you can do with inheritance, you can also do with composition - and more, such as emulating multiple inheritance.
Here's how you can implement the IActionPerformer interface from another subclass, and still reuse ActionPerformerBase:
public class SomeOtherSubClass : SomeOtherSuperClass, IActionPerformer
{
private readonly ActionPerformerBase #base;
public SomeOtherSubClass(ActionPerformerBase #base)
{
this.#base = #base;
}
public void Action()
{
// Perhaps do something before calling #base...
#base.Action();
// Perhaps do something else after calling #base...
}
// Other methods of IActionPerformer go here, possibly following the same pattern...
}
SomeOtherSubClass composes with any ActionPerformerBase, and since ActionPerformerBase has the desired functionality, that functionality is effectively reused.
Once you've figured out how to use composition for reuse instead of inheritance, do yourself a favour and eliminate inheritance from your code base. Trust me, you don't need it. I've been designing and writing production code for more than a decade without inheritance.

How to deal with "optional interfaces"?

"Optional interface" is probably not a standard term, so let me give an example. Suppose I have:
interface Car {
start();
honk();
}
Now I can have like HondaCar, PriusCar, etc., implementations. Yay! But what if honking is not all that important to me or my users, so I decide to do something like this:
interface Car {
start();
canHonk(); // return true if honking is supported
honk(); // undefined behavior of canHonk is false
}
So this is what I'm calling an "optional interface", because actually supporting honk is optional. It still seems like a fine, well-defined interface, but another way you could've expressed this is by separating this into two interfaces:
interface Car {
start();
}
interface Honkable {
honk();
}
Now, if user code really needs to do some honking, you must pass it a Honkable. If it's optional, it can take a null pointer. And if it doesn't care about honking at all, it can ignore Honkable completely. However, this does put more onus on the user code to manage all this.
So, I've listed some pros and cons that I see, but I'm curious what others think. Which is the preferable pattern in which situations?
Composition over Inheritance, our subject here, is an important OOP principle. It tells us to define our objects by their functions. Which means, your second approach is the best practice. Do it like:
public class SomeCar: ICar, IHonk {}
public Interface ICar {}
public Interface IHonk {}
Design for capability instead of identity.
Two separate interfaces is the way to go in my opinion
If you want to honk, implement the interface
As others have mentioned, separate interfaces are a better solution here. It is also worth noting that it conforms to the Interface Segregation Principle from SOLID.
However, another approach would be to use a feature container:
public class FeatureContainer {
// ...
public bool isAvailable<T>() {
// ...
}
public T getFeatureOrNull<T>() {
// ...
}
}
and then have for example:
public abstract class Car : FeatureContainer {
// ...
};
public class SomeCar : Car {
public SomeCar()
: base(/* instantiate all implementations of supported interfaces */)
{}
}
so then you could have:
Car aCar = getSomeCar();
if (aCar.isAvailable<Honkable>()) {
Honkable h = aCar.getFeatureOrNull<Honkable>();
h.honk();
}
This can have of course numerous syntactical variations depending on language and desired semantics.

Concepts where an object can behave like it implements an interface which it has the method signatures for, w/o explicitly implementing the interface?

I'd like to ask whether this is a useful concept, if other languages have ever done this sort of thing, or if this idea is problematic or just bad. If it is problematic, an explanation of what principles it violates would also be greatly appreciated.
For the sake of being clear about what I mean, I've written some C# pseudocode where I've created an imaginary "lazy" keyword that provides a concrete implementation of this idea. The "lazy" keyword instructs the compiler to 1) explicit cast any object that has functions that conform to an interface contract to that interface, even if the object in question does not explicitly implement the interface and 2) if said explicit cast function doesn't exist, create it, 3.) The object can be cast back to what it was originally, 4.) If the object doesn't implement the methods required by the interface, you get a compiler error.
Then the following code would compile and run.
class Program
{
public interface iRoll
{
public void Roll();
public int Dimensions { get; set;}
}
public class Basketball
{
public void Roll()
{
Console.WriteLine("I'm a rolling basketball");
}
private int _dimensions = 3;
public int Dimensions { get { return _dimensions; } set { _dimensions = value; } }
public string Brand = "BallCo.";
}
public class Tire
{
public void Roll()
{
Console.WriteLine("I'm a rolling tire");
}
private int _dimensions = 3;
public int Dimensions { get { return _dimensions; } set { _dimensions = value; } }
}
static void Main(string[] args)
{
Tire MyTire = new Tire();
Basketball MyBall = new Basketball();
var myList = new List<iRoll>();
myList.Add(lazy iRoll MyTire);
myList.Add(lazy iRoll MyBall);
foreach(iRoll myIRoll in myList)
{
myIRoll.Roll();
Console.WriteLine("My dimensions: " + myIRoll.Dimensions);
}
}
}
The benefits are not always having classes implement interfaces like crazy, and not having to derive from a base class just to implement a custom interface when the base class already has the methods and properties you need (e.g., certain situations with external libraries, certain UI controls).
Good idea, bad idea, terrible idea? Do any other languages experiment with this?
Thanks to all of you for the information. I found a similar question to my own with some interesting information. Two very important related and different concepts to learn about are structural typing and duck typing , both of which could fit my original question.
In my example, C# uses nominal typing which is not compatible with structural typing. The "lazy" keyword I proposed is a keyword that causes a nonimally-typed system to do certain things that make it look to a programmer like a structurally typed system. That should be static duck typing in a nominally typed language, for this example.
I wonder if someone could say the lazy keyword isn't "really" duck typing, but semantic sugar to have classes implement interfaces, if the implementation details of the lazy keyword caused the compiler to have the class operated on to implement any interfaces it needs to implement at compile time. However, I think duck typing is an OOP concept, so this should be duck typing regardless of what the compiler does as long as the end result acts like duck typing. Please feel free to correct anything I'm mistaken about or disagree.
There's a great section in the Wikipedia article about duck typing that shows many examples of it in programming languages.

IntelliJ Idea's Law of Demeter inspection. False positive or not?

Suppose the next class
interface Thing {
void doSomething();
}
public class Test {
public void doWork() {
//Do smart things here
...
doSomethingToThing(index);
// calls to doSomethingToThing might happen in various places across the class.
}
private Thing getThing(int index) {
//find the correct thing
...
return new ThingImpl();
}
private void doSomethingToThing(int index) {
getThing(index).doSomething();
}
}
Intelli-J is telling me that I'm breaking the law of demeter since DoSomethingToThing is using the result of a function and supposedly you can only invoke methods of fields, parameters or the object itself.
Do I really have to do something like this:
public class Test {
//Previous methods
...
private void doSomething(Thing thing) {
thing.doSomething();
}
private void doSomethingToThing(int index) {
doSomething(getThing(index));
}
}
I find that cumbersome. I think the law of demeter is so that one class doesn't know the interior of ANOTHER class, but getThing() is of the same class!
Is this really breaking the law of demeter? is this really improving design?
Thank you.
Technically, this is breaking the Demeter's laws. Though I would contest that private functions should be considered for LoD-F, as supposedly they are not accessible from outside. At the same time, it's not really breaking Demeter's laws, if 'thing' is owned by Test. But in Java, the only way to get to thing may be through a getter, which takes this back to that technicality (no clear separation between getter and action methods).
I would say, do this:
public class Test {
private Thing getThing(int index) {
//find the thing
return thing;
}
private void DoSomethingToThing(Thing thing) {
thing.doSomething();
}
private void DoSomethingToThing(int index) {
DoSomethingToThing(getThing(index));
}
}
Or, probably better, have the caller use thing directly. Which is possible if Test's function is to produce or expose things, rather than being the intermediary to manipulate thing.
IntelliJ is not detecting object instantiation correctly.
Wikipedia (what IDEA links to) describes that you can call objects created in the current context.
That's what I do, but still I get the warning on getMajor():
Version version = Loader.readVersion(inputStream); // Instantiates a new Version
if (version.getMajor() != 2)
throw new IOException("Only major version 2 is supported");
IDEA's inspection offers an option to ignore calls to 'library' methods. In my case, Loader.readVersion() is a library method, however it's located inside the current project (the project must be self-supporting). IDEA thinks it's not a library method.
Since the mechanism of this inspection is inadequate/incomplete/naive (like with MANY of IDEA's inspections btw), the only solution is disabling it and attempt to avoid these situations manually.

Managing inter-object relationships

How do you code special cases for objects?
For example, let's say I'm coding an rpg - there are N = 5 classes. There are N^2 relationships in a matrix that would determine if character A could attack (or use ability M on) character B (ignoring other factors for now).
How would I code this up in OOP without putting special cases all over the place?
Another way to put it is, I have something maybe
ClassA CharacterA;
ClassB CharacterB;
if ( CharacterA can do things to CharacterB )
I'm not sure what goes inside that if statement, rather it be
if ( CharacterA.CanDo( CharacterB ) )
or a metaclass
if ( Board.CanDo( CharacterA, CharacterB ) )
when the CanDo function should depend on ClassA and ClassB, or attributes/modifiers with ClassA/ClassB?
i would start with a canSee(Monster monster) or canBeSeenBy(Monster monster) method and see what happens. you may end up with a Visibilility class or end up using the http://en.wikipedia.org/wiki/Visitor_pattern. an extreme example is uncle bobs triple dispatch:
// visitor with triple dispatch. from a post to comp.object by robert martin http://www.oma.com
/*
In this case, we are actually using a triple dispatch, because we have two
types to resolve. The first dispatch is the virtual Collides function which
resolves the type of the object upon which Collides is called. The second
dispatch is the virtual Accept function which resolves the type of the
object passed into Collides. Now that we know the type of both objects, we
can call the appropriate global function to calculate the collision. This
is done by the third and final dispatch to the Visit function.
*/
interface AbstractShape
{
boolean Collides(final AbstractShape shape);
void Accept(ShapeVisitor visitor);
}
interface ShapeVisitor
{
abstract public void Visit(Rectangle rectangle);
abstract public void Visit(Triangle triangle);
}
class Rectangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
RectangleVisitor visitor=new RectangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Rectangle
}
class Triangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
TriangleVisitor visitor=new TriangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Triangle
}
class collision
{ // first dispatch
static boolean Collides(final Triangle t,final Triangle t2) { return true; }
static boolean Collides(final Rectangle r,final Triangle t) { return true; }
static boolean Collides(final Rectangle r,final Rectangle r2) { return true; }
}
// visitors.
class TriangleVisitor implements ShapeVisitor
{
TriangleVisitor(final Triangle triangle)
{ this.triangle=triangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,triangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(triangle,this.triangle); }
boolean result() {return result; }
private boolean result=false;
private final Triangle triangle;
}
class RectangleVisitor implements ShapeVisitor
{
RectangleVisitor(final Rectangle rectangle)
{ this.rectangle=rectangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,this.rectangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(rectangle,triangle); }
boolean result() {return result; }
private boolean result=false;
private final Rectangle rectangle;
}
public class MartinsVisitor
{
public static void main (String[] args)
{
Rectangle rectangle=new Rectangle();
ShapeVisitor visitor=new RectangleVisitor(rectangle);
AbstractShape shape=new Triangle();
shape.Accept(visitor);
}
}
Steve Yegge has an awesome blog post about the Properties pattern that you could use handle this. In fact, he wrote an RPG using it!
http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html
You might say player1 is a type1 and type1s can attack type2s and player2 is a type2, so unless there is some "override" on the specific player1, player1 can attack player2.
This enables very robust and extensible behavior.
What is the definition of "see"? If they occupy the same square? If so, this will be answered in how you implement collision detection (or whatever in this case) rather then OOP relationships between characters. Without knowing more information, I would approach the problem in this manner (in C++/pseudo code for illustration):
class Character {
private:
matrixSquare placement;
public:
Character() {};
~Character {};
matrixSquare getLocation() { return placement;};
};
class GameBoard {
private:
//your 5 x 5 matrix here
public:
GameBoard() {};
~GameBoard() {};
boolean isOccupied(matrixSquare)
{
if (occupied)
{
//do something
return true;
}
else
{
return false;
}
}
};
The trick here is to define the relationship between your character pieces and your implementation of the playing field. After that is established you could then clarify how you determine if two characters are in the same square, adjoining squares, etc... Hope that helps.
I would say use design patterns, generally I think Observer, Mediator and Visitor patterns are quite good for managing complex inter-object relationships.
I would (assuming C++) give each class a std::string identifier, returned by a getter method on the class's instance, and use a std::map< std::pair<std::string, std::string>, ... > to encode the special cases of relationship between classes, all nice and ordered in one place. I'd also access that map exclusively through a getter function so that changing the strategy for encoding some or all of the special cases is made easy as pie. E.g.: if only a few pairs of classes out of the 25 have the "invisibility" property, the map in that case might contain only the few exceptions that do have that property (for a boolean property like this a std::set might actually be a preferable implementation, in C+_).
Some OO languages have multi-dispatch (Common Lisp and Dylan are the two that come to mind at the moment), but for all the (vast majority) of languages that lack it, this is a good approach (in some cases you'll find that a centralized map / dict is restrictive and refactor to a Dynamic Visitor design pattern or the like, but thanks to the "getter function" such refactorings will be pretty transparent to all the rest of your code).
In response to your edit of your question, you'll want to look into polymorphism. I personally would have the cando() function be a part of the Board, then, depending on the two classes passed in, the Board would call the appropriate function and return the result (of battle, of seeing, so on and so forth).
If you're doing this in java an enum/interface to go along with your Game Board would be a very clean way of approaching this problem.
I suggest you look at double dispatch pattern.
http://c2.com/cgi/wiki?DoubleDispatchExample
The above example explains how a group of printers can print a group of shapes.
http://en.wikipedia.org/wiki/Double_dispatch
The wikipedia example specifically mentions solving adaptive collision problems with this pattern.