SlideShare a Scribd company logo
Get the Most Out of Your Code
Making Your Apex and Visualforce Reusable
Raleigh Chen, USAA, Sr. Software Developer/Integrator
Safe harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties
materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results
expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be
deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other
financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any
statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new
functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our
operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any
litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our
relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our
service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to
larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is
included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent
fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor
Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently
available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions
based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these
forward-looking statements.
Raleigh Chen
Senior Software Developer/Integrator
Enterprise Decision Support Systems
Primary Problem

VS
What Makes Code Reusable?

Flexibility

Genericisation
Case Study Example
Two custom fields on two different objects – similar functionality
▪ Campaign
• Source System
• Subsystem Application

▪ Lead
• IT System (IT Source of Lead)
• Lead Application (Lead Generation Application)
Campaign – Starting Point
Visualforce Page for Campaign
Campaign – Create Component
Generic Object Components allow for a level of
flexibility/genericisation.
▪ Create new Visualforce Component
▪ Replace PageBlock with a Visualforce Component

Tip: The <apex:attribute> tag allows you to pass
values/objects from the visualforce page to the component
COMPONENTIZATION
“replacing a Visualforce Page with a Component allowing for
more flexibility due to the ability to embed Components in other
Pages and pass variables into Components”
Campaign – Add Component Controller
Reusable Logic should live in the Generic Component Controller
▪ Create new Component Controller
▪ Replace the Attribute Object being passed with a more flexible Object
ID

Tip: The assignTo property in the <apex:attribute> tag
allows you to pass values/objects from the Visualforce page
directly to the component’s controller
IDEEIFY
“passing an ID instead of an object or fields from an object to
ensure portability across any object type”
Campaign – Begin to Genericize Controller
Use GlobalDescribe to allow different Objects
▪ Add describe methods necessary for Generic Use
• getGlobalDescribe() – pulls all Object tokens
• getDescribe() – pulls Object details
• getName() – pulls Object Name
• getKeyPrefix() – retrieves the 3 character Object Prefix

▪ Remove Strongly Typed fields from the Visualforce Component
Tip: Using the Dynamic Visualforce Binding Notation
“runObject[fieldName]” allows using variables for field
names.
DESCRIBESPLOSION
“using a generic ID to determine object metadata such as
Object Name, key prefix, etc. without relying on hardcoded values”
DYNAMISUALFORDING
“using Dynamic Visualforce Binding notation to ensure flexibility
in your sObject’s field names so that they can be variablized and
determined at runtime instead of being hardcoded”
Campaign – Create Custom Setting Object
Custom Settings allow for faster access to metadata for mappings,
settings, environment variables, etc.
▪ Define a new Custom Setting

Tip: Custom Settings prevent developers from having to
alter code as it moves from environment to environment
Campaign – Add Campaign Entry to Custom Setting
The entry will map the 3 character Object Prefix to all the Object
specific information we need
▪ Define Object and Field Name fields

▪ Set Values for Campaign
METAFIELD METANAMING METADATA
“storing the field names that are needed to refer to an object
within another reference object, such as a Custom Setting so that
the fields that are used can be changed and new possible objects
added without code changes”
Campaign – Finalize Controller
Remove all mention of any specific Objects/Field Names
▪ Utilize Custom Setting to get Object/Field Names based on passed
Record ID

Tip: The getInstance() method of a Custom Setting allows
for quick retrieval of a row of data based on the Name.
DEPROPERIZE
“ensuring that there is no hardcoded object names or field
names (except for the Custom Setting object and fields) to ensure
that the component can be used with ANY object”
Lead – Try it out for Lead!
Create the same Page for Leads
▪ Add entry in Custom Settings for Lead
▪ Add Leads Visualforce Page
Review
Visualforce Components
▪

<c:component_name attribute_name=“{!value}” />

▪

<apex:attribute name="objID" description="The object ID" required="true" type="String" assignTo="{!
objectID}“

Dynamic Visualforce Field Bindings
▪

<apex:inputField value="{!object_name[field_name_variable]}" />

Describe Functions
▪

getGlobalDescribe()

▪

getDescribe()

▪

getName()

▪

getKeyPrefix()
Review (cont.)
Custom Settings
▪

Definition/Usage

▪

Custom_Setting_Object_Name.getInstance(rowName)

▪

Custom_Setting_Object_Name.getAll()
Raleigh Chen
Sr. Software
Developer/Integrator,
USAA
Chatter Challenge
On Chatter, Submit an example of this type of genericisation using
the new Fieldset.
Winner gets a gold star.
Making Your Apex and Visualforce Reusable

More Related Content

PDF
Banco de Dados II Projeto Final de Banco de Dados
PPTX
소프트웨어공학 프로젝트 최종발표.pptx
ODP
Devops Devops Devops
PPT
Introduction to Git Commands and Concepts
PDF
Tóm tắt lệnh Ubuntu
PDF
Introduction to Git
PDF
Virtualization – Proxmox
PPTX
Git n git hub
Banco de Dados II Projeto Final de Banco de Dados
소프트웨어공학 프로젝트 최종발표.pptx
Devops Devops Devops
Introduction to Git Commands and Concepts
Tóm tắt lệnh Ubuntu
Introduction to Git
Virtualization – Proxmox
Git n git hub

What's hot (20)

PDF
Cloud computing foundation
PPTX
What is Exception Handling?
PDF
Aula 01 - UML e Padrões de Projeto
PDF
Sapo Microservices Architecture
PDF
z16 zOS Support - March 2023 - SHARE in Atlanta.pdf
PPTX
OMEGAMON XE for z/OS V530 Long client presentation
DOCX
Content server installation guide
PPTX
Distributed Transaction in Microservice
PDF
[AWS Dev Day] 앱 현대화 | DevOps 개발자가 되기 위한 쿠버네티스 핵심 활용 예제 알아보기 - 정영준 AWS 솔루션즈 아키...
PDF
Introduzione a Git
PDF
[오픈소스컨설팅]Zabbix Installation and Configuration Guide
PPTX
Tìm hiểu và triển khai ứng dụng Web với Kubernetes
PDF
Linux Directory Structure
PDF
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
PPTX
JSON.pptx
PDF
XPDDS18: EPT-Based Sub-page Write Protection On Xenc - Yi Zhang, Intel
PDF
PUBG: Battlegrounds 라이브 서비스 EKS 전환 사례 공유 [크래프톤 - 레벨 300] - 발표자: 김정헌, PUBG Dev...
PDF
Documenting Software Architectures
PDF
(발표자료) CentOS EOL에 따른 대응 OS 검토 및 적용 방안.pdf
Cloud computing foundation
What is Exception Handling?
Aula 01 - UML e Padrões de Projeto
Sapo Microservices Architecture
z16 zOS Support - March 2023 - SHARE in Atlanta.pdf
OMEGAMON XE for z/OS V530 Long client presentation
Content server installation guide
Distributed Transaction in Microservice
[AWS Dev Day] 앱 현대화 | DevOps 개발자가 되기 위한 쿠버네티스 핵심 활용 예제 알아보기 - 정영준 AWS 솔루션즈 아키...
Introduzione a Git
[오픈소스컨설팅]Zabbix Installation and Configuration Guide
Tìm hiểu và triển khai ứng dụng Web với Kubernetes
Linux Directory Structure
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
JSON.pptx
XPDDS18: EPT-Based Sub-page Write Protection On Xenc - Yi Zhang, Intel
PUBG: Battlegrounds 라이브 서비스 EKS 전환 사례 공유 [크래프톤 - 레벨 300] - 발표자: 김정헌, PUBG Dev...
Documenting Software Architectures
(발표자료) CentOS EOL에 따른 대응 OS 검토 및 적용 방안.pdf
Ad

Similar to Making Your Apex and Visualforce Reusable (20)

PPTX
Force.com Friday - Intro to Visualforce
PDF
Summer '13 Developer Preview Webinar
PPTX
Javascript and Remote Objects on Force.com Winter 15
PPTX
Force.com Friday: Intro to Visualforce (May 8, 2015)
PDF
Looking under the hood of your org with eclipse
PDF
Force.com Friday: Intro to Force.com
PDF
Winter 14 Release Developer Preview
PPTX
Mastering Force.com: Advanced Visualforce
PPTX
Coding Apps in the Cloud with Force.com - Part 2
PPTX
Force.com Friday : Intro to Visualforce
PDF
Elevate london dec 2014.pptx
PPTX
Spring ’15 Release Preview - Platform Feature Highlights
PDF
Salesforce Spring'15 release overview
PDF
Introduction to Visualforce
PPTX
Elevate Tel Aviv
PPTX
5 Easy Ways to Make Your Org Instantly More User Friendly
PDF
Spring '14 Release Developer Preview Webinar
PDF
Introduction to Visualforce
PDF
Intro to Apex Programmers
PDF
Manage Development in Your Org with Salesforce Governance Framework
Force.com Friday - Intro to Visualforce
Summer '13 Developer Preview Webinar
Javascript and Remote Objects on Force.com Winter 15
Force.com Friday: Intro to Visualforce (May 8, 2015)
Looking under the hood of your org with eclipse
Force.com Friday: Intro to Force.com
Winter 14 Release Developer Preview
Mastering Force.com: Advanced Visualforce
Coding Apps in the Cloud with Force.com - Part 2
Force.com Friday : Intro to Visualforce
Elevate london dec 2014.pptx
Spring ’15 Release Preview - Platform Feature Highlights
Salesforce Spring'15 release overview
Introduction to Visualforce
Elevate Tel Aviv
5 Easy Ways to Make Your Org Instantly More User Friendly
Spring '14 Release Developer Preview Webinar
Introduction to Visualforce
Intro to Apex Programmers
Manage Development in Your Org with Salesforce Governance Framework
Ad

More from Salesforce Developers (20)

PDF
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
PDF
Maximizing Salesforce Lightning Experience and Lightning Component Performance
PDF
Local development with Open Source Base Components
PPTX
TrailheaDX India : Developer Highlights
PDF
Why developers shouldn’t miss TrailheaDX India
PPTX
CodeLive: Build Lightning Web Components faster with Local Development
PPTX
CodeLive: Converting Aura Components to Lightning Web Components
PPTX
Enterprise-grade UI with open source Lightning Web Components
PPTX
TrailheaDX and Summer '19: Developer Highlights
PDF
Live coding with LWC
PDF
Lightning web components - Episode 4 : Security and Testing
PDF
LWC Episode 3- Component Communication and Aura Interoperability
PDF
Lightning web components episode 2- work with salesforce data
PDF
Lightning web components - Episode 1 - An Introduction
PDF
Migrating CPQ to Advanced Calculator and JSQCP
PDF
Scale with Large Data Volumes and Big Objects in Salesforce
PDF
Replicate Salesforce Data in Real Time with Change Data Capture
PDF
Modern Development with Salesforce DX
PDF
Get Into Lightning Flow Development
PDF
Integrate CMS Content Into Lightning Communities with CMS Connect
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Local development with Open Source Base Components
TrailheaDX India : Developer Highlights
Why developers shouldn’t miss TrailheaDX India
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Converting Aura Components to Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
TrailheaDX and Summer '19: Developer Highlights
Live coding with LWC
Lightning web components - Episode 4 : Security and Testing
LWC Episode 3- Component Communication and Aura Interoperability
Lightning web components episode 2- work with salesforce data
Lightning web components - Episode 1 - An Introduction
Migrating CPQ to Advanced Calculator and JSQCP
Scale with Large Data Volumes and Big Objects in Salesforce
Replicate Salesforce Data in Real Time with Change Data Capture
Modern Development with Salesforce DX
Get Into Lightning Flow Development
Integrate CMS Content Into Lightning Communities with CMS Connect

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
A Presentation on Artificial Intelligence
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
20250228 LYD VKU AI Blended-Learning.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MIND Revenue Release Quarter 2 2025 Press Release
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Agricultural_Statistics_at_a_Glance_2022_0.pdf
cuic standard and advanced reporting.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
sap open course for s4hana steps from ECC to s4
Review of recent advances in non-invasive hemoglobin estimation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Unlocking AI with Model Context Protocol (MCP)
A Presentation on Artificial Intelligence

Making Your Apex and Visualforce Reusable

  • 1. Get the Most Out of Your Code Making Your Apex and Visualforce Reusable Raleigh Chen, USAA, Sr. Software Developer/Integrator
  • 2. Safe harbor Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3. Raleigh Chen Senior Software Developer/Integrator Enterprise Decision Support Systems
  • 5. What Makes Code Reusable? Flexibility Genericisation
  • 6. Case Study Example Two custom fields on two different objects – similar functionality ▪ Campaign • Source System • Subsystem Application ▪ Lead • IT System (IT Source of Lead) • Lead Application (Lead Generation Application)
  • 7. Campaign – Starting Point Visualforce Page for Campaign
  • 8. Campaign – Create Component Generic Object Components allow for a level of flexibility/genericisation. ▪ Create new Visualforce Component ▪ Replace PageBlock with a Visualforce Component Tip: The <apex:attribute> tag allows you to pass values/objects from the visualforce page to the component
  • 9. COMPONENTIZATION “replacing a Visualforce Page with a Component allowing for more flexibility due to the ability to embed Components in other Pages and pass variables into Components”
  • 10. Campaign – Add Component Controller Reusable Logic should live in the Generic Component Controller ▪ Create new Component Controller ▪ Replace the Attribute Object being passed with a more flexible Object ID Tip: The assignTo property in the <apex:attribute> tag allows you to pass values/objects from the Visualforce page directly to the component’s controller
  • 11. IDEEIFY “passing an ID instead of an object or fields from an object to ensure portability across any object type”
  • 12. Campaign – Begin to Genericize Controller Use GlobalDescribe to allow different Objects ▪ Add describe methods necessary for Generic Use • getGlobalDescribe() – pulls all Object tokens • getDescribe() – pulls Object details • getName() – pulls Object Name • getKeyPrefix() – retrieves the 3 character Object Prefix ▪ Remove Strongly Typed fields from the Visualforce Component Tip: Using the Dynamic Visualforce Binding Notation “runObject[fieldName]” allows using variables for field names.
  • 13. DESCRIBESPLOSION “using a generic ID to determine object metadata such as Object Name, key prefix, etc. without relying on hardcoded values”
  • 14. DYNAMISUALFORDING “using Dynamic Visualforce Binding notation to ensure flexibility in your sObject’s field names so that they can be variablized and determined at runtime instead of being hardcoded”
  • 15. Campaign – Create Custom Setting Object Custom Settings allow for faster access to metadata for mappings, settings, environment variables, etc. ▪ Define a new Custom Setting Tip: Custom Settings prevent developers from having to alter code as it moves from environment to environment
  • 16. Campaign – Add Campaign Entry to Custom Setting The entry will map the 3 character Object Prefix to all the Object specific information we need ▪ Define Object and Field Name fields ▪ Set Values for Campaign
  • 17. METAFIELD METANAMING METADATA “storing the field names that are needed to refer to an object within another reference object, such as a Custom Setting so that the fields that are used can be changed and new possible objects added without code changes”
  • 18. Campaign – Finalize Controller Remove all mention of any specific Objects/Field Names ▪ Utilize Custom Setting to get Object/Field Names based on passed Record ID Tip: The getInstance() method of a Custom Setting allows for quick retrieval of a row of data based on the Name.
  • 19. DEPROPERIZE “ensuring that there is no hardcoded object names or field names (except for the Custom Setting object and fields) to ensure that the component can be used with ANY object”
  • 20. Lead – Try it out for Lead! Create the same Page for Leads ▪ Add entry in Custom Settings for Lead ▪ Add Leads Visualforce Page
  • 21. Review Visualforce Components ▪ <c:component_name attribute_name=“{!value}” /> ▪ <apex:attribute name="objID" description="The object ID" required="true" type="String" assignTo="{! objectID}“ Dynamic Visualforce Field Bindings ▪ <apex:inputField value="{!object_name[field_name_variable]}" /> Describe Functions ▪ getGlobalDescribe() ▪ getDescribe() ▪ getName() ▪ getKeyPrefix()
  • 24. Chatter Challenge On Chatter, Submit an example of this type of genericisation using the new Fieldset. Winner gets a gold star.