CSC/ECE 517 Summer 2008/wiki3 1 PF: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(75 intermediate revisions by 2 users not shown)
Line 8: Line 8:
objects.
objects.
== Introduction ==
== Introduction ==
One of the beloved features of '''[http://www.ruby-lang.org/en/ Ruby]''' is the block based '''[http://en.wikipedia.org/wiki/Iterator Iterator]'''. A Ruby Iterator is simply a method that loops over the contents of an object without exposing its underlying representation.
Programming all code by a [http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 design pattern] can make the code more readable and easy to manipulate in the future. What do you do when you don't have any patterns that actually work in the design? A pure fabrication is a class that does not represent a concept in the problem domain. It is specially made up to achieve low coupling, high cohesion, and the reuse potential only if needed. So in code where you need to put something in and you can't come up with a pattern to match it, it may be time to just write the code and worry about a perfect solution later.
The verb 'iterate' means "do the same thing many times' so 'iterator' means "one which does the same thing many times". It can also be considered as an object that behaves like a ''[http://www.faqs.org/docs/learnc/x658.html generic pointer]''. The iterator usually references to one particular element in the object collection and then modifies itself so that it points to the next element. '''[http://en.wikipedia.org/wiki/Generator_%28computer_science%29 Generators]''' are a similar feature in '''[http://www.python.org/ Python]'''. The name came as it is the entity which generate iterators. It allows you to write a function that can return a result and pause, resuming in the same place the next time you call the function. The generator feature in Ruby can be implemented by adding a library class called Generator or external iterator. In python the generator is a feature and part of the language.
===Problem Definition===
Ruby, like Java, has iterators to facilitate doing operations on each member of a set. Python has generators as well. Describe how generators differ from iterators, and find examples of code sequences using generators that would be awkward with iterators.


== Iterator ==
Strictly speaking, [http://davidhayden.com/blog/dave/archive/2005/09/18/2476.aspx Pure Fabrication] is more of a design strategy than a design pattern. It helps designers create flexible solutions to a problem, and isolate changes to a subset of objects in applications to preserve the low-coupling and high cohesion of classes in design and to increase software maintainability.  
The word "iterator" means different things in different contexts and programming languages, but it's always got something to do with visiting each one of a set of objects, where "object" doesn't necessarily mean "class instance": Just take "object" to mean "some instance of some data type, somewhere". Iterators may provide additional features and may behave in a different way depending on the languages.


===Implementing Iterator===
=== Why pure fabrication? ===
Most of the ''[http://en.wikipedia.org/wiki/Object-oriented_programming OOP]'' languages provide ways to make iterations easy, for example some languages provide class for controlling iteration, etc. But Ruby allows the definition of control structures directly. In terms of Ruby, such user-defined control structures are called iterators.
We do not want our clients to know the fine grained entities to the client, so we'll have to provide a high level view to them. To achieve this, we do not want to change the interface of the entity. Therefore, to solve this problem, we can provide an additional element that provides a distributable view to the system. It also facilitates the co-ordination of the business entities, so that they still remain independent of each other. This approach is called "Pure Fabrication", because, from the business point of view, an insignificant class was introduced to decouple the client from the business objects.


====Iterator in Ruby====
* Pure fabrication is used when an operation does not conceptually belong to any object. For example, a class is not conceptually related to relational database, but it may be used to manage the database. Following the natural contours of the problem, you can implement these operations in services. It is known as "Pure Fabrication" in GRASP.
Iterator in Ruby is simply a method that invokes a block of code. The power is in the code block between the do and end keywords or {...}. Meaning, we can put as much, or little, code in there as needed. And each item being iterated over is passed into the block as a parameter between the pipes.  Examples of different iterators are given below.


=====Using Each [http://www.math.hokudai.ac.jp/~gotoken/ruby/ruby-uguide/uguide09.html]=====
* Pure fabrication can be thought of assigning a highly cohesive set of responsibilities to an artificial class.


a = [ 1, 2, 3 ]
* The controller, in a MVC architecture can be viewed as an elegant example of pure fabrication pattern.
a.each { |x| print x }
==>123
#The internal implementation of the Array.each method could be defined internally like this:
# def each
# for i in 0...size
#  yield(self[i])
#  end
#  end
 
x is the local variable in which each value of a is stored. And, each is probably the simplest iterator which yield successive elements of its collection.The above two line code is translated into C.


#include<stdio.h>
==How would you classify it ==
main()
Pure Fabrication is classified as one of the nine [http://davidhayden.com/blog/dave/archive/2005/09/18/2476.aspx GRASP Patterns] that help aid developers in assigning responsibilities to objects in your web applications and winform applications. [http://en.wikipedia.org/wiki/Factory_method_pattern Factories] are very similar to pure fabrication; they help with object persistence and object creation. They delegate object reconstitution and creation to specialized classes so domain objects are mere data containers and behaviors that act on that data. Most code is created for a specific application. Plug-in and refactoring can help redesign code to be used in the next generation. At some point when your developing code you may decide that the life cycle of the code is short and so you develop code for short term. Following patterns can help make your code more reusable and readable but in some situations writing code for just that application where it doesn't follow any pattern is the best choice
{
  int s[3]={1,2,3};
  int i=0;
  while(i<3)
  {
    printf("%d",s[i]);
    i++;
  }
}
==>123
 


The advantage of the block-passing style is that generators are a lot more built-in to the language. For example, the below two codes are equivalent and in neither of those cases is an array instantiated with all members of the range (X..Y):
===Suggestion of where to use pure fabrication===
  1.upto(100000).each {|x| puts x}
Sometimes you may be ask to modify code that hasn't been developed well or you will need to [http://en.wikipedia.org/wiki/Refactoring refactor] the code to make it useful. In this situation you may just want to write a coupler that allows the code to go between the new code and the old. This would allow you to finish the job and help prevent a complete rewrite of the old code. The coupler would be considered pure fabrication because it will never be used again.


  for i in 1..100000
[[Image:PureFab.gif]]
  puts i
* Example 1 -Let us consider another example of saving sale instances in a database. According to [http://davidhayden.com/blog/dave/archive/2005/03/28/903.aspx Expert Pattern], we need to assign this responsibility to Sales. However, there are a large number of database operations performed. In this case, we are coupling our application to the database. Also, saving objects in a database is a common task; therefore, many classes need to know how to work with the database. Also, there is low cohesion because the Sales class performs more than one function.
  end
[[Image:LowCohesion.gif]]


=====Using Find [http://www.nickpeters.net/2008/01/09/ruby-iterators/]=====
One of the easy solution is to create a class that is solely responsible for saving objects in the database. Let us name this class as SalesStorage. It will take care of the insert, update, delete etc. operations. It encapsulates the database from the clients, by providing them coarse view of database operations. Also, it facilitates co-ordination among different databases. The PersistentManager class is itself relatively cohesive and has the sole purpose of managing and storing objects. It is a generic and reusable object and a good example of pure fabrication.


a = [ 10,20,30 ]
[[Image:SalesStorage.gif]]
a.find { |n| n % 5 == 0 }
==>10
The find iterator method in ruby will compare each element using some comparison operator (<, >, ==, etc.) and based on the boolean result (true or false), it will return the first matching value.


=====Using Collect [http://www.nickpeters.net/2008/01/09/ruby-iterators/]=====
== Where not to use pure fabrication ==
1. Pure fabrication should be used only when necessary. It should not be overused as in general, its not a good thing to separate behavior from the relevant information. In case of the above example of sales instances, sale could use another fabricated class to add a line item: SalesLineItemAdder. But that increases the complexity of the system. It also increases coupling as it leads to a class that knows things (the Sale) and another class that does things with that knowledge (SalesLineItemAdder).


a = [ 1, 2, 3, 4, 5 ]
2. Also, pure fabrication violates a basic OO principle "Do not talk to strangers". So in places where maintaining data and is crucial pure fabrication should not be used.
b = a.collect { |n| n + 1 }
  ==>[2, 3, 4, 5, 6]
Another common iterator is the collect that returns an array of elements that is taken from the corresponding collections.
Iterator can return derived values and not only limited to accessing the data stored in arrays and hashes.


====Iterator in Python====
=Conclusion=
Python also supports iteration over containers. It is implicitly used in the for statement, in ''[http://en.wikipedia.org/wiki/List_comprehension list comprehensions]'', and in ''[http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generator_expressions generator expressions]''. An iteration protocol is defined so that iteration is possible over different objects. Most of the container objects can be looped over using for statement. Example of a typical implicit iteration over a sequence is given below [http://docs.python.org/tut/node11.html#SECTION0011900000000000000000].
Sometimes its better to develop something that works better in your code but isn't a perfect pattern. The Pure Fabrication Pattern is where you add classes into your application to create [http://en.wikipedia.org/wiki/GRASP_(Object_Oriented_Design)#High_Cohesion high cohesion] and [http://en.wikipedia.org/wiki/GRASP_(Object_Oriented_Design)#Low_Coupling low coupling]. Today with code changing at a rapid pace it may be easier to design something one time and redesign it or refactor it later. We need to remember to let Design Patterns emerge, don't force them in
for element in [1, 2, 3]:
just for the sake of using a pattern. Always use the simplest solution that meets your needs, even if it doesn't include a pattern.
    print element
The actual internal implementation is that the for statement calls iter() on the container object. The function returns an iterator object that defines the method next(). The method next() then returns the next item one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate.
Iterators can also be defined explicitly. An example using explicit iterators is given below [http://en.wikipedia.org/wiki/Iterator#Python]


it = iter(sequence)
while True:
    try:
        value = it.next()
    except StopIteration:
        break
    print value


Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The iterator object just have to implement __iter()__ and next().  Ruby iterator has an advantage over Python as it supports code blocks as objects where as Python can use only the for loop for iteration.
===Uses===
# The main use of iterator is it hides the internal details from the user when manipulating with the objects.
# Iterator is trivially more cleaner and elegant which makes it more easy to maintain compared to the accessing of elements based on ''[http://en.wikipedia.org/wiki/Index_%28information_technology%29 indexing]''.
# Iterators follow a consistent way of iterating through all kinds of data structures, as a result it becomes more readable and reusable.
# Using Iterators, inserting of a new element into the container object is easy even after the iterator has advanced beyond the first element. On the other hand, it is more difficult when using indexing as it requires changing of index numbers.
== Generators ==
A generator looks like a function but behaves like an iterator. Both Ruby and Python support generators. As mentioned in the introduction, Ruby has a Generator library and Python has generator as a fundamental part of the language. As being a language feature it is more robust and syntactically more concise and cleaner. On the other hand, using a library class helps to learn a language more easily and more elegant with the less number of features.
=== Generators in Python===
Generators are a simple and powerful tool for creating iterators. They are written like regular functions and called only once. It then returns an iterator which is the actual iterator with _iter()_ and next() methods. Generator doesn't have to worry about the iterator protocol (__iter()__,.next()..), it just works. Yield statement is used whenever they want to return data. Each time next() is called, the generator resumes where it left-off (it remembers all the data values and which statement was last executed). The generator function does NOT run to completion when it's first called - instead, it only runs until it has a value available to return, at which point it yields that value back and suspends operation until called again to resume.
This is described with an example below [http://www.builderau.com.au/program/python/soa/Lazy-list-builders-Generators-in-Python/0,2000064084,339279708,00.htm].
>>> def generator1():
...    yield "first"
...    yield "second"
...    yield "third"
>>> gen = generator1()
>>> gen
>>>            #No output was produced.
>>> gen.next()
    'first'    #Function starts executing here.
>>> gen.next()
    'second'
>>> gen.next()
    'third'
>>> gen.next()
    Traceback (most recent call last):
    File "", line 1, in ?
    StopIteration
First, a generator called generator1 is defined which will yield three values, the strings "first", "second" and "third". When we create a new generator object (gen) it begins the function. Each time you call the generator's next method, it continues the function until the next yield. When the generator reaches the end of the block, or reaches a return statement, it throws a StopIteration exception.
A generator is a one time operation. So, the generated data is iterated only once but one can call the generated function again if needed. In this way, ''[http://en.wikipedia.org/wiki/Lazy_evaluation Lazy evaluation]'' can be achieved which increases the performance by eliminating unnecessary calculation of values that are never used.
Generator can be more powerful as Python has now included the ability to return the data the generator. For example :
x= yield y
From the perspective of the caller of the generator, this statement returns control back to the caller, just as before. From the perspective of the generator, when the execution comes back into the generator, a value will come with it. In this case, the generator saves it into the variable x. The value comes when the caller calls a function called send() to pass a value back into the generator. The function send() behaves just like the function next(), except that it passes a value. This is explained with an example below.
 
class MyStuff:
  def __init__(self):
  self.a = [2,4,6,8,10,12]
  def iterate(self):
  i = 0
  while i < len(self.a):
  val = yield self.a[i]
  if val == None:
  i += 1
  else:
  if val < 0:
  val = 0
  if val >= len(self.a):
  val = len(self.a) -1
  i = val
Here, send() is used to let the caller of the generator reposition the index in the array. Value received is checked whether it is within the bounds of the array, else the closest boundary is set. The value generator received is tested and stored in 'val'.If val is None, that means the generator received no value (the calling code used next(), or perhaps send(None)).
=== Generators in Ruby===
Some of the reason's why Generator library comes into play where external iterators are implemented are mentioned below.
*The internal iterator in Ruby would fail if the iterator is required to pass through a method that needs access on each of the values returned by that iterator.
*Iterators cannot iterate over more than one collection at a time, they cannot be paused or stopped in the middle.
*They can only implement a single traversal strategy.
Example with the library to iterate over a block is given below [http://www.ruby-doc.org/docs/ProgrammingRuby/].
require 'generator'
gen = Generator.new do |result|
result.yield " Start"
3.times { |i| result.yield i}
result.yield "done"
end
while gen.next?
print gen.next,"--"
end
==> Start--0--1--2--done--
==An example to print the successive elements from 10 to 20 in ruby and python ==
===Using generator in Python===
def countfrom(n):
    while True:
        yield n
        n += 1
for i in countfrom(10):
    if i <= 20:
        print i
    else:
        break
==>10,11,12,13,14,15,16,17,18,19,20
===Using iterators in Ruby===
(10..20).each { |i| print i,","  }
==>10,11,12,13,14,15,16,17,18,19,20
This above example shows how iterators in Ruby are not very elegant.
===Using generator in Ruby===
require 'generator'
gen = Generator.new(10..20)
while gen.next?
  print gen.next, ", "
end
==>10,11,12,13,14,15,16,17,18,19,20
With Ruby generators the code flows similar to Python.
==Comparisons of Ruby generators and Python generators ==
Python was intended to be a highly readable language.Ruby can be a highly readable language with the use of external iterators. Ruby's internal iterators aren't always the best solution. Adding the generator or external iterators function helps get over the difficulty of  writing the code and helps with the readability. This sort of makes Ruby like a highly readable language like Python. Ruby's code however runs slower than many compiled languages and other major scripting languages such as Python. 
===examples of code sequences that would be awkward ===
==See Also==
* '''[http://www.ruby-lang.org/en/ Ruby]'''
==External links==
==External links==
*[http://www.ruby-doc.org/docs/ProgrammingRuby/ Programming Ruby The Pragmatic Programmer's Guide]
*[http://davidhayden.com/blog/dave/archive/2005/09/18/2476.aspx Grasp Pattern]
 
*[http://codebetter.com/blogs/david.hayden/archive/2006/08/26/Over_2D00_Architecting-Via-Pure-Fabrication-and-Indirection-to-Reduce-Coupling.aspx Over-Architecting Via Pure Fabrication]
*[http://en.wikipedia.org/wiki/GRASP_(Object_Oriented_Design)#Pure_Fabrication  Grasp OOD]
*[http://web.njit.edu/~gblank/cis683/Larman%20Chapter%2025.ppt GRASP Pure Fabrication]
*[http://www.ibm.com/developerworks/rational/library/jun07/cuellar/ the case for High Cohesion and low coupling]
*[http://ai.ee.ccu.edu.tw/oose/Fall05/notes/sec-Ch05.pdf Pattern oriented software development]
*[http://alcor.concordia.ca/~smw/comp354/L22web-2x2.pdf Pure Fabrication Notes]
*[http://www.christmann.ws/ucis342/class9/class9.html Object Oriented Analysis and Logical design]
*[http://www.mindspring.com/~mgrand/pattern_synopses2.htm Software Pattern Synopses]
* Book - Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development


[[CSC/ECE 517 Summer 2008/wiki1 Assignment|Back to the assignment page]]
[[CSC/ECE 517 Summer 2008/wiki3 Assignment|Back to the assignment page]]

Latest revision as of 02:01, 1 August 2008

Pure fabrication

Sometimes it is a good idea to introduce into a system an object that has no counterpart in the real world. This is called the pure fabrication pattern. Find examples of pure fabrication, and weave them into a narrative that can teach programmers when it is helpful and when it is not helpful to fabricate objects.

Introduction

Programming all code by a design pattern can make the code more readable and easy to manipulate in the future. What do you do when you don't have any patterns that actually work in the design? A pure fabrication is a class that does not represent a concept in the problem domain. It is specially made up to achieve low coupling, high cohesion, and the reuse potential only if needed. So in code where you need to put something in and you can't come up with a pattern to match it, it may be time to just write the code and worry about a perfect solution later.

Strictly speaking, Pure Fabrication is more of a design strategy than a design pattern. It helps designers create flexible solutions to a problem, and isolate changes to a subset of objects in applications to preserve the low-coupling and high cohesion of classes in design and to increase software maintainability.

Why pure fabrication?

We do not want our clients to know the fine grained entities to the client, so we'll have to provide a high level view to them. To achieve this, we do not want to change the interface of the entity. Therefore, to solve this problem, we can provide an additional element that provides a distributable view to the system. It also facilitates the co-ordination of the business entities, so that they still remain independent of each other. This approach is called "Pure Fabrication", because, from the business point of view, an insignificant class was introduced to decouple the client from the business objects.

  • Pure fabrication is used when an operation does not conceptually belong to any object. For example, a class is not conceptually related to relational database, but it may be used to manage the database. Following the natural contours of the problem, you can implement these operations in services. It is known as "Pure Fabrication" in GRASP.
  • Pure fabrication can be thought of assigning a highly cohesive set of responsibilities to an artificial class.
  • The controller, in a MVC architecture can be viewed as an elegant example of pure fabrication pattern.

How would you classify it

Pure Fabrication is classified as one of the nine GRASP Patterns that help aid developers in assigning responsibilities to objects in your web applications and winform applications. Factories are very similar to pure fabrication; they help with object persistence and object creation. They delegate object reconstitution and creation to specialized classes so domain objects are mere data containers and behaviors that act on that data. Most code is created for a specific application. Plug-in and refactoring can help redesign code to be used in the next generation. At some point when your developing code you may decide that the life cycle of the code is short and so you develop code for short term. Following patterns can help make your code more reusable and readable but in some situations writing code for just that application where it doesn't follow any pattern is the best choice

Suggestion of where to use pure fabrication

Sometimes you may be ask to modify code that hasn't been developed well or you will need to refactor the code to make it useful. In this situation you may just want to write a coupler that allows the code to go between the new code and the old. This would allow you to finish the job and help prevent a complete rewrite of the old code. The coupler would be considered pure fabrication because it will never be used again.

  • Example 1 -Let us consider another example of saving sale instances in a database. According to Expert Pattern, we need to assign this responsibility to Sales. However, there are a large number of database operations performed. In this case, we are coupling our application to the database. Also, saving objects in a database is a common task; therefore, many classes need to know how to work with the database. Also, there is low cohesion because the Sales class performs more than one function.

One of the easy solution is to create a class that is solely responsible for saving objects in the database. Let us name this class as SalesStorage. It will take care of the insert, update, delete etc. operations. It encapsulates the database from the clients, by providing them coarse view of database operations. Also, it facilitates co-ordination among different databases. The PersistentManager class is itself relatively cohesive and has the sole purpose of managing and storing objects. It is a generic and reusable object and a good example of pure fabrication.

Where not to use pure fabrication

1. Pure fabrication should be used only when necessary. It should not be overused as in general, its not a good thing to separate behavior from the relevant information. In case of the above example of sales instances, sale could use another fabricated class to add a line item: SalesLineItemAdder. But that increases the complexity of the system. It also increases coupling as it leads to a class that knows things (the Sale) and another class that does things with that knowledge (SalesLineItemAdder).

2. Also, pure fabrication violates a basic OO principle "Do not talk to strangers". So in places where maintaining data and is crucial pure fabrication should not be used.

Conclusion

Sometimes its better to develop something that works better in your code but isn't a perfect pattern. The Pure Fabrication Pattern is where you add classes into your application to create high cohesion and low coupling. Today with code changing at a rapid pace it may be easier to design something one time and redesign it or refactor it later. We need to remember to let Design Patterns emerge, don't force them in just for the sake of using a pattern. Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


External links

Back to the assignment page