azizkhani.net

I know that I know nothing

What is Refactoring?

clock May 17, 2013 20:57 by author Administrator

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

This is a simple list of refactorings both from the original book and some later sources. Refactorings marked with with have some extra material to what's in the Refactoring book. Refactorings marked with are in addition to those in the refactoring book. Refactorings with Link Only are references to refactorings described elsewhere.

 

 



kent beck new post

clock March 17, 2013 23:32 by author Administrator
  • point of the "code/code/fix/fix" vs "code/fix/code/fix" question wasn't which is "right", but identifying criteria to use when choosing;

 

  • when the first thing i want to do to address the complexity of a program is write a complexity analyzer, i've gone too inception. just clean;

 

  • they are both expensive, but mutable singletons are way worse than immutable singletons because they create temporal coupling;

 

  • if everyone agrees it's a problem, the fact that you've begun solving it is pretty much all the permission you need


Fluent Object Creation

clock January 23, 2013 22:02 by author Administrator
Many posts have been written on this subject (overwhelmingly many) but I just wanted to contribute my two-cents and write a short post about how I use the Fluent Object Creation pattern or object builders in Java to instantiate Value Objects.

 Value Objects are abstractions that are defined by their state (value) rather than their address in memory. Examples of value objects are things like money, a number, a coordinate, etc. They are used not to describe Business Objects but rather descriptions of concrete indivisible entities.  Also, they make great candidates for adding them to collections and maps.


In Java, Value Objects should be declared final and provide no setter methods, basically making it's state immutable after creation, this is a very important requirement. Declaring them final makes them unable to serve as parent objects. This is done by design since value objects should model small and concrete entities. The reason being is that we should be able to create and compare multiple copies of these objects, which is always done by state not by reference. In addition, you should declare proper equals() and hashCode() methods to qualify for a proper value object.

In C++, the same principles apply. In C++ you should make use of the Copy Constructor and overload the assignment and comparison operators.  

The Fluent Object Creation pattern makes value object instantiation elegant and clean. There are many benefits that can be gained by using fluent object creation as we will see shortly. 

 

 

 

The end result of applying this pattern from the API user's perspective will look like the following:

 


Money fiveEuros = new Money.Builder()
   .currency(Currency.EURO)
   .value(5.0L)
   .countryOfOrigin("Spain")
   .type("Coin")
   .reverse("Map of Europe")
   .obverse("Map of Spain")
   .addColor("Bronze")
   .addColor("Silver")
   .year("1880")
.build();


I think you would agree that this pattern flows a lot more smoother as opposed to this:


Money fiveEuros = new Money();
fiveEuros.setCurrency(Currency.EURO);
fiveEuros.setValue(5.0L);
fiveEuros.countryOfOrigin("Spain");
fiveEuros.type("Coin");
fiveEuros.reverse("Map of Europe");
fiveEuros.obverse("Map of Spain");
List<String> colors = new ArrayList<String>();
for(String color: new String[] {"Bronze", "Silver"}) {
   colors.add(color);
}
fiveEuros.setColors(colors);
fiveEuros.setYear("1880");


Which seems broken and has lots of typing and repetition. This is an example of building a pretty big  value object in my opinion, most of tend to be very small.

Before we talk about the benefits of creating objects this way, let's have a look at the structure of this pattern:


public final class Money {
   
      private Long value;
      private String countryOfOrigin;     
      private Currency currency;
      private String type; 
      private String reverse;
      private String obverse;    
      private List<String> colors;
     private Date year;    
 
      private Money() {   }

     // -- getters, hashCode, equals -- //

     // Static inner Builder class
   publicstaticclass Builder {
        private Money _temp = new Money();
 
        public Builder countryOfOrigin(String countryOfOrigin) {
_temp.contryOfOrigin = countryOfOrigin;
         returnthis;
}
 
public Builder currency(Currency c) {
_temp.currency = c;
returnthis;
}
 
public Builder type(String t) {
_temp.type = t;
returnthis;
}
 
public Builder reverse(String r) {
_temp.reverse = r;
returnthis;
}


       public Builder obverse(String o) {
_temp.obverse = o;
return this;
}


public Builder addColor(String c) {
if(_temp.colors == null) {
              _temp.colors = new ArrayList<String>(); 
           }
           _temp.colors.add(c);
return this;
}
 
         public Builder year(String y) {
              if(y == null || y.isEmpty()) {
                  _temp.year = new Date();
              }
              else {
                  _temp.year = DateFormat.parse(y);
              }
return this;
}
 
public Money build() {
                // Validate object
               if(Strings.isNullOrEmpty(_temp.name) || _temp.currency == null) {
                  throw new IllegalArgumentException("Coin currency and value required");
               }
return_temp;
}
    } }


This is also a matter of taste, but I prefer the static inner class approach. I like the canonical nature of referring to the builder as Money.Builder. Also making it static is required since the builder instance needs to live independently of the enclosing class.

I like this pattern because it has the following benefits:

  1. Greater object encapsulation: I can easily enforce object construction using builders by making the Money constructor private (this is just stylistic). This completely hides all of the intricacies of creating this object: list creation, date parsing, etc. From the user's perspective, what we end up with is an object that is simple to instantiate. My illustration is a very simple one, but imagine more complex object graphs.
  2. Code readability: Using this pattern to create objects, makes unit tests and code very easy to read and follow. 
  3. Less typing in the long run: Even though you have to add an extra builder method for every added attributes, the amount of typing you save in the long run makes it worth while. 


Conclusion

Using the fluent creation pattern is more work up front, but the benefits of having it pays off at the end. It makes instantiating objects very elegant and clean. You don't have to use it with Value Objects, most of the benefit of using Fluent Object Creation is when you need to build pretty complex object graphs, but I wanted to show that it can also suit small value objects.

 

 

 

refer:http://www.reflectivethought.net/2013/01/fluent-object-creation.html



Object Associations

clock January 20, 2013 21:37 by author Administrator


 


Composition: the Employee is encapsulated within the Company . There is no way for the outside world to get a reference to the Employee. The Employee is created and destroyed with the company

final class Company{
private final Employee Employee;
{
    Company(EmpDetails details) {
    engine = new Employee(details);
  }
   void assign() {
      emp.work();
   }
}

 

Aggregation: The Company also performs its functions through an Employee, but the Employee is not always an internal part of the Company . Employees can be exchanged, or even completely removed. As the employee is injected, the Employee reference can live outside the Company.

final class Company{
  private Employee engine;
  void addEmployee(Employee emp) {
    this.emp = emp;
  }
  void assign() {
    if (emp != null)
      emp.work();
  }
}

 

Dependency: The company does not hold the employee reference. It receives an employee reference only to the scope an operation. Company is dependent on the Employee object to perform an operation

final class Company{
  void assign(Employee emp) {
    if (emp != null)
      emp.work();
  }
}

Abstraction: Defines the basic operations the implementer should adher to. Employee interface lists the general behavior of an employee

public interface Employee{
 public void work();
 public void off();
 public void quit();
}

Realisation: A class implements the behavior defined by the other other class or interface

public abstract class Engineer implements Employee{
 public void work();
 public void off();
 public void quit();
}

Generalization: A class which is a special form of a parent class

 public class SWEngineer extends Engineer {
 public void work()
 {
  System.out.println('SW Engineer working');
 }
 public void off()
 {
  System.out.println('SW Engineer is off today');
 }
 public void quit()
 {
  System.out.println('SW Engineer is quitting');
 }

}

Association Defines a relationship between classes. Compositon and Aggregation are types of associations
Composition the Employee is encapsulated within the Company . There is no way for the outside world to get a reference to the Employee. The Employee is created and destroyed with the company
Aggregation The Company also performs its functions through an Employee, but the Employee is not always an internal part of the Company . Employees can be exchanged, or even completely removed. As the employee is injected, the Employee reference can live outside the Company.
Dependency The company does not hold the employee reference. It receives an employee reference only to the scope an operation. Company is dependent on the Employee object to perform an operation
Abstraction Defines the basic operations the implementer should adher to. Employee interface lists the general behavior of an employee
Realization A class implements the behavior defined by the other other class or interface
Generalization A class which is a special form of a parent class

UML Relationship Pointers

ref:http://techie-experience.blogspot.gr/2013/01/quick-summary-object-associations.html



Good Developer, Bad Developer

clock January 10, 2013 21:13 by author Administrator
Good developer Bad developer
Good developer is an artist, a craftsman who enjoys the process of creation. Bad developer considers himself as a programmer, responsible for generating lines of code.
Good developer understands the problems of the customers Bad developer understands only the technical problem at hand. Good developer does not define the why, but constantly strives to understand why. He’s responsible for the how, and still sees the big picture. Bad developer is focused on building classes and methods and configuration files, but does not get the big picture.
Good developer understands the complete architecture of the product. Bad developer knows only the components he’s written. Good developer fully understands the technologies that are used within the product. He understands what they are used for, and how they work internally.
Good developer is not afraid of new technologies but embraces them by quickly getting a grip. Bad developer only sticks to what he knows. His immediate reaction to any technical change is negative.
Good developer is constantly learning and improving his skills. Good developer reads technical articles, and finishes several technical books a year. Bad developer does not have time to learn. He’s always too busy with other stuff.
Good developer cares about the product quality. He is also very much concerned with the process quality. Good developer pushes himself to create bug-free code; bad developer leaves it to QA to find bugs to fix.
Good developer develops features which create value for customers. Bad developer completes tasks. Good developer will never claim the requirements are incomplete, and will make sure to fully understand the features he’s working on. Bad developer will wait until the finest details are available. To emphasize: good developer is the CEO of the feature – he’s going to make sure he always has the information needed to accomplish the feature, and in case information is missing he’ll make sure he gets it.
Good developer is not afraid to go into anyone’s code. Bad developer is afraid of others looking into his. Good developer understands that it shouldn’t take more time to write self-explanatory and well-documented code. Bad developer always needs to allocate extra time to document and simplify.
Good developer will never feel his code is good enough, and will always continue to clean and fix. Good developer always strives to create elegant solutions but understands that his job is to deliver value to customers. Bad developer thinks only about the elegance of his code and leave the job of delivering value to others.
   


Roles in the IT World

clock December 4, 2012 23:03 by author Administrator

Reference: Roles in the IT World



kent beck new post

clock December 1, 2012 22:58 by author Administrator

In the optimization model of software design there are one or more goals in play at any one time--reliability, performance, modifiability, and so on. Changes to the design can move the design on one or more of these dimensions. Each change requires some overhead, and so you would like few changes, but each change also entails risk, so you would like the changes to be as small as possible, but each change creates value, so you would like changes to be as big as possible. Balancing cost, risk, and progress is the art of software design.

 

If you've been reading along, you will know that my Sprinting Centipede strategy is to reduce the cost of each change as much as possible so as to enable small changes to be chained together nearly continuously. From the outside it is clear that big changes are happening, even though from the inside it's clear that no individual change is large or risky.

 

One knock on this strategy is how it deals with the situation where incremental improvement is no longer possible, where the design has reached a local maximum. For example, suppose you have squeezed all the performance you can out of a single server and you need to shard the workload. This can be a large change to the software and can't be achieved by incremental improvements.

 

It's tempting to pull out a clean white sheet of paper when faced with a local maximum and a big trough. However, the risk compounds when replacing a large amount of functionality in one go. Do we have to give up the risk management advantages of incremental change just because have painted ourselves into a (mixed) metaphorical corner?

 

The problem is worse than it seems on the surface. If we have been making little incremental changes daily for months or years, our skills at de novo development will have atrophied. Not only are we putting a big bunch of functionality into production at once, we developed that functionality at less than 100%. Bad mojo.

 

The key is being able to abandon the other half of the phrase "incremental improvement". If we are willing to mindfully practice incremental degradation, then we can escape local maxima, travel through the Valley of Despair, and climb the new Mountain of Blessedness all without abandoning the safety of small steps. Here are some examples.

 

Suppose we have a class that is awkwardly factored into methods. Say there is 100 lines of logic, the coding standards demand no more than 10 lines per function, and someone took the original 100 line function and chopped it every 10 lines (I'm not smart enough to make this stuff up). What's the best way to get to a sensible set of helper methods? Incremental improvement is hard because related computations can easily be split between functions. Incremental degradation, though, is easy (especially with the right tools): inline everything until you have one gigantic, ugly function. With the, er..., stuff all in one pile, it's relatively easy to make incremental improvements.

 

Suppose we need to switch from one data store to another. Normalization is good, right? So the incremental way to convert is to denormalize. Everywhere we write to the old store, write to the new store. Bulk migrate all the old data. Begin reading from the new store and comparing results to make sure they match. When the error rate is acceptable, stop writing to the old store and decommission.

 

The literature and tools for incremental change betray a bias towards improvement. Fowler's "Refactoring" covers extracting methods more thoroughly than inlining them. Refactoring tools often implement varieties of extract before inline. To be fair, that's the more common direction to move. However, mastering incremental design demands being equally prepared to improve or degrade the design at any time, depending on whether it's possible to incrementally improve. In fact, sometimes when I have degraded the design and discover I still can't make incremental progress, I release my inner pig and make a really big mess.

 

tl;dr If you can't make it better, make it worse.



The Principles of Good Programming

clock November 23, 2012 13:56 by author Administrator

The principles of good programming are closely related to principles of good design and engineering. The following programming principles have helped me over the years become a better programmer, and I believe can help any developer become more efficient and to produce code which is easier to maintain and that has fewer defects.

DRY - Don’t repeat yourself. - Probably the single most fundamental tenet in programming is to avoid repetition. Many programming constructs exist solely for that purpose (e.g. loops, functions, classes, and more). As soon as you start repeating yourself (e.g. a long expression, a series of statements, same concept) create a new abstraction.
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Abstraction Principle - Related to DRY is the abstraction principle “Each significant piece of functionality in a program should be implemented in just one place in the source code.”
http://en.wikipedia.org/wiki/Abstraction_principle_(programming)

KISS (Keep it simple, stupid!) - Simplicity (and avoiding complexity) should always be a key goal.
http://en.wikipedia.org/wiki/KISS_principle

Avoid Creating a YAGNI (You aren’t going to need it) - You should try not to add functionality until you need it.
http://en.wikipedia.org/wiki/YAGNI

Do the simplest thing that could possibly work - A good question to ask one’s self when programming is “What is the simplest thing that could possibly work?” This helps keep us on the path towards simplicity in the design.
http://c2.com/xp/DoTheSimplestThingThatCouldPossiblyWork.html

Don’t make me think - This is actually the title of a book by Steve Krug on web usability that is also relevant in programming. The point is that code should be easily read and understood with a minimum of effort required. If code requires too much thinking from an observer to understand, then it can probably stand to be simplified
http://www.sensible.com/dmmt.html

Open/Closed Principle - Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. In other words, don't write classes that people can modify, write classes that people can extend.
http://en.wikipedia.org/wiki/Open_Closed_Principle

Write Code for the Maintainer - Almost any code that is worth writing is worth maintaining in the future, either by you or by someone else. The future you who has to maintain code often remembers as much of the code, as a complete stranger, so you might as well always write for someone else.
A memorable way to remember this is “Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.”
http://c2.com/cgi/wiki?CodeForTheMaintainer

Principle of least astonishment - The principle of least astonishment is usually referenced in regards to the user interface, but the same principle applies to written code. Code should surprise the reader as little as possible. The means following standard conventions, code should do what the comments and name suggest, and potentially surprising side effects should be avoided as much as possible.
http://en.wikipedia.org/wiki/Principle_of_least_astonishment

Single Responsibility Principle - A component of code (e.g. class or function) should perform a single well defined task.
http://en.wikipedia.org/wiki/Single_responsibility_principle

Minimize Coupling - Any section of code (code block, function, class, etc) should minimize the dependencies on other areas of code. This is achieved by using shared variables as little as possible. “Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability”
http://en.wikipedia.org/wiki/Coupling_(computer_programming)

Maximize Cohesion - Code that has similar functionality should be found within the same component.
http://en.wikipedia.org/wiki/Cohesion_(computer_science)

Hide Implementation Details - Hiding implementation details allows change to the implementation of a code component while minimally affecting any other modules that use that component.
http://en.wikipedia.org/wiki/Information_Hiding

Law of Demeter - Code components should only communicate with their direct relations (e.g. classes that they inherit from, objects that they contain, objects passed by argument, etc.)
http://en.wikipedia.org/wiki/Law_of_Demeter

Avoid Premature Optimization - Don’t even think about optimization unless your code is working, but slower than you want. Only then should you start thinking about optimizing, and then only with the aid of empirical data.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil" Knuth.
http://en.wikipedia.org/wiki/Program_optimization

Code Reuse is Good - Not very pithy, but as good a principle as any other. Reusing code improves code reliability and decrease development time.
http://en.wikipedia.org/wiki/Code_reuse

Separation of Concerns - Different areas of functionality should be managed by distinct and minimally overlapping modules of code.
http://en.wikipedia.org/wiki/Separation_of_concerns

ref:http://area.autodesk.com/blogs/chris/the_principle_of_good_programming



Things Great Engineers (almost) Never Say

clock October 12, 2012 22:48 by author Administrator
  • “I’ve used _____ but I have no idea how it works”
    – Great engineers gained their skills through probing and curiosity.  They go ‘under the hood’ of the products they use just to understand how things work, even if that information will never be very useful to them.  It is unclear whether this need to dig deeper is a choice or a compulsion, but it seems that it is a trait of the best talent.
  • “______ works, I just don’t know how to explain it”
    – Not only do the greats know how things work, but most of them derive genuine pleasure in telling others why and how things workThis is often true even if the other person doesn’t care to know.  Over the course of my career I’ve listened to engineers talk for thousands of hours, and in almost all cases my conversations with the most talented go much longer.  I actually made a point of scheduling an extra fifteen to twenty minutes on my calendar when I will be speaking to someone who appears to be great on paper, as I know that the person will go deep into some technical details and nuances that will come up in conversation.
  • “I will need ______ (tool/condition) to complete this task”
    – The masters of development will have the ability to improvise and adjust on the fly to arrive at a solution in non-ideal conditions.  When you hear of engineers being compared to MacGyver they are speaking of this very rare skill.  Greats will figure out a way based on minimal resources and will be aware of alternatives to their first choice of tool.
  • “I’ve learned all I want/will ever need to know about ________ “
    – Continuous learning and improvement is probably the most obvious differentiation between the good and the great.  They don’t just get to a high level and then rest.  The best engineers understand that industry progress causes them to never stop learning, and if they are not gaining enough new knowledge in their day jobs they will invest the time to learn during off hours.
  • “There is no solution” – The greats will continue looking at a problem different ways to come up with an answer instead of conceding.  This characteristic can be both a blessing and a curse.
  • “I hate programming” - At times a great engineer will hate their job or employer, but their love of solving problems with code is what brought them to this skill level.
  • “I’m an expert in _____” (when it’s not true, and even sometimes when it is true) – The strongest engineers have no need or desire to lie or exaggerate the depth of their skills.  Much of the great talent will be reluctant to say they are an expert in anything, as they are aware others could know more.
  • “I don’t understand the business” – The stronger engineers will always want to know how their code impacts the employer and is able to describe their contribution and value to the organization.
  • “I don’t pay particular attention to industry trends” – Being both great and relevant (in demand) is only possible if you keep an eye on where the industry is headed.  When speaking to talented engineers, the topic of which new technologies are actually viable and which are a passing phase will often come up.

If you find yourself using any of these lines on a regular basis, give some thought to why.  Quoting one of these lines in a job interview could be a serious mistake.

 

 

Reference: Things Great Engineers (almost) Never Say



kent beck

clock October 7, 2012 23:35 by author Administrator

when my search space gets big and uncertain i need a pen and paper, not a computer



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In