Decorator pattern, Head First Design Patterns - decorator

I am reading the Head First Design Patterns book. In Chapter 3 ("Decorating Objects: The Decorator Pattern"), I do not understand this part:
"Wouldn’t it be easy for some
client of a beverage to end up with
a decorator that isn’t the outermost
decorator? Like if I had a DarkRoast with
Mocha, Soy, and Whip, it would be easy
to write code that somehow ended up
with a reference to Soy instead of Whip,
which means it would not include Whip in
the order."
Could someone please help me understand the main point of this section, and what the main issue was that the authors were addressing?

I think what they wanted to point out, is the fact that you can get your references mixed up if you are not careful where and how you create your decorated objects. Consider the example on page 98 (first edition from 2004).
Beverage beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
If you would do stuff in between those steps of creation, you might end up with a Mocha without Whip.
And like they wrote in the answer section:
However, decorators are typically created by using other patterns like Factory and Builder.
If you automate your object creation, it might prevent you from making reference errors.

Related

Kotlin arrow-kt Flatten nested Either

I'm programming using the functional library arrow-kt (formerly known as kategory). I'm using Either monad to aggregate errors or success information of an api call. I got myself into a state (which shouldn't happen in the first place) in which I have a nestet Either monads. I'm trying to flatten the structure to get the inner monad. The documentation is very limited and I couldn't find a way to do It.
Here's an example of a nested Either monad that I would like to flatten:
Either.right(Either.right(Either.left("error")))
You may flatten such a structure with flatten:
import arrow.core.*
import arrow.typeclasses.*
val result = Either.right(Either.right(Either.left("error")))
Either.monad<String>().flatten(result)
// keep flattening until you are happy with the result
// Right(b=Left(a=error))
Or just flatMap:
import arrow.core.*
import arrow.typeclasses.*
val result = Either.right(Either.right(Either.left("error")))
result.flatMap { it.flatMap { it } }
// Left(a=error)
The fact that you ended up with such nested structure probably means that you are not using the right datatype or wrong abstraction at some point in your program as that is kind of a useless value.
If you wish to preserve the left values as indicated in your comment I think a more suitable datatype would be Validated which allows for error accumulation as demonstrated here http://arrow-kt.io/docs/datatypes/validated/
Alternatively Either#fold can help you contemplate both cases and coalesce then into whatever value you wish.
I'm assuming you already run into these where most of this stuff is explained but just in case some useful links that will help you model this with Arrow
Docs: http://arrow-kt.io/docs/datatypes/either/
Video: https://www.youtube.com/watch?v=q6HpChSq-xc
FP Error handling with Arrow: http://arrow-kt.io/docs/patterns/error_handling/
Additionally feel free to swing by our chat channels if you need a more interactive experience with the maintainers and other contributors than SO where we frequently help people of all levels learning FP and Arrow.
Gitter: https://gitter.im/arrow-kt/Lobby
Slack: https://kotlinlang.slack.com/messages/C5UPMM0A0
Cheers!

Elixir - Changing Behavior

This is mostly a Functional Programming question rather than an Elixir one, but since I'm learning Elixir it would be nice if someone can answer it using that language. Even so, if someone wants to give a more general answer it'll be appreciated.
I'm an OO programmer myself and I can't wrap my head around how to change the behavior of a component based on a configuration file (for example).
Example:
I have an application that loads/saves users from a database. In a production environment, I want my users to be saved and retrieved from a MongoDB database, while in development and testing I want to use an in-memory map. If I was programming given system in an OO language (Lets say Java), I would simply make an Interface named "UserRepository" with 2 implementations: "MemoryUserRepository" and "MongoDBUserRepository". I would then instantiate the corresponding Repository based on a configuration file (or hardcoding it, it doesn't matter) at startup and right after it, all the objects that interact with the Repository will never know its implementation (they will use a repository, but will never care if it's in memory or in mongo).
That gives me the ability to create as many implementations as I want and the only thing I need to do to change the behavior of the system is instantiate the implementation that I want to use.
I want the same behavior but in Elixir (let's use the same example). Since it's not an Object Oriented language I can't use the above approach. Obviously I want it to be extensible (I could easily pass a String with the type of repository I want to use in each call and use pattern matching to determine what behavior to use, but that doesn't scale well because every time I'll want to add an implementation I will have to look in every piece of code I'm pattern matching the type and add the new implementation). What would be the best approach to achieve this?
Thanks in advance!
Suppose you have these two (or more) repository implementations, which implement the same interface:
defmodule MyApp.Repository.Memory do
def get(key) do
# ...
end
def put(key, value) do
# ...
end
end
defmodule MyApp.Repository.Disk do
def get(key) do
# ...
end
def put(key, value) do
# ...
end
end
Then you can write a general repository module that will just forward the function calls to one of the repository backends, based on a configuration value in your config/config.exs file:
defmodule MyApp.Repository do
#backend Application.get_env(:my_app, :repository_backend)
defdelegate [get(key), put(key, value)], to: #backend
end
The configuration can be made so that it is environment specific (just look at the default config.exs in a mix project freshly created with mix new my_app):
# config/config.exs
import_config "#{Mix.env}.exs"
# config/dev.exs
config :my_app, repository_backend: MyApp.Repository.Memory
# config/prod.exs
config :my_app, repository_backend: MyApp.Repository.Disk
Throughout your entire code, you can then just use the MyApp.Repository module without explicitly referencing one of the specific implementations:
MyApp.Repository.put(:foo, "Hello world!")
value = MyApp.Repository.get(:foo)

Box2D - b2Fixture touching

I have a question about b2Fixture. I have a body with multiple fixtures (polygons). In my picture you can see a body with multiple fixtures for example. The line in the middle of the body should represent a point. My question is how can i figure out which fixtures are on which site, including the fixtures which are connected.
My first throught was to loop through all vertices of each fixture and find out where the current vertex are located from the line (left or right?).
But this doesn't work because the fixtures on right side can connected with other fixtures which are overlap over the line like here in the image.
So is there a way to find out which fixture are connected with other fixtures? Or can i order the fixtures from left to right?
Hope anyone understand me. And sorry for the bad images (:
Thank you in advance.
Greetings alex
My advice would be to keep track of the fixtures during construction. You have to create these fixtures at some point, right? Because you didn't tag any specific version of box2d I'll assume you're using the c++ version.
box2d allows you to SetUserData for the fixture. If you are not already using the userData then you can use this to refer to an object that stores the fixture's neighbors. A simple structure might look like this:
struct FixtureNeighbors
{
b2Fixture* leftNeighbor;
b2Fixture* rightNeighbor;
};
During construction of the fixtures, you should create a FixtureNeighbors object, cast it as a void*, and call b2Fixture::SetUserData. Then, during the game, whenever you want to find out who a fixture's neighbors are just call b2Fixture::GetUserData, cast the result back to a fixtureNeighbors object, and use that to access the left and right neighbors.
Notes
If you are already using the fixture userData to point to an entity or something else, you should add a GetEntity method to your FixtureNeighbors structure and you can still access the entity if you have the fixture.
If a fixture can be touching more than two neighbors, just use an stl vector to store a list of them.
I hope this helps!

How can I tell the Closure Compiler not to rename an inner function using SIMPLE_OPTIMIZATIONS?

How can I tell the Closure Compiler not to rename an inner function? E.g., given this code:
function aMeaninglessName() {
function someMeaningfulName() {
}
return someMeaningfulName;
}
...I'm fine with Closure renaming the outer function (I actively want it to, to save space), but I want the function name someMeaningfulName left alone (so that the name shown in call stacks for it is "someMeaningfulName", not "a" or whatever). This despite the fact that the code calling it will be doing so via the reference returned by the factory function, not by the name in the code. E.g., this is purely for debugging support.
Note that I want the function to have that actual name, not be anonymous and assigned to some property using that name, so for instance this is not a duplicate of this other question.
This somewhat obscure use case doesn't seem to be covered by either the externs or exports functionality. (I was kind of hoping there'd be some annotation I could throw at it.) But I'm no Closure Compiler guru, I'm hoping some of you are. Naturally, if there's just no way to do that, that's an acceptable answer.
(The use case is a library that creates functions in response to calls into it. I want to provide a version of the library that's been pre-compressed by Closure with SIMPLE_OPTIMIZATIONS, but if someone is using that copy of the library with their own uncompressed code and single-stepping into the function in a debugger [or other similar operations], I want them to see the meaningful name. I could get around it with eval, or manually edit the compressed result [in fact, the context is sufficiently unique I could throw a sed script at it], but that's awkward and frankly takes us into "not worth bothering" territory, hence looking for a simple, low-maintenance way.)
There is no simple way to do this. You would have to create a custom subclass of the CodingConvention class to indicate that your methods are "local" externs (support for this was added to handle the Prototype library). It is possible that InlineVariables, InlineFunctions, or RemoveUsedVariables will still try to remove the name and would also need to be fixed up.
Another approach is to use the source maps to remap the stack traces to the original source.
read the following section
https://developers.google.com/closure/compiler/docs/api-tutorial3#export
Two options basically, use object['functionName'] = obj.functionName or the better way
use exportSymbol and exportProperty both on the goog object, here is the docs link for that
http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html
-- edit
ah, i see now, my first answer is not so great for you. The compiler has some interesting flags, the one which might interest you is DEBUG, which you can pass variables into the compiler which will allow you to drop some debugging annotations in via logging or just a string which does nothing since you are using simple mode.
so if you are using closure you can debug against a development version which is just a page built with dependiencies resolved. we also the drop the following in our code
if(DEBUG){
logger.info('pack.age.info.prototype.func');
}

Law of Demeter and OOP confusion

I've been doing some reading recently and have encountered the Law of Demeter. Now some of what I've read makes perfect sense e.g. the paperboy should never be able to rifle through a customers pocket, grab the wallet and take the money out. The wallet is something the customer should have control of, not the paperboy.
What throws me about the law, maybe I'm just misunderstanding the whole thing, is that stringing properties together with a heirarchy of functionality/information can be so useful. e.g. .NETs HTTPContext class.
Wouldn't code such as :
If DataTable.Columns.Count >= 0 Then
DataTable.Columns(0).Caption = "Something"
End If
Or
Dim strUserPlatform as string = HttpContext.Current.Request.Browser.Platform.ToString()
Or
If NewTerm.StartDate >= NewTerm.AcademicYear.StartDate And
NewTerm.EndDate <= NewTerm.AcademicYear.EndDate Then
' Valid, subject to further tests.
Else
' Not valid.
End If
be breaking this law? I thought (perhaps mistakenly) the point of OOP was in part to provide access to related classes in a nice heirarchical structure.
I like, for example, the idea of referencing a utility toolkit that can be used by page classes to avoid repetitive tasks, such as sending emails and encapsulating useful string methods:
Dim strUserInput As String = "London, Paris, New York"
For Each strSearchTerm In Tools.StringManipulation.GetListOfString(strUserInput, ",")
Dim ThisItem As New SearchTerm
ThisItem.Text = strSearchTerm
Next
Any clarity would be great...at the moment I can't reconcile how the law seems to banish stringing properties and methods together...it seems strange to me that so much power should be disregarded? I'm pretty new to OOP as some of you might have guessed, so please go easy :)
What the Law of Demeter (also "Law of Demeter for Functions/Methods") wants to reduce with saying "only use one dot" is that in a method you shouldn't have to assume such a lot of context from the provided arguments. This increases the dependency of the class and makes it less testable.
It doesn't mean that you can't use all of the above examples but it suggests that instead of giving your method the customer which then accesses the wallet and retrieves the money from it:
function getPayment(Customer customer)
{
Money payment = customer.leftpocket.getWallet().getPayment(100);
...
// do stuff with the payment
}
that you instead only pass what the paperboy needs to the method and as such reduce the dependency for the method if it's possible:
function getPayment(Money money)
{
// do stuff with the payment
}
Your benefit from it will be that you dont depend on the customer to have the wallet in the left pocket but instead just process the money the customer gives you. It's a decision you have to base on your individual case though. Less dependencies allow you to test easier.
I think applying the Law of Demeter to individual classes is taking it a bit too far. I think a better application is to apply it to layers in your code. For example, your business logic layer shouldn't need to access anything about the HTTP context, and your data access layer shouldn't need to access anything in the presentation layer.
Yes, it's usually good practice to design the interface of your object so that you don't have to do tons of property chaining, but imagine the hideously complex interface you'd have if you tried to do that to the DataTable and HttpContext classes you gave as examples.
The law doesn't say that you shouldn't have access to any information at all in a class, but that you should only have access to information in a way that you can't easily misuse it.
You can for example not add columns in a data table by assigning anything to the Count property:
DataTable.Columns.Count = 42;
Instead you use the Add method of the Columns object that lets you add a column in a way that all the needed information about the column is there, and also so that the data table get set up with data for that column.

Resources