Skip to main content

Posts

Showing posts with the label object_oriented

Avoid assumptions in infrastructure code

A few days back, while reviewing some code I came across what I considered to an over abundance of assumptions in infrastructure code. Such assumptions in infrastructure code can make software buggy and difficult to change. Let me first explain what I mean by infrastructure code. Frameworks always have interactions that we use when we extend their classes. For example if you have used Struts, then the custom action classes we create, use Strut's infrastructure code from the ActionServlet and the Struts RequestDispatcher. These classes call methods which are overriden by our custom classes, thus allowing our code to get called. Even when we do not use such frameworks, there are lots of places where we have hand written infrastructure code in our projects. Typically these are methods in base classes that are invoked as part of a use case. These methods will do a bunch of things that are determined by reading configuration files, decoding the request that invoked them, and perhaps oth...

Polymorphism

Polymorphism is the ability of an object to assume multiple forms. The example below assumes a class heirarchy with Appender as the superclass. For now it is sufficient to know that the Appender class is responsible for appending log statements to a certain destination. This class has three subclasses, ConsoleAppender, FileAppender, and DatabaseAppender, each of which implement the 'append' of the superclass to direct the log statement to the console, file, and database respectively. The audio explains polymorphism with this simple example. [Time: 3 mins 40 secs] Watch a simple animation of how Polymorphism works. Discuss this post in the learning forum . Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net     Commercial Links Buy programming books from our Amazon.com powered storefront . Earn as you browse. Sign up for Algoco .

Inheritance

Logging frameworks like Log4J allow us to send logs to a multitude of destinations. The code responsible for logging to a destination is usually encapsulated into seperate classes. Without inheritance With inheritance When to use inheritance: IS-A relationship An Employee is a Person A BumperSale is a Sale A Square is a Shape IS-LIKE-A relationship But if the relationship between them is HAS-A (eg: Car has an Engine), then we use composition instead of inheritance. Reflections: What is the relationship between the following objects? Bathroom - Bathtub Car - Engine Person - Professor Vehicle - Car Discuss this post in the learning forum . Note: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net   Commercial Links Buy programming books from our Amazon.com powered storefront . Earn as you browse. Sign up for Algoco .

Encapsulation and information hiding

Encapsulation and information hiding are often used interchangeably. But they are actually different. Information hiding is a design principle, whereas encapsulation is a langauge facility. Encapsulation is the process of bundling code and the data it acts on together in one entity. David Parnas describes information hiding as "hiding of critical design decisions", so that the client code does not have to understand the intricacies of the design, and is also oblivious to any changes in design. Encapsulation can happen without information hiding, but will not be effective. Encapsulation facilitates, but does not gaurantee information hiding. Following some simple guidelines will help us create better classes   Rules for encapsulation: Rules for information hiding: These rules have been taken from this JavaWorld article on encapsulation . It's an excellent article that explains the concepts very well with relevant and well thought of code samples. Something on the side...

Abstraction

According to Wikipedia - Abstraction is the process of reducing the information content of a concept, typically in order to retain only information which is relevant for a particular purpose. For example, abstracting a premiership football to a ball retains only the information on general ball attributes and behaviour. Similarly, abstracting an emotional state to happiness reduces the amount of information conveyed about the emotional state. Click on the audio player below to listen to an explanation of what abstraction means in object oriented development.   This photograph is attributed to gautamnguitar, and is posted on Flickr with a Creative Commons license. Discuss this post in the learning forum . Resources: What is data abstraction?     Commercial Links Buy programming books from our Amazon.com powered storefront .

What does object oriented design promise?

In this section we will refresh basic object oriented concepts, to ensure that everyone understands the basics before proceeding.  Let us start with a brief history of object orientated programming. Object orientation is a step in the evolution of software design The purpose of object orientation is to create programs that are flexible, maintainable, and robust. Discuss this post in the learning forum . Notes: This text was originally posted on my earlier blog at http://www.adaptivelearningonline.net

Object oriented design

Simula 67 was the first object oriented language, and as it's name suggests was created in 1967. Since then many object oriented languages have been created, all with the purpose of easing software development and making it easier to write robust, maintainable, and flexible programs. In the next few posts I will cover the fundamental principles of programming with objects and how to apply those principles while coding in real life situations. Remember, even though object orientation gives us constructs for writing maintainable programs, if we do not use them properly, the resulting code will probably be more unmaintainable than simple structured programs. These are some of the topics that I will post about. A quick refresher of object oriented principles In this section we will once again refresh the basic concepts of abstraction, encapsulation, inheritance, and polymorphism.  Translating requirements into system design In this section we will understand how to identify classes and...

Your feedback on translating requirements into system design

Please take a couple of minutes to give your feedback on this section. Would you like to see any additions, subtractions, or changes? How did you like the audio and video descriptions used in this section? I know they are not optimal, and I hope to improve them, but it will really help me if I get feedback on exactly what should be improved to make the course more effective for you. Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

What is object oriented programming - by Alan Kay

Alan Kay coined the term object oriented programming in the 60's. Even though the progression of this paradigm has been a collaborative effort, Alan Kay has played a very important part in the creation of this paradigm. In 2003 Stephan Ram could not find an authoritative source on what "object oriented" really meant, so he decided to ask Alan Kay himself. Here's a link to his reply. A must read for anyone who is interested in object oriented programming and design.

Identifying interactions

[Time 5:50 mins] In this section we will identify collaborations among the classes as they enact each use case. In this phase we may discover new classes that we had not thought of earlier, as well as new responsibilities for existing classes. We may also discard some initial classes. The process of determining the collaborations as each use case is enacted helps in refining and validating the design. CUSTOMER DETERMINES THE PRICE OF A GROUP OF ITEMS: Customer enters item codes at the UserTerminal UserTerminal creates Item objects for each item and finds out their individual prices The UserTerminal finds out all the schemes these items belong to The UserTerminal determines the Scheme price of all items belonging to a Scheme and adds the individual price of the remaining items The UserTerminal displays all the above information to the Customer   CUSTOMER CHECKS OUT ITEMS: Customer takes items to the checkout system Checkout assistant adds item codes in the CheckoutSy...

Identifying responsibilities

[Time 2:04 mins] Here I have listed classes from the previous post and associated responsibilities to them. Customer - To shop - To pay for the items Item - Holds an item code - Has a cost - Has a price Scheme - Holds a scheme code - Has a price - Contains a list of other Items Price - Holds the price (for an item) DiscountedPrice - Holds the price - Holds the discount PerUnitPrice - Hold the price - Holds the unit for the price Unit (and subclasses) - Specifies a unit - May have methods for converting between units. StoreManager - Checks the audit trail of items sold - Determines the value of current in-shop inventory CurrentStock - Contains a list of all items in the shop  Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

Refine classes

[Time 6:29 mins] Now that we have identified some basic classes, some questions come to mind. Let us ponder a bit over these questions. We might identify new classes or remove some old ones at the end. Do we need different types of customers Do we need to represent simple and complex items differently? How do we represent different types of prices? Attributes vs sub classes How do we represent units? So now we have added a few classes: PriviledgedCustomer (maybe... let me ask the client) DiscountedPrice PerUnitPrice Various Unit subclasses This is by no means the final class list. As we identify responsibilities and collaborations, we will further refine this class list. Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

Class and communication diagrams

[Time: 7:07 mins] We have identified classes, their responsibilities, and interactions among them as they enact use cases. Shown below is a class diagram and several communication diagrams that outlines important classes, their relationships, and collaborations among them. I have not shown all the classes, but only the ones that are important and have relationships with other classes. Classes that are not shown include: Customer StoreManager UserTerminal ControlPanel CheckoutSystem    Figure 1   Communication Diagrams: Customer determines the price of a group of items    Figure 2   Customer checks out items Figure 3    Store Manager valuates in-shop inventory   Figure 4  Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

Translating requirements into system design - A case study

In this section we will take a requirements document for a software system and create a system design from it. The statement for the excercise has been inspired by Dave Thomas' coding kata #1 . Let's build a system for a supermarket. Here are the requirements. The supermarket has various items for selling. Each item has a price. Sometimes an item may have a discounted price, and sometimes it may be part of a scheme. Schemes could be similar to buy two get one free, or buy a certain quantity of an item and get another item free. Items may also be priced for a certain unit. For example Apples may be Rs 40/Kg, however they can be sold in a fractional unit also 500 gms. Some items may be simple, like a can of Pepsi or complex like a crate of 10 Pepsi cans. The sytem should also maintain an audit trail of all sold items for future evaluation. The store manager should be able to get a valuation of the current stock. When a shopper checks out items the system should calculate the most...

Your feedback on principles of object oriented design

Please take a couple of minutes to give your feedback on this section. Would you like to see any additions, subtractions, or changes? How did you like the audio and video descriptions used in this section? I know they are not optimal, and I hope to improve them, but it will really help me if I get feedback on exactly what should be improved to make the course more effective for you. Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

Using inheritance and composition

Inheritance is used for Code resuse To support polymorphism Disadvantages of inheritance Difficult to change the interaface of the subclass Superclass is always instantiated Can get complex and unmanageable Composition is used for code reuse Disadvantages of composition We cannot use polymorphism We cannot extend the system by adding subclasses May have a slight performance overhead Usage Inheritance: IS- A Composition: HAS - A Example  1 :  public class  Car  {      private  Engine engine;      public  void  start () {}      public  void  stop () {} }  public class  SUV  extends  Car {      public  void  start () {}  //overrides the start method from Car        public  void  fourByFourMode () {} } Examp...

High Cohesion

[Time: 4 mins] Stuff that goes together, stays together Easy to discover relevant code Levels of cohesion packages classes methods    So in very simple words, cohesion is keeping related stuff together so we can find what we want without too much difficulty.      Example  1 :  public class  Student  {      //cohesive methods      public  void  registerForCourse () {}      public  void  deregisterFromCourse () {}      viewTranscripts () {}      //methods below are not in synch with the responsibilities of the Student class      //hence cohesion is broken      submit grades () {}      submitCourseSchedule () {}   }  ...

Loose coupling

[Time: 4:32 mins] Loose (or low) coupling means (in a generic sense) that an entity can interact with another entity without being concerned with the internal implementation, and through a stable interface. Low coupling is implemented by using principles of information hiding. When two entities are loosely coupled, internal changes in one of them do not affect the other. The calling method is coupled to the called method and not it's implementation. Since we have already discussed encapsulation and information hiding in detail, I will not repeat it here. Loose coupling is achieved with information hiding And by programming to the interface rather than the implementation   Example  1 : Tightly coupled system  public  void  aMethod () {       ArrayList myList =  new  ArrayList () ;      doSomethingWithList ( list ) ;  }  ...

Don't repeat yourself

The code says everything once and only once, which is the essence of good design. -- Martin Fowler [Time: 4:44 mins] Repititive code makes maintainance more difficult There are more places to change We may forget to change some of them Increases probability of bugs Types of repitition In methods in a class Accross the entire software  Example 1: DRY violated public class  Account  {    public  void  transferFunds ( double  amt, Account dest ) {      //transfer funds      //generate email... create connection      //create message      //dispatch email    }    public  void  delete () {      //delete account      //generate email... create connection      //create me...