Smalltalk equivalent of a factory method? - factory

Are factory methods used in Smalltalk, and if so, how should one go about writing one, as opposed to how they would in Java, for example?
Thanks.

In a factory pattern we instantiate some subclass without naming it. Consider a pizza factory and hierarchy:
Pizza
PepperoniPizza
CheesePizza
...
We'd like instantiate a pizza subclass without knowing it's class name. For example:
pizza := Pizza flavor: 'cheese' size: 12 inches
answers the right subclass of pizza, with it's size filled in.
Now in Java or C++ one would probably do a large 'switch' statement to compare on different string names. Each time we added a new subclass of Pizza, we'd need to remember to add to the master switch statement. See Wikipedia article for typical examples.
Not so in Smalltalk, where classes are first class objects, so we can iterate down the class hierarchy, asking each subclasses to match. For example:
Pizza class>>flavor: aString size: anInteger
matchingClass := self subclasses detect: [:first | first matching: aString].
^matchingClass new size: anInteger.
And whenever we implement a new subclass of pizza, we implement one method to do the factory matching:
CheesePizza class>>matching: aString
^aString = 'cheese'
PepperoniPizza class>>matching: aString
^aString = 'pepperoni'
No central switch statement to maintain. Just objects!

First of all, in Smalltalk you have named constructors. In fact, classes are objects and "constructors" are just methods defined on the class that happen to return new instances. Many uses of factory methods in other languages can be covered that way.
For example
Thing class >> withName: aString
^ dictionaryOfAllThings
at: aString
ifAbsentPut: (self new name: aString; yourself)
which get a thing by name, and only creates a new thing if a thing with that name does not yet exist.

Related

Trying to understand what a Method is, how can it be 'part of a class'?

I've done some work with functions in Javascript, and thought that a Method was the Ruby name for the same. I recently did a technical interview and the interviewer was trying to help me debug by explaining how Methods were part of a class, and that it's an OOP thing.
I can't spot a functional difference between a Method and an equivalent Function, so I don't see what classes have to do with it.
Can you explain the whole 'Methods are part of a class' thing and why it matters? How can a Method be part of a class? Class as in an integer or a string?
The interviewer believed it would help, but it seems like a tiny technicality more than something useful.
Can you explain the whole 'Methods are part of a class' thing and why it matters? How can a Method be part of a class? Class as in an integer or a string?
Let's say you have two classes, Apple and Cake. Let's assume that when you sell an apple, it has a tax rate of 10%, and cake 20%. By splitting the methods into individual classes, we can define a different method for 'price_with_tax' to each class:
class Apple < ApplicationRecord
def price_with_tax
self.price * 1.1
end
end
class Cake < ApplicationRecord
def price_with_tax
self.price * 1.2
end
end
In javascript we wouldn't be able to do this, and would need to have 2 methods, 'add 10% tax' and 'add 20% tax'. By structuring the methods as we have, we're able to do:
apple = Apple.find(1)
cake = Cake.find(1)
cake.price_with_tax
apple.price_with_tax
Methods are generally something that a class can do,
class MailClient(for example) might have methods such as sendMail, getMail, forwardMail, etc. In OOP, methods should for the most part be something that a class can do.
MailClient.getMail();
The above code can be conceptualized as telling the class to invoke its getMail() behavior.
You may think of this in real-life terms such as:
Dog.bark();
Objects have behavior and attributes, the behaviors are the methods.
In OOP:
Class is like a blueprint/template. It has properties, methods etc. An object can be created with it. So an object can call method in class.
Usually a method is created to perform an operation.
Example:
// a demo class
public class Animal{
// a method
public void sound(){
// do something...
}
// main class, we create an object and call sound() method
public static void main(String[] args){
Animal dog = new Animal(); // create an object so that we can use the method
dog.sound(); // method call
}
}

Reference to an instance method of a particular object breaks the type-safety in Java?

Does the notion of a reference to an instance method of a particular object break the type-safety in Java?
According to
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
you can have a custom class ComparisonProvider that DOES not implement the Comparator interface, and still use an instance of this class as the second argument of the method
Arrays.sort(T[] a, Comparator c)
Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?
In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.
This means, that we are loosing Type-safety in Java, do we?
lambda expressions and method reference don't have a predefined type, they are poly expressions, as seen here. That means that their type is derived from the context in which they are used.
In your example these both would be legal for example:
BiFunction<Person, Person, Integer> biFun = myComparisonProvider::compareByName;
Comparator<Person> comp = myComparisonProvider::compareByName;
But at the same time you can't do:
Arrays.sort(pers, biFun);
When you actually try to sort the array like this:
Arrays.sort(pers, myComparisonProvider::compareByName);
At the bytecode level that is a Comparator:
// InvokeDynamic #0:compare:(LTest$ComparisonProvider;)Ljava/util/Comparator;
Also notice that this would print true:
Comparator<Person> comp = myComparisonProvider::compareByName;
System.out.println(comp instanceof Comparator); // true
You can enable a flag : -Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here
and look at what that method reference is transformed into:
final class Test$$Lambda$1 implements java.util.Comparator
and inside it there's the compare method implementation(I've simplified it and removed some of it's code to make it a little more obvious):
public int compare(java.lang.Object, java.lang.Object);
Code:
4: aload_1
5: checkcast // class Test3$Person
8: aload_2
9: checkcast // class Test$Person
12: invokevirtual Test$ComparisonProvider.compareByName:(Test$Person;Test$Person;)I
Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not
Not exactly, it allows you to use a single method of some instance of a class as if it were implementing some functional interface.
And it doesn't add any functionality that didn't exist in Java 7 - it just gives you a short cut to writing that functionality.
For example, instead of:
Arrays.sort(someArray, someInstance::someMethod);
In Java 7 you could use anonymous class instance to write:
Arrays.sort(someArray, new Comparator<SomeType> () {
public int compare (SomeType one, SomeTypeTwo) {
return someInstance.someMethod(one,two);
}
});
As long as the instance method is accessible (i.e. public), you can use it as you see fit.
Comparator is a functional interface, which means that when requested you can pass an instance of a class implementing it, use a lambda expression that conforms to the type of single abstract method declared in it or use a method reference that also conforms to.
Java 8 Functional interface makes the difference. This tries to catch the concept of function. Afterall what is important in Comparator is not the type itself but the method (and its type) that should be provided at runtime. In pre Java 8 you need to provide a function object, while in Java 8 you can simply provide the function (just what is needed).
So for the type system everything is correct, provided that the lambdas or references you use are of the type of the method of the functional interface.

Pascal passing object of inheritance class to procedure

I have types declared as:
TPlayer = class(TObject)
TBullet = class(TObject)
TEnemy = class(TObject)
and objects:
Player: TPlayer;
PlayerBullets: Array[1..20] of TBullet;
Enemies: Array[1..20] of TEnemy;
EnemyBullets: Array[1..20] of TBullet;
Now I want to create TBullet constructor, which can process informations from both Player and Enemies. In short, I want this constructor to handle both TPlayer and TEnemy objects.
My idea is:
constructor TBullet.Create(const Source: TObject);
Sadly it does not work. How to do this?
EDIT:
My exact problem is: when I pass TPlayer or TEnemy object to this constructor it doesn't see atributes of those objects. For example: TPlayer has attr xPos. If I use Bullet.Create(Player) and in TBullet.Create I use Source.xPos I get an error.
I can think of 3 ways to achieve that.
Have TPlayer and TEnemy both derive from the same base class that have all the information TBullet's constructor need, and have the constructor parameter of that type.
Define an interface contains all the information needed by TBullet and have TPlayer and TEnemy implement that interface
Leave everything "as is" and manage the different class in a "hard coded" manner in TBullet's constructor.
By that I mean:
constructor TBullet.Create(const Source: TObject);
var
vPlayer : TPlayer;
vEnemy : TEnemy;
begin
if Source is TPlayer then
begin
vPlayer := TPlayer(Source);
[Do whatever with vPlayer]
end else if Source is TEnemy then
begin
vEnemy := TEnemy(Source);
[Do Whatever with vEnemy]
end;
end;
Which solution is the best? That could be a debate in itself and largely dependant on your specific situation. Based solely on the name of your class, I'd guess option 1 could be valid. A "TCharacter" class could be created and use as a base calss for both TCharacter and TEnemy. But this is mere speculation at this point.
In windows there is little difference in inheriting from a parent with the common methods (could be abstract in the parent ) or implementing an interface (when again the behavior could be customized ).
If you have an enumeration commonParticipant( cpPlayer, cpEnemy) then Windows allows access to the ultimate parent IUnknown and then down again to a child interface that identifies the methods peculiar to that child, i.e. you can pass an ICommonParticipant including the commonParticipant and then work with either a iPlayer or IEnemy interface

Walking Core Data graph to-many relationships always seems awkward, is there a better way?

I'm able to get things working fine with Core Data and to achieve my desired results, but I always feel it very awkward when walking to-many relationships because NSSet is, for my typical purposes, fairly useless.
An example is if I have obtained a NSManagedObject of Entity "Zoo" with attribute "nameOfZoo" and to-many relationship "animalCages", the to-many relationship pointing to Entity "AnimalCage" which has attribute "nameOfSpecies" and to-many relationship pointing to Entity "IndividualAnimal"
Zoo [nameOfZoo] ->> AnimalCage [nameOfSpecies] ->> Animals
So, getting the top level Zoo object, that's simple. But then I want to get the data for nameOfSpecies "Canus Lupus". The code I want to write is this:
// Normal NSEntityRequest or whichever it is, I have no gripe with this
NSManagedObject *zoo = ..the request to get the one Zoo..;
// I want to get the object where the key "nameOfSpecies" is set to "CanusLupus"
NSManagedObject *wolf = [[zoo animalCages] object:#"Canus Lupus" forKey:#"nameOfSpecies"];
Obviously, I can't obtain wolf in this manner. Instead, I have to write like 10 lines of code (feels like 100 lines of code) to first obtain the set, then set up a search predicate request, and declare an error variable, execute the request, then get an array of the results, then get the first element of that array.. and if I want to walk further down the tree, to find the animal named "Wolfy" for instance, then I have to do it all over again.
Am I doing things correctly or am I foolishly an easier way? I guess I can put a category on NSSet, maybe I will, but I feel like there should be a built in better way. If not, why?
If you have a data model like this:
Zoo{
name:string
animalCages<-->>AnimalCage.zoo
}
AnimalCage{
nameOfSpecies:string
zoo<<-->Zoo.animalCages
animals<-->>Animal.animalCage
}
Animal{
name:string
animalCage<<-->AnimalCage.animals
}
The to find a specific AnimalCage by name of species for a given Zoo object:
NSString *soughtSpecies=#"Canis Lupis"; // normally this variable would be passed in to the method
NSPredicate *p=[NSPredicate predicateWithFormat:#"nameOfSpecies==%#", soughtSpecies];
NSSet *wolves=[[zoo animalCages] filteredSetUsingPredicate:p];
Or you can use objectPassingTest: if you like blocks.
If you use custom NSManagedObject subclasses, then you get custom accessor methods and can use self.dot notation so the above would be:
Zoo *zoo= // fetch the appropriate zoo object
NSString *soughtSpecies=#"Canis Lupis";
NSPredicate *p=[NSPredicate predicateWithFormat:#"nameOfSpecies==%#", soughtSpecies];
NSSet *wolves=[zoo.animalCages filteredSetUsingPredicate:p];
If you know before hand that you are going to have to find cages a lot, you could wrap the above up in a method on your Zoo class e.g.
#implementation Zoo
//... other stuff
-(AnimalCage *) cageForSpecieNamed:(NSString *) specieName{
NSPredicate *p=[NSPredicate predicateWithFormat:#"nameOfSpecies==%#", specieName];
NSSet *wolves=[self.animalCages filteredSetUsingPredicate:p];
return [wolves anyObject]; // assuming one cage per species
}
Objective-c is intentionally verbose because it was supposed to be "self documenting" and the editor written for the language at the beginning had autocomplete. So, if your used to a more expressive language it might seem you are doing a lot of work but logically you aren't.

What's so great about Func<> delegate?

Sorry if this is basic but I was trying to pick up on .Net 3.5.
Question: Is there anything great about Func<> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc<> with the exact 5 overloads and even more.
eg: public delegate TResult MyFunc<TResult>() and a combo of various overloads...
The thought came up as I was trying to understand Func<> delegates and hit upon the following scenario:
Func<int,int> myDelegate = (y) => IsComposite(10);
This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?
So am I justified in saying that Func<> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func<>" delegates to suit our own needs?
Thanks,
The greatness lies in establishing shared language for better communication.
Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?'
So as soon as I see a
Action = some method that just does something and returns no output
Comparison = some method that compares two objects of the same type and returns an int to indicate order
Converter = transforms Obj A into equivalent Obj B
EventHandler = response/handler to an event raised by some object given some input in the form of an event argument
Func = some method that takes some parameters, computes something and returns a result
Predicate = evaluate input object against some criteria and return pass/fail status as bool
I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own.
Disclaimer: Personally I like this move by the language designers.
Counter-argument : Sometimes defining your delegate may help communicate intent better. e.g. System.Threading.ThreadStart over System.Action. So it’s a judgment call in the end.
The Func family of delegates (and their return-type-less cousins, Action) are not any greater than anything else you'd find in the .NET framework. They're just there for re-use so you don't have to redefine them. They have type parameters to keep things generic. E.g., a Func<T0,bool> is the same as a System.Predicate<T> delegate. They were originally designed for LINQ.
You should be able to just use the built-in Func delegate for any value-returning method that accepts up to 4 arguments instead of defining your own delegate for such a purpose unless you want the name to reflect your intention, which is cool.
Cases where you would absolutely need to define your delegate types include methods that accept more than 4 arguments, methods with out, ref, or params parameters, or recursive method signatures (e.g., delegate Foo Foo(Foo f)).
In addition to Marxidad's correct answer:
It's worth being aware of Func's related family, the Action delegates. Again, these are types overloaded by the number of type parameters, but declared to return void.
If you want to use Func/Action in a .NET 2.0 project but with a simple route to upgrading later on, you can cut and paste the declarations from my version comparison page. If you declare them in the System namespace then you'll be able to upgrade just by removing the declarations later - but then you won't be able to (easily) build the same code in .NET 3.5 without removing the declarations.
Decoupling dependencies and unholy tie-ups is one singular thing that makes it great. Everything else one can debate and claim to be doable in some home-grown way.
I've been refactoring slightly more complex system with an old and heavy lib and got blocked on not being able to break compile time dependency - because of the named delegate lurking on "the other side". All assembly loading and reflection didn't help - compiler would refuse to just cast a delegate() {...} to object and whatever you do to pacify it would fail on the other side.
Delegate type comparison which is structural at compile time turns nominal after that (loading, invoking). That may seem OK while you are thinking in terms of "my darling lib is going to be used forever and by everyone" but it doesn't scale to even slightly more complex systems. Fun<> templates bring a degree of structural equivalence back into the world of nominal typing . That's the aspect you can't achieve by rolling out your own.
Example - converting:
class Session (
public delegate string CleanBody(); // tying you up and you don't see it :-)
public static void Execute(string name, string q, CleanBody body) ...
to:
public static void Execute(string name, string q, Func<string> body)
Allows completely independent code to do reflection invocation like:
Type type = Type.GetType("Bla.Session, FooSessionDll", true);
MethodInfo methodInfo = type.GetMethod("Execute");
Func<string> d = delegate() { .....} // see Ma - no tie-ups :-)
Object [] params = { "foo", "bar", d};
methodInfo.Invoke("Trial Execution :-)", params);
Existing code doesn't notice the difference, new code doesn't get dependence - peace on Earth :-)
One thing I like about delegates is that they let me declare methods within methods like so, this is handy when you want to reuse a piece of code but you only need it within that method. Since the purpose here is to limit the scope as much as possible Func<> comes in handy.
For example:
string FormatName(string pFirstName, string pLastName) {
Func<string, string> MakeFirstUpper = (pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
};
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
It's even easier and more handy when you can use inference, which you can if you create a helper function like so:
Func<T, TReturn> Lambda<T, TReturn>(Func<T, TReturn> pFunc) {
return pFunc;
}
Now I can rewrite my function without the Func<>:
string FormatName(string pFirstName, string pLastName) {
var MakeFirstUpper = Lambda((string pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
});
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
Here's the code to test the method:
Console.WriteLine(FormatName("luis", "perez"));
Though it is an old thread I had to add that func<> and action<> also help us use covariance and contra variance.
http://msdn.microsoft.com/en-us/library/dd465122.aspx

Resources