Showing posts with label OOPs. Show all posts
Showing posts with label OOPs. Show all posts

Abstraction Concept In OOPs

2022-05-07

What is Abstraction?

As per https://www.collinsdictionary.com/dictionary/english/abstraction I think this definition suits best match for programmers:

"the act of considering something as a general quality or characteristic, apart from concrete realities, specific objects, or actual instances."

Synonyms of abstraction given are: concept, thought, idea, view. 

Above information is about the meaning and synonyms about the word: abstraction given in the Collins dictionary.

Abstractions are used regularly in everyday language, we use abstraction when talking about lots of things, such as:

  • Chair
  • Table
  • Computer
  • Mobile Phone

These are abstract ideas which everyone understands but people don’t have a mobile phone, they have an exact make of mobile phone but most people don’t talk about the exact type by the abstract type of mobile phone.

Understanding Abstraction & Why is understanding Abstraction important

Abstractions help hide concrete code which can change with abstractions such as interfaces and abstract classes which are less likely to change. Using abstraction limits dependencies in code, reduced dependency means reducing the effect of change in your code. 

Two of the key long term goals for developers when writing code

  • Increase the readability of the code
  • Minimize dependencies in code, reducing the effects of change

Junior developers seem reluctant to use abstractions in code because of a mixture of not understanding how abstractions work and because they are focused on getting the code working and bypass the creation of abstractions, which can lead to big complex methods, few classes and no abstractions.

Junior developers are focused on the short term goal of getting the code working with the intent of leaving the design and creation of abstractions until later (later often doesn’t come).

Abstraction is one of the key principles behind many of the OO design principles such as:

  • Inheritance
  • Polymorphism
  • Composition

Benefits of abstraction:

  • Code is easy to understand
  • Manages change and the effect of change
  • Creates cohesive code – it finds common fields
  • Create loose coupling

Abstraction refines concepts to their core values, stripping away ideas to the fundamentals of the abstract idea. It leaves the common details of an idea.

Abstractions make it easier to understand code because it concentrates on core features/actions and not on the small details.

  • Encapsulate what varies
  • Favor composition over inheritance
  • Program to interfaces, not to implementations
  • Strive for loosely coupled design between objects that interact
  • Depend upon abstractions. Do not depend upon concrete classes

When abstraction proceeds into the operations defined, enabling objects of different types to be substituted, it is called polymorphism. When it proceeds in the opposite direction, inside the types or classes, structuring them to simplify a complex set of relationships, it is called delegation or inheritance.

How to find abstractions?

Common abstractions are

  • Nouns – things, people, systems
  • Verbs
  • Types
  • Behaviors
  • Is A – Inheritance
  • Has A – Behaviors

Actions/Verbs are often abstractions e.g. Drawing, validating, processing, routing.

When I mention types I am referring to Abstractions are useful in life. People use abstractions all the time, you often mention

  • Computers
  • Chairs
  • People
  • Cars

You don’t talk about the distinctive type of car but say car in general and people will understand you what you are talking about. The same idea can be used in your code design. You can find a common action like validating, drawing, Updating, exceptions. The common action will be the interface and the concrete classes can hide behind it. 

Exceptions are a good example you have a core exception (the ones lazy programmers throw when they don’t want to specify the exact error) and then distinctive exceptions extend it. Exception is the abstraction and InvalidPluginExecutionException , NullReferenceException etc are the implementing concrete classes.

Why Abstractions are so important?

Change can ripple through poorly designed code because poorly designed code is fragile, you change one part of it and an unrelated part of the code suddenly breaks. The reason for this sudden breaking is dependency.

Abstractions (interfaces/Abstract classes) reduces dependencies and the abstraction acts as a barrier to dependency and change.

Abstractions help create well designed code.

The code is easy to understand because if you have captured the right abstractions is obvious what the code is doing.

Abstractions help create loosely coupled code. The reason is the abstraction acts like a type and encapsulates the potential changes behind the abstract class/interface.

To understand why this is import you need to understand the statement

code to an interface, not a concrete class.

A classic abstraction is creating a database layer, an abstract class or interface which parts of the code users to interact with the database. The abstract minimizes the effects of change because the code which interacts with the interface will not be effected by the implementation/concrete class changing. It also allows the code to change in the future and more types being added.

Adding more types will not effect any code which interacts only with the interface.

This brings me nicely to the design principle

Encapsulate what varies

Business rules or algorithms are a good example. When you have a behavior or type you have an Abstraction. Using an abstract class will manage the effects of change and create a loosely coupled system which will manage the effect of change.

Understanding abstractions can make you look at your existing code base from a different perspective because the potential abstractions highlight where the code might change in the future and areas of potential refactoring.

Ref: https://crmbusiness.wordpress.com/2015/08/12/why-understanding-abstractions-helps-you-write-better-code/

Code smell

2022-04-17

Note that a CodeSmell is a hint that something might be wrong, not a certainty. A perfectly good idiom may be considered a CodeSmell because it's often misused, or because there's a simpler alternative that works in most cases. Calling something a CodeSmell is not an attack; it's simply a sign that a closer look is warranted.

One of the nice things about smells is that it's easy for inexperienced people to spot them, even if they don't know enough to evaluate if there's a real problem or to correct them. I've heard of lead developers who will pick a "smell of the week" and ask people to look for the smell and bring it up with the senior members of the team. Doing it one smell at a time is a good way of gradually teaching people on the team to be better programmers.

Some examples of code smells

Conditional Complexity

Watch out for large conditional logic blocks, particularly blocks that tend to grow larger or change significantly over time. Consider alternative object-oriented approaches such as decorator, strategy, or state.

Combinatorial Explosion

You have lots of code that does almost the same thing.. but with tiny variations in data or behavior. This can be difficult to refactor-- perhaps using generics or an interpreter?

Oddball Solution

There should only be one way of solving the same problem in your code. If you find an oddball solution, it could be a case of poorly duplicated code-- or it could be an argument for the adapter model, if you really need multiple solutions to the same problem.

Data Clumps

If you always see the same data hanging around together, maybe it belongs together. Consider rolling the related data up into a larger class. 

Indecent Exposure

Beware of classes that unnecessarily expose their internals. Aggressively refactor classes to minimize their public surface. You should have a compelling reason for every item you make public. If you don't, hide it.

Feature Envy

Methods that make extensive use of another class may belong in another class. Consider moving this method to the class it is so envious of.

Long method names

Seriously: If you follow good naming standards, long method names are often an indication that the method is in the wrong class. For example,

createWhateverFromWhateverOtherClass(OtherClass creator) vs

creator.createWhatever(). See UsingGoodNamingToDetectBadCode.



Duplicated Code

Balance the smell against the cost of reducing it in your environment. Each environment (language, linkers, etc) has its own threshold for how much duplication you can remove without it being too painful or too obfuscating.

Consequently if a company spent X dollars to develop a product with duplicated code it will have to spend X * K dollars on code refactoring without any single visible improvement of the product, where K is between 3 and 100 depending on skills, complexity, language, etc.

Some companies hire more and more developers to pay interest on that duplication debt or keep changing developers wondering why production emergencies don’t disappear even with best minds on it.

Switch Statements Smell

ObjectOrientedProgramming avoids them: "Most times you see a switch statement, you should consider polymorphism. This is not to say that SwitchStatementsAreEvil, just that they aren't ObjectOriented. Please note also that not all programs that use switches exhibit the CodeSmell.

When you get the SwitchStatementsSmell, it's an indication that your code isn't ObjectOriented. It could also be a case of following the rule DoTheSimplestThingThatCouldPossiblyWork.

Classes with too much code -

See: OneResponsibilityRule, GodClass
Violates the Single responsibility principle of SOLID

Principle of Least Knowledge or Law of Demeter(LOD)

An object should avoid invoking methods of an object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.m().n() breaks the law where a.m() does not.

Ref: https://wiki.c2.com/?SwitchStatementsSmell 

https://wiki.c2.com/?CodeSmell

http://mywwwexperience.blogspot.com/2022/03/principle-of-least-knowledge-or-law-of.html

Principle of least knowledge or Law of Demeter (LoD)

2022-03-13

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling.

· Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
· Each unit should only talk to its friends; don't talk to strangers.
· Only talk to your immediate friends.

In particular, an object should avoid invoking methods of an object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.m().n() breaks the law where a.m() does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead one commands the dog which then commands its own legs.

Advantages

The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object implementation can be changed without reworking their callers.

Disadvantages

Although the LoD increases the adaptiveness of a software system, it may result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead

4 Basic Principles of OOPs

4 Basic principles of OOPs are:
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Abstraction: Its about modeling the relevant attributes and interactions of entities as classes to define an abstract representation of a system.
It's a modelling or design concept in which we define the methods & attributes or members of entities via classes or interfaces.
Abstraction separates the interface from implementation. An abstraction focuses on the outside view of an object's essential behavior from its implementation.

Encapsulation is the process of hiding the internal implementation of an object. Hides
 the internal state and functionality of an object and only allowing access through a public set of functions.

Inheritance: ability to create new create new abstractions based on existing abstractions. Inheritance enables hierarchical relationships to be represented and refined.

Polymorphism: Ability to implement inherited properties or methods in different ways across multiple abstractions. Polymorphism allows objects of different types to receive the same message and respond in different ways.

About Interface

2011-04-03

I read simple & correct definition about the Interface here

The basic problem an interface is trying to solve is to separate how we use something from how it is implemented.

Why do we want to separate the use from the implementation?

So that we can write code that can work with a variety of different implementations of some set of responsibilities without having to specifically handle each implementation.

To put this simpler, this means that if we have a Driver class it should be able to have a method Drive that can be used to drive any car, boat or other kind of class that implements the IDriveable interface.

The Driver class should not have to have a DriveBoat, DriveCar or DriveX methods for each kind of class that supports the same basic operations that are needed for it to be driven.

Interfaces are trying to solve a very specific problem by allowing us to interact with objects based on what they do, not how they do it.


Interfaces are contracts
=======================
Interfaces allow us to specify that a particular class meets certain expectations that other classes can rely on.

If we have a class that implements an interface, we can be sure that it will support all the methods that are defined in that interface.

At first glance interfaces seem to be similar to concrete inheritance, but there is a key difference.

Concrete inheritance says Car is an Automobile, while an interface says Car implements the Drivable interface.

When a class implements an interface, it does not mean that class IS that interface. For this reason interfaces that completely describe the functionality of a class are usually wrong.

A class can implement multiple interfaces, because each interface only talks about a particular contract that class is able to fulfill.


Interfaces are always implemented by more than one class
===========================================================
You might be saying “no they’re not, I have a class here that has an interface that no other class implements.”

To that I say, “you are doing it wrong.”

But, don’t worry, you are not alone. I am doing it wrong also. Many of us are not using interfaces correctly anymore, but are using them instead because we are under the impression that we should never use a concrete class directly.

We are afraid of tightly coupling our application, so instead we are creating interfaces for every class whether or not we need an interface.

There are some really good reasons why I say that interfaces are always implemented by more than one class.

Remember how we talked about how interfaces are designed to solve a particular problem?

In my example, I talked about how the Driver class shouldn’t have to have a method of each kind of class it can drive, instead it should depend on an IDriveable interface and can have one generic Drive method that can drive anything that implements IDrivable.

Most of us accept the YAGNI principle which says “You Ain’t Gonna Need It.” If we only have a Car class, and we don’t have any other classes that need to be driven by the Driver class, we don’t need an interface. YAGNI!

At some point we may later add a Boat class. Only at that point in time do we actually have a problem that the interface will solve. Up until that point adding the interface is anticipating a future problem to solve.

If you think you are good at anticipating when you will need an interface, I want you to do a little exercise. Go into your codebase and count all the interfaces you have. Then count all the classes that implement those interfaces. I bet the ratio is pretty close to 1 to 1.

Interface Example:

As said Interface defines well defined contracts. These contracts are implemented by the classes which are ready to implement this interface. That's it's like A company called X outsource some job to its contracting company Y.  Company X can later give that job to any other company if they wish. This flexibility can be achieved thorough interface programming.

Abstract Class- An Object Oriented View

2008-12-07

We usually think of classes as being complete definitions. However, there are situations where incomplete definitions are useful, and classes that represent these incomplete definitions are equally useful. For example, in everyday conversation, we might talk about such items as bank accounts, insurance policies, and houses. In object-oriented thinking, we often isolate useful, but incomplete, concepts such as these into their own special classes.

Abstract classes are classes that embody coherent and cohesive, but incomplete, concepts, and in turn, make these characteristics available to their specializations via inheritance. People sometimes use the terms "partial type" and "abstract superclass" as synonyms for abstract class. While we would never create instances of abstract classes, we most certainly would make their individual characteristics available to more specialized classes via inheritance.

For example, consider the concept of an automobile. On one hand, most people know what an automobile is. On the other hand, "automobile" is not a complete definition for any vehicle. It would be quite accurate to describe "automobile" as the set of characteristics that make a thing an automobile, in other words, the "essence of automobile-ness."

Object-oriented programming fundamentals

2008-10-19

The following sections use the analogy of a cat, demonstrating how cats might compare to OOP concepts.

Objects

Think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In the world of OOP, objects also have properties and behaviors. Using object-oriented techniques, you can model a real-world object (such as a cat) or a more abstract object (such as a chemical process).

What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.
A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.
A software object.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
Consider a bicycle, for example:
A picture of an object, with bibycle methods and instance variables.
A bicycle modeled as a software object.
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.


Instances and class members

Continuing with the real-world analogy of a cat, consider that there are cats of different colors, ages, and names, with different ways of eating and purring. But despite their individual differences, all cats are members of the same category, or in OOP terms, the same class: the class of cats. In OOP terminology, each individual cat is said to be an instance of the Cat class.

Likewise in OOP, a class defines a blueprint for a type of object. The characteristics and behaviors that belong to a class are jointly referred to as members of that class. The characteristics (in the cat example, the name, age, and color) are called properties of the class and are represented as variables; the behaviors (play, sleep) are called methods of the class and are represented as functions.

Inheritance
One of the primary benefits of OOP is that you can create subclasses of (or extend) a class; the subclass then inherits all the properties and methods of the class. The subclass typically defines additional methods and properties or overrides methods or properties defined in the superclass. Subclasses can also override (provide their own definitions for) methods defined in a superclass.

One of the major benefits of using a superclass/subclass structure is that it is easier to reuse similar code between various classes. For example, you could build a superclass called Animal, which contains common characteristics and behaviors of all animals. Next you could build several subclasses that inherit from the Animal superclass and add characteristics and behaviors specific to that type of animal.

You might create a Cat class that inherits from another class. For example, you might create a Mammal class that defines certain properties and behaviors common to all mammals. You could then create a Cat subclass that extends the Mammal class. Another subclass, say, the Siamese class, could extend (subclass) the Cat class, and so on.

Writing subclasses lets you reuse code. Instead of recreating all the code common to both classes, you can simply extend an existing class.

TIP
In a complex application, determining how to structure the hierarchy of your classes is an important part of the design process. Make sure you determine this hierarchy before you begin to program.

Interfaces
Interfaces in OOP can be described as templates of class definitions, and classes that implement interfaces are required to implement that template of methods. Using the cat analogy, an interface is similar to a blueprint of a cat: the blueprint tells you which parts you need, but not necessarily how those parts are assembled, or how the parts work.

You can use interfaces to add structure and ease of maintenance to your applications. Because ActionScript 2.0 supports extending only from a single superclass, you can use interfaces as a form of limited multiple inheritance.

You can also think of an interface as a "programming contract" that you can use to enforce relationships between otherwise unrelated classes. For example, suppose you are working with a team of programmers, each of whom is working on a different part (class) of the same application. While designing the application, you agree on a set of methods that the different classes use to communicate. So you create an interface that declares these methods, their parameters, and their return types. Any class that implements this interface must provide definitions for those methods; otherwise, a compiler error results.

Encapsulation

In elegant object-oriented design, objects are seen as "black boxes" that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems.

Encapsulation is why ActionScript 2.0 includes, for example, member access control, so details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object's programming interface rather than with the implementation details (which can be hidden in private methods and properties). This approach provides some important benefits; for example, it lets the creator of the object change the object's implementation without requiring any changes to code outside of the object--that is, as long as the programming interface doesn't change.

Polymorphism

OOP lets you express differences between individual classes using a technique called polymorphism, by which classes can override methods of their superclasses and define specialized implementations of those methods. In Flash, subclasses can define specialized implementations of methods inherited from its superclass but cannot access the superclass's implementation as in other programming languages.

For example, you might start with a class called Mammal that has play() and sleep() methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the play() method from the Mammal class to reflect the habits of those particular kinds of animals. Monkey implements the play() method to swing from trees; Cat implements the play() method to pounce at a ball of yarn; Dog implements the play() method to fetch a ball. Because the sleep() functionality is similar among the animals, you would use the superclass implementation.

Using polymorphism in an application

Object-oriented programming lets you express differences between individual classes using a technique called polymorphism, by which classes can override methods of their superclasses and define specialized implementations of those methods. Funny aspect Boys use the word friendship to start love, girls use the same word to end love. Same words but different attitude. This OOPS concept is called as polymorphism!!!