SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
MODULARIZING STRATEGIES:
FIXING CLASS & PACKAGE TANGLES
ganesh samarthyam
(ganesh@codeops.tech)
WHAT’S A “TANGLE”?
➤ “A tangle is a portion of a dependency graph within which all
the items are directly or indirectly dependent on all the other
nodes in the tangle.” (Source: structure101.com)
Example of a class tangle (cycle)
Example of a package tangle
REMOVING TANGLES - VISUALISING IN STRUCTURE101
REFACTORING CLASS TANGLES
DEPENDENCIES BETWEEN CONCRETE CLASSES - TANGLE
import java.util.List;
public class Customer {
List<Order> orders;
}
class Order {
Customer purchaser;
}
A direct cyclic dependency between the Customer & Order class because
they contain instances of each other’s type
DEPENDENCIES BETWEEN CONCRETE CLASSES - TANGLE - FIX
import java.util.List;
public class Customer {
List<Order> orders;
}
class Order {
Customer purchaser;
}
Depend on the interface instead of the implementation (and the cycle is gone)
import java.util.List;
interface Buyer {}
public class Customer implements Buyer {
List<Buyable> orders;
}
interface Buyable {}
class Order implements Buyable {
Buyer purchaser;
}
BASE CLASS REFERS TO ITS DERIVED TYPES(S)
enum ImageType { JPEG, BMP, PNG };
abstract class Image {
public static Image getImage(ImageType imageType,
String name) {
switch (imageType) {
// JPEGImage, BMPImage, PNGImage are
// derived classes of the abstract class Image
case JPEG: return new JPEGImage(name);
case BMP: return new BMPImage(name);
case PNG: return new PNGImage(name);
}
return null;
}
}
This is a special kind of cyclic dependency - the base type knows about its
derived type! Here it is creation of its derived objects results in a tangle
BASE CLASS REFERS TO ITS DERIVED TYPES(S) - FIX
It’s easy to break this cyclic dependency - move the getImage() method to a
dedicated class named ImageFactory!
AVOIDABLE REFERENCES TO CLASSES - TANGLE
In this case, the Target abstract class has unnecessary references to concrete
classes; instead of overloading, could be specific method calls instead
package main;
abstract class Target {
public abstract void genCode(Constant constant);
public abstract void genCode(Plus plus);
public abstract void genCode(Mult mult);
}
class JVMTarget extends Target {
public void genCode(Constant constant) {
System.out.println("bipush " + constant.getValue());
}
public void genCode(Plus plus) {
System.out.println("iadd");
}
public void genCode(Mult mult) {
System.out.println("imul");
}
}
class DotNetTarget extends Target {
public void genCode(Constant constant) {
System.out.println("ldarg " + constant.getValue());
}
public void genCode(Plus plus) {
System.out.println("add");
}
public void genCode(Mult mult) {
System.out.println("mul");
}
}
abstract class ExprNode {
protected static Target target = new JVMTarget();
public static void setTarget(Target newTarget) {
target = newTarget;
}
public abstract void genCode();
}
class Constant extends ExprNode {
int val;
public Constant(int arg) {
val = arg;
}
public int getValue() {
return val;
}
public void genCode() {
target.genCode(this);
}
}
UNNECESSARY REFERENCES TO CLASSES - TANGLE - FIX
abstract class Target {
public abstract void genCodeConstant(int constValue);
public abstract void genCodePlus();
public abstract void genCodeMult();
}
class JVMTarget extends Target {
public void genCodeConstant(int constValue) {
System.out.println("bipush " + constValue);
}
public void genCodePlus() {
System.out.println("iadd");
}
public void genCodeMult() {
System.out.println("imul");
}
}
abstract class Target {
public abstract void genCode(Constant constant);
public abstract void genCode(Plus plus);
public abstract void genCode(Mult mult);
}
class JVMTarget extends Target {
public void genCode(Constant constant) {
System.out.println("bipush " + constant.getValue());
}
public void genCode(Plus plus) {
System.out.println("iadd");
}
public void genCode(Mult mult) {
System.out.println("imul");
}
}
By making the Target class not refer to the concrete ExprNode classes, the
tangle is gone!
SUMMARY - STRATEGIES FOR BREAKING CLASS TANGLES
Cause(s) Potential Solution(s)
References among concrete classes
causes cycle(s)/tangle(s)
Depend on the interfaces than on the
concrete classes (extract interfaces
if they are absent)
A base class refers to one or more
of its derived class(es) causing
tangle(s) (e.g., base class creates
objects of its derived types)
Remove the offending references
from base class to the derived
class(es) (e.g., move the object
creation to a dedicated factory class)
Unnecessary references to classes
causes tangles
Remove the unnecessary references
REFACTORING PACKAGE TANGLES
INTERFACE & IMPLEMENTATION PACKAGED TOGETHER
Packaging the interface & corresponding implementation together causes tangle!
package buyers;
import buyables.Buyable;
import java.util.List;
interface Buyer {}
public class Customer implements Buyer {
List<Buyable> orders;
}
package buyables;
interface Buyable {}
public class Order implements Buyable {
Buyer purchaser;
}
INTERFACE & IMPLEMENTATION PACKAGED TOGETHER - FIX
Separating the interfaces as a separate package (from the
implementation package) disentangles the structure!
MISPLACED ENTITY - PACKAGE TANGLE
An entity misplaced in a package causes a tangle (where does enum
ImageType belong? In the “factory” package or “image” package?
package image;
import factory.ImageType;
public abstract class Image {
public abstract ImageType getType();
}
package factory;
public enum ImageType { JPEG, BMP, PNG }
package imagetypes;
import factory.ImageType;
import image.Image;
public class BMPImage extends Image {
public BMPImage(String name) {
super();
}
public ImageType getType() {
return ImageType.BMP;
}
}
MISPLACED ENTITY - PACKAGE TANGLE - FIX
Here, the entity “enum ImageType” arguably belongs better in “image”
package than in the “factory” package (moving the enum breaks the tangle)
MIXED PACKAGE - PACKAGE TANGLE
Here, the Expr class and the builder class ExprBuilder (that builds objects) are put
together in the same “core” package - this results in a tangle
package core;
import nodes.*;
public class ExprBuilder {
private Expr expr = null;
public ExprBuilder() {}
public ExprBuilder Const(int arg) {
expr = Constant.make(arg);
return this;
}
public ExprBuilder Plus(int arg) {
expr = new Addition(expr, Constant.make(arg));
return this;
}
public ExprBuilder Mult(int arg) {
expr = new Multiplication(expr, Constant.make(arg));
return this;
}
public Expr Build() {
return expr;
}
}
MIXED PACKAGE - PACKAGE TANGLE - FIX
The tangle is broken by splitting the 

“core” package into two packages (“core” and “builder”)
SUMMARY - STRATEGIES FOR BREAKING PACKAGE TANGLES
Cause(s) Potential Solution(s)
Interfaces and implementations are
mixed together
Separate the interfaces and
implementations to separate
packages
A class is misplaced in a package
causing a tangle
Move the offending class to a more
suitable package
Classes that may not belong
together packaged into a single
package cause a tangle
Split the package
www.codeops.tech
www.konfhub.com
www.designsmells.com

Mais conteúdo relacionado

Mais procurados

Mais procurados (11)

Swings in java
Swings in javaSwings in java
Swings in java
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Mieux programmer grâce aux design patterns
Mieux programmer grâce aux design patternsMieux programmer grâce aux design patterns
Mieux programmer grâce aux design patterns
 
GWT Widgets
GWT WidgetsGWT Widgets
GWT Widgets
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.Chat application in java using swing and socket programming.
Chat application in java using swing and socket programming.
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swing
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
 
CRM Science - Dreamforce '14: Generic Package Extension Architecture for App...
CRM Science - Dreamforce '14:  Generic Package Extension Architecture for App...CRM Science - Dreamforce '14:  Generic Package Extension Architecture for App...
CRM Science - Dreamforce '14: Generic Package Extension Architecture for App...
 
Java swing
Java swingJava swing
Java swing
 

Semelhante a Modularization Strategies - Fixing Class and Package Tangles

VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Anton Arhipov
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 

Semelhante a Modularization Strategies - Fixing Class and Package Tangles (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
SOLID principles with Typescript examples
SOLID principles with Typescript examplesSOLID principles with Typescript examples
SOLID principles with Typescript examples
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Inheritance
InheritanceInheritance
Inheritance
 
Java interface
Java interfaceJava interface
Java interface
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
 
droidparts
droidpartsdroidparts
droidparts
 
Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4Effective java-3rd-edition-ch4
Effective java-3rd-edition-ch4
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
MVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsMVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) Details
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 

Mais de CodeOps Technologies LLP

Mais de CodeOps Technologies LLP (20)

AWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetupAWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetup
 
Understanding azure batch service
Understanding azure batch serviceUnderstanding azure batch service
Understanding azure batch service
 
DEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNINGDEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNING
 
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONSSERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
 
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSBUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
 
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESAPPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
 
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPSBUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
 
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNERCREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
 
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
 
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESSWRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh SharmaTraining And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
 
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu SalujaDeploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
 
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
 
YAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra KhareYAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra Khare
 
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
 
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta JhaMonitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
 
Jet brains space intro presentation
Jet brains space intro presentationJet brains space intro presentation
Jet brains space intro presentation
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Distributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps FoundationDistributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps Foundation
 
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire  "Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

Modularization Strategies - Fixing Class and Package Tangles

  • 1. MODULARIZING STRATEGIES: FIXING CLASS & PACKAGE TANGLES ganesh samarthyam (ganesh@codeops.tech)
  • 2. WHAT’S A “TANGLE”? ➤ “A tangle is a portion of a dependency graph within which all the items are directly or indirectly dependent on all the other nodes in the tangle.” (Source: structure101.com) Example of a class tangle (cycle) Example of a package tangle
  • 3. REMOVING TANGLES - VISUALISING IN STRUCTURE101
  • 5. DEPENDENCIES BETWEEN CONCRETE CLASSES - TANGLE import java.util.List; public class Customer { List<Order> orders; } class Order { Customer purchaser; } A direct cyclic dependency between the Customer & Order class because they contain instances of each other’s type
  • 6. DEPENDENCIES BETWEEN CONCRETE CLASSES - TANGLE - FIX import java.util.List; public class Customer { List<Order> orders; } class Order { Customer purchaser; } Depend on the interface instead of the implementation (and the cycle is gone) import java.util.List; interface Buyer {} public class Customer implements Buyer { List<Buyable> orders; } interface Buyable {} class Order implements Buyable { Buyer purchaser; }
  • 7. BASE CLASS REFERS TO ITS DERIVED TYPES(S) enum ImageType { JPEG, BMP, PNG }; abstract class Image { public static Image getImage(ImageType imageType, String name) { switch (imageType) { // JPEGImage, BMPImage, PNGImage are // derived classes of the abstract class Image case JPEG: return new JPEGImage(name); case BMP: return new BMPImage(name); case PNG: return new PNGImage(name); } return null; } } This is a special kind of cyclic dependency - the base type knows about its derived type! Here it is creation of its derived objects results in a tangle
  • 8. BASE CLASS REFERS TO ITS DERIVED TYPES(S) - FIX It’s easy to break this cyclic dependency - move the getImage() method to a dedicated class named ImageFactory!
  • 9. AVOIDABLE REFERENCES TO CLASSES - TANGLE In this case, the Target abstract class has unnecessary references to concrete classes; instead of overloading, could be specific method calls instead package main; abstract class Target { public abstract void genCode(Constant constant); public abstract void genCode(Plus plus); public abstract void genCode(Mult mult); } class JVMTarget extends Target { public void genCode(Constant constant) { System.out.println("bipush " + constant.getValue()); } public void genCode(Plus plus) { System.out.println("iadd"); } public void genCode(Mult mult) { System.out.println("imul"); } } class DotNetTarget extends Target { public void genCode(Constant constant) { System.out.println("ldarg " + constant.getValue()); } public void genCode(Plus plus) { System.out.println("add"); } public void genCode(Mult mult) { System.out.println("mul"); } } abstract class ExprNode { protected static Target target = new JVMTarget(); public static void setTarget(Target newTarget) { target = newTarget; } public abstract void genCode(); } class Constant extends ExprNode { int val; public Constant(int arg) { val = arg; } public int getValue() { return val; } public void genCode() { target.genCode(this); } }
  • 10. UNNECESSARY REFERENCES TO CLASSES - TANGLE - FIX abstract class Target { public abstract void genCodeConstant(int constValue); public abstract void genCodePlus(); public abstract void genCodeMult(); } class JVMTarget extends Target { public void genCodeConstant(int constValue) { System.out.println("bipush " + constValue); } public void genCodePlus() { System.out.println("iadd"); } public void genCodeMult() { System.out.println("imul"); } } abstract class Target { public abstract void genCode(Constant constant); public abstract void genCode(Plus plus); public abstract void genCode(Mult mult); } class JVMTarget extends Target { public void genCode(Constant constant) { System.out.println("bipush " + constant.getValue()); } public void genCode(Plus plus) { System.out.println("iadd"); } public void genCode(Mult mult) { System.out.println("imul"); } } By making the Target class not refer to the concrete ExprNode classes, the tangle is gone!
  • 11. SUMMARY - STRATEGIES FOR BREAKING CLASS TANGLES Cause(s) Potential Solution(s) References among concrete classes causes cycle(s)/tangle(s) Depend on the interfaces than on the concrete classes (extract interfaces if they are absent) A base class refers to one or more of its derived class(es) causing tangle(s) (e.g., base class creates objects of its derived types) Remove the offending references from base class to the derived class(es) (e.g., move the object creation to a dedicated factory class) Unnecessary references to classes causes tangles Remove the unnecessary references
  • 13. INTERFACE & IMPLEMENTATION PACKAGED TOGETHER Packaging the interface & corresponding implementation together causes tangle! package buyers; import buyables.Buyable; import java.util.List; interface Buyer {} public class Customer implements Buyer { List<Buyable> orders; } package buyables; interface Buyable {} public class Order implements Buyable { Buyer purchaser; }
  • 14. INTERFACE & IMPLEMENTATION PACKAGED TOGETHER - FIX Separating the interfaces as a separate package (from the implementation package) disentangles the structure!
  • 15. MISPLACED ENTITY - PACKAGE TANGLE An entity misplaced in a package causes a tangle (where does enum ImageType belong? In the “factory” package or “image” package? package image; import factory.ImageType; public abstract class Image { public abstract ImageType getType(); } package factory; public enum ImageType { JPEG, BMP, PNG } package imagetypes; import factory.ImageType; import image.Image; public class BMPImage extends Image { public BMPImage(String name) { super(); } public ImageType getType() { return ImageType.BMP; } }
  • 16. MISPLACED ENTITY - PACKAGE TANGLE - FIX Here, the entity “enum ImageType” arguably belongs better in “image” package than in the “factory” package (moving the enum breaks the tangle)
  • 17. MIXED PACKAGE - PACKAGE TANGLE Here, the Expr class and the builder class ExprBuilder (that builds objects) are put together in the same “core” package - this results in a tangle package core; import nodes.*; public class ExprBuilder { private Expr expr = null; public ExprBuilder() {} public ExprBuilder Const(int arg) { expr = Constant.make(arg); return this; } public ExprBuilder Plus(int arg) { expr = new Addition(expr, Constant.make(arg)); return this; } public ExprBuilder Mult(int arg) { expr = new Multiplication(expr, Constant.make(arg)); return this; } public Expr Build() { return expr; } }
  • 18. MIXED PACKAGE - PACKAGE TANGLE - FIX The tangle is broken by splitting the 
 “core” package into two packages (“core” and “builder”)
  • 19. SUMMARY - STRATEGIES FOR BREAKING PACKAGE TANGLES Cause(s) Potential Solution(s) Interfaces and implementations are mixed together Separate the interfaces and implementations to separate packages A class is misplaced in a package causing a tangle Move the offending class to a more suitable package Classes that may not belong together packaged into a single package cause a tangle Split the package