Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Friday, November 17, 2017

The Eisenhower Matrix Fallacy

Road trips reveal truths and clarify ideas, at least that's what my Auntie Pat Tern insists. On a recent trip with her and cousin Tim Toady,  this came up when Tim requested a bathroom stop. What he said was, "I could use a bathroom some time soon." And as we flew past exit after exit, Auntie Pat Tern said he should let her know if it becomes urgent, otherwise she wanted to find a good spot to stop for lunch too. That got me thinking about competing interests when it comes to programming and the Fallacy of the Eisenhower Matrix.

Jastrow, J. (1899). Popular Science Monthly US public domain
Duck or Rabbit? It may depend on how long

you allow yourself to analyze the problem.
In a speech at Northwestern University, President Dwight D. Eisenhower said "I have two kinds of problems, the urgent and the important. The urgent are not important, and the important are never urgent. "   


Prioritizing Competing Requirements

Important issues and urgent ones often compete. On our road trip, Auntie Pat Tern knew that a nice place to stop for lunch would also have a nice bathroom, that was part of her selection criteria. She also wanted to get as far as possible to her ultimate goal before the end of the day. Stopping both for lunch and for a separate bathroom pit-stop would delay her from reaching her ultimate goal. So she employed the Eisenhower statement as it was intended, to express that a thing cannot be both urgent and important.

Unfortunately, a lot of people in the business world have worked Eisenhower's statement into a matrix, which suggests that requirements can be both urgent and important.  Trying to accomplish a task as both important and urgent makes no sense. If it is important enough to need an optimal solution, then take the time to discover that optimal solution. If it is urgent enough to resolve immediately, do your best with what you have right now.

Importance means you have the time to be thoughtful and take time to discover the most optimal solution; it is the polar opposite of urgency.

As long as stopping for a bathroom break was important, it was worth waiting for the best location to stop both for food, which was also important, and for clean restrooms. But as soon as the need for a bathroom became urgent, the competing priority for food could be disregarded, at least to some extent. And with greater urgency, even the competing priority for a clean restroom might be set aside; the greatest urgency means you act now even if you have to pull off the road at that tree up ahead.

Eisenhower and Software Architecture 

For software architecture, the urgent and the important need to be kept separate because the important parts of the project should inevitably be the most stable code in the system. The least stable code is the stuff you write out of urgency, when things are likely to change, but we can't wait until we understand all the factors that cause change.

Don't believe the Eisenhower Matrix, it is a fallacy. Important and Urgent are like North and South ends of a magnet. Anything that is equally Important and Urgent lies in the middle, and that part of the magnet is neutral. The neutral zone is where we find the mindless and repetitive tasks that only become urgent when they are neglected for too long and only become important when something out of the ordinary arises.

For Tim Toady on our road trip, he appreciated waiting for a sandwich on Dutch Crunch and a clean restroom because he values good food; it's important as long as he doesn't have more urgent needs.

Sunday, November 12, 2017

Why Coders Use Interfaces

Going on a road trip with Auntie Pat Tern and cousin Tim Toady reveals a lot about them as only a road trip can. Tim was called a "whipper snapper" on more than one occasion for criticizing Auntie Pat Tern's driving. "I cannot wait for self-driving cars," he proclaimed while Auntie Pat Tern praised the freedom of the open road and the control she feels while driving a car. Which got me thinking about why interfaces are so important as part of my programming team's design decisions.

Tim Toady prefers to drive arcade games while Auntie Pat Tern craves a 64 1/2 mustang convertible. But they both drive reasonably well in the electric car they have at home and the gas guzzler we rented for our long drive. That's because the interface of gear shift, accelerator, brake, and steering wheel are universally well understood by users.

Accelerate, brake, steer, and shift.
The simplicity of a good interface.
That same interface translates inputs to a multitude of different systems from arcade games to tractor-trailer trucks. When it comes to deciding whether to accelerate or decelerate, the driver/user does not care if the vehicle is electric or gas-powered. A lot of people who drive electric cars even still say "gas pedal".

Autonomous driving vehicles use the same interface as people: shift, accelerate, brake, steer. By using the same interface, a person can take over in an emergency, or maybe just for the fun of driving.

Developers use good interfaces like this to future-proof their code. If the business rules are protected from the mechanism for inputting data thanks to a reliable interface, we can make sure the most important business rules continue to function as expected.

Sure, sometimes the interface has to change a bit with new business automations. When cars got automatic transmissions, the gear shift changed and we lost the clutch. The same happens with code, new automations require small changes to the programming interface, but the goal of an interface is to minimize the need for such changes. Ultimately, we want to put interfaces between systems to give ourselves flexibility to support new automation, like Tim Toady's self driving car, as easily as we support more manual systems, like Auntie Pat Tern's stick shift.

Friday, March 4, 2016

Start Documenting Rather Than Accepting "No Comment"

My Auntie Pat Tern tried to convince my cousin Tim Toady that he should be using the 3/5 rule of essay writing he'd been taught -- three ideas, five paragraphs -- but, as usual, Tim insisted there is more than one way to do it (TIMTOWTDI). So I looked through the code in my Salesforce org to see if my developers were following the 3/5 rule for comments or if TIMTOWTDI had gotten into our code.  Unfortunately, I mostly found code with no comments at all.

Code without comments is like a research paper without a thesis statement to detail its purpose.  It's like doing something over and over without understanding why because comments should always clarify why it does what it does.  It's like burying treasure without leaving a proper map because good comments point to valuable resources the code uses or makes available.

Code comments should follow the 3/5 rule of comments:  there are three places where comments should occur and five specific topics that need to be addressed.

The three places where comments should be found in Apex code are:
  1. Block comments at the beginning of classes.
  2. Block comments at the beginning of methods.
  3. Line level comments for constants, loops, conditions, and where clarification is possible.
The five topics that should always be found in block comments are:
  1. Description of purpose and assumptions.
  2. Author/date for creation and modification.
  3. Parameters for methods that accept values, or none.
  4. Return values for methods that pass values, or none.
  5. References and dependencies.
Here's an example of code that follows the 3/5 rule of comments:



In this example, block comments appear at the start of the class and at the start of the methods while inline comments appear within methods and for named constants. The comments use Javadoc tags like "@description" to make the important topics easy to locate.  These comments even include "TBD" to indicate code that is incomplete and point out the limitation imposed by the choice of Integer as a data type rather than Long. Comments should always include information that may be reconsidered during the next phase of development.

We ask that developers and admins both be responsible for code comments because the admin should know how code effects data integrity and user experience.  Without that level of cooperation and understanding, admins have been known to implement validation rules that cause code to fail and developers have been known to implement code that causes user experience to decline.

Tim Toady is right, there is more than one way to do it with code.  That's why we ask for comments that explain why the code was written the way it was.  And we follow Auntie Pat Tern's 3/5 rule to make sure we have comments in three areas of code and covering 5 required topics.  Better comments lead to better collaboration and easier maintenance of the code and the org where it runs.

Sunday, February 14, 2016

Poltergeist Busters Get A Call

Auntie Pat Tern mentioned that she loves a good ghost story, so I looked through my code and told her about the Poltergeist object I found there.

Poltergeist objects exist simply for the purpose of passing data from one place to another and are essentially useless.  These objects don't serve a clear function relative to business or technology rules, instead they just take up space.  Poltergeists are unlike Leads, which are required by business rules to hold data until it can be verified and converted to Contacts.  Leads aren't Poltergeists because they service the business rules related to data verification.

The object I found in my code was no Lead, it was a troublesome Poltergeist.
In the above code, the Order object serves no purpose other than passing data from an external system into Salesforce.  Since there is no verification process defined, there doesn't need to be a holding bin for data, and it could be passed directly into the Sales Order object that already existed in our Salesforce org. We can simply refactor the code to write directly to the third-party object rather than the Poltergeist.

Auntie Pat Tern said she's seen a lot of weird stuff, but the code in my org might be the scariest of all.

Thursday, February 11, 2016

When To Soft Code Or Not To Soft Code

My Auntie Pat Tern got mad at my no good cousin when he told her he changes phone numbers every time he gets a new burner phone; she warned us to make sure we do business by the rules.  So I looked through my code and shared her suggestion with my developers.

It turns out they tried to correct a problem with badly implemented hard-coded values by soft-coding some values that represented software architecture decisions and similar business rules.

Previously, I showed you the example of a hard-coded username being assigned as record owner, which caused two problems in the org.  The first problem was that the username needed to be an API-only user rather than an employee who might leave the company whose username would be deactivated.  The second problem was that the username was hard-coded deep in the code rather than being represented as a constant at the beginning of the class.

The developer who tried to fix these problems decided to soft-code the username as follows:

Using Custom Settings allows the username to be changed outside of code at any time, multiple times.  The above example does not solve the first problem we had, though. Unfortunately, soft-coding the username defeats our business rule requiring data coming from integrations to be owned by a user or Queue specific to that integration.  In other words, our business rule required the use of a constant rather than a soft-coded value.

We had to take that code back to the drawing board one more time because, like Auntie Pat Tern demonstrates, code should behave according to the rules of business, and enforce those rules automatically.


Monday, February 1, 2016

Avoiding the Negative for Clear Code

My Auntie Pat Tern recently reminded me to avoid double negatives and use positive language as often as possible. So I looked through some of the code in my org and decided to share her advice with my developers. When we write conditional statements using NOT (or "!"), we are using negative syntax which is more difficult to understand than positive syntax. Here's an example written in negative syntax, then rewritten in positive syntax:

The conditions evaluate the same, but I find the negative syntax more difficult to read during code review and maintenance. Note that it can be improved upon further with a basic knowledge of String methods.

The first time I encountered super negative syntax, I thought the developers who used it were making a game of being abstruse.  But knowing that the two programmers were friends led me to discover that this was in fact a case of "cargo cult programming" where they were sharing and reusing a bad pattern because they hadn't taken the time to pick apart what the code needed to accomplish. Once they better understood what the code was doing, they learned to write it more clearly.

Sunday, August 16, 2015

Rethink Salesforce Projects With Great Administration Techniques

System administrators are getting more tools with even greater power with every new Salesforce release.  Tools like Lightning App Builder, Process Builder and Visual Flow work like visual programming tools.  They offer clicks-not-code solutions that can bring down project costs of time and expertise by eliminating the need for developer involvement in the creation and maintenance of all but the most complex projects.

This year at Dreamforce, I will be helping admins learn skills they can use to better plan and implement projects in their orgs.  Please look for my sessions here:

Getting To Know Visual Workflow (Tuesday session)

and

Getting To Know Visual Workflow (Thursday session)

Choose either of these sessions to learn about this powerful tool.  It requires no coding experience to use, but works like a visual programming tool enabling you to improve user interface and user experience, manage data consistency and integrity, and automate business processes without needing to write any code.

7 Essential Tips Every Admin Should Know About Apex

Whether you are working with in-house developers or hiring contractors, learn what to look for to ensure the code you are getting follows best practices and meets your needs.  This session will introduce you to concepts that will help ensure the overall health of your org and help you to work better with developers.

Trailhead Gladiators

Join us for these fun sessions on Tuesday, Wednesday, and Thursday to discover how Trailhead helps you stretch your skills.  You may be able to win prizes, but best of all, you will see what Trailhead has to offer as a learning tool.  And with more knowledge, everyone's a winner.

Tuesday, July 14, 2015

Agree on Guidelines Before Adding Code

Remember how your high school and college research papers were graded partly on niggling formatting concerns?  The point was to make sure we all used ibid, idem, op. cit. and loc. cit. correctly.  By getting us all following the same style, the teacher had an easier job understanding our work and we learned to better understand the work of others.  These are the same reason you should define code guidelines for your Salesforce org.
A good style guide provides grounding
without weighing you down.

Whether you are a Salesforce Administrator who works with vendors for your development needs or an in-house developer yourself, documenting basic code style and guidelines for your org should be considered a must.  Code guidelines help ensure that the code can be maintained for years to come and that the org is well documented down to the code level so that admins and developers alike have a thorough understanding of what takes place in the org.

A lot of Apex programmers start with the Google Java Style Guide, which is a great starting point, but you may want to create something brief to share among everyone writing code for your org.  Here are some suggestions for a brief Apex Style Guide:

Style

  1. Avoid unnecessary whitespace.  Whitespace is helpful for indicated blocks of code, using indentations at the beginnings of lines or blank lines before methods, for example.  But whitespace inside of lines of code adds to maintenance time.
  2. Use tab rather than spaces for indenting lines of code to ensure they line up properly and reduce character count.  Indent lines of code within a method by one level from the method.  Indent the code contained by a loop by one level from the line that sets up the loop, for example.
  3. Limit code to 100 columns wide, even in comments so that it can be read without scrolling.
  4. Break SOQL statements into multiple lines with new lines for each clause: From, Where, Order By, etc.  Selected fields should be listed in ascending alphabetical order.

  5.   Map<id,account> aMap = new Map<id,account>([SELECT Id,Name 
                                                  FROM Account 
                                                  LIMIT 50000]);

  6. Comments should appear at the beginning of every class and at the beginning of every method in block format (/* */).  
  7. At the beginning of each class, comments should
    • describe purpose and list related files (classes, triggers, components, VF pages, etc either called by or that will be calling this file) as well as HTTP services called, if any
    • list author name(s) and creation date
    • include modification dates and authors and purpose of modifications
    • list business processes in order they are addressed in the code as a brief summary of methods.
  8. At the beginning of each method, comments should
    • Describe purpose and detail parameters and returned values.
  9. Trigger logic should be contained in at least two files: the Trigger and the Handler(s) containing the business logic.
  10. All code should be ‘bulkified’ to avoid exceeding governor limits when multiple records are processed, at the very least, SOQL and DML statements should only appear outside of loops.

Naming Conventions

  1. File names should begin with a Primary sObject name, followed by a description of the action the code performs, followed by the type of class (eg. Controller, Extension, Helper, Utility, Test, Trigger).  For example, you might have the AccountAddressUpdate Visualforce page and the AccountAddressUpdateExtension controller extension.
  2. Avoid spaces and underscores in file, class, method and variable names.  Also avoid abbreviations when possible.  
  3. Method names begin with a lowercase verb.
  4. Classes should use camel case (eg. CamelCase) while Methods and Variables should use nerd case (eg. modifiedCamelCase).  You could have a controller extension class called AccountAddressUpdateExtension with method updateAddress and variable newStreet, as an example.
  5. Use all caps for constants such as MAXIMUM and MINIMUM.  Constants should be placed after the class header comments and before the first method and method header comments so they can be easily located and updated.
  6. Append “Test” to the class name for all test classes.  For example, the class AccountAddressUpdateExtension would have a corresponding AccountAddressUpdateExtensionTest. 
  7. Collection variables should be plural or otherwise represent the fact that they represent a collection (eg. recordMap, newAccountMap).

Deployment

  1. Remove System.debug statements before pushing code to production.
  2. Require positive and negative scenarios in unit tests using assertions that are clear. 
  3. Salesforce defines minimum code coverage as 75% but we prefer minimum code coverage of 90%.

Fundamentals

  1. For integrations, employ a 'single source of truth' model where possible—data should be stored in one location and referenced by other systems or pulled on an as needed basis only. A redundant system should be created for backup purposes, but should not be used as a data source except in the event of failure recovery. 
  2. Follow the rule of 3 and the abstraction principle. If the same code is used 3 or more times, it needs to be implemented as a reusable class, method or loop. Programmers sometimes refer to this as DRY v WET : "Don’t Repeat Yourself" vs "We Enjoy Typing"). Create abstract code for reusable procedures.

Friday, December 5, 2014

Get Ready Glossary for Administrators Learning to Code

If you are and administrator learning to code, you already know more than you may realize.  I've started preparing a glossary to help you with programming terms by giving you similar examples from your daily tasks as a Salesforce Administrator.

Database customization and coding, it's all connected.
  • Data Types:  When you create custom fields, you have to specify a data type: Date, Text, Currency, Number, etc.
  • Polymorphism:  When you use "+" in a formula for two text fields, it concatenates, when you use it in a formula with two number fields it adds them.  This different behavior in different scenarios is polymorphism at work.
  • Variables:  Fields that let users input values are variables.  They can be changed if needed, just look for the label you gave and edit the data.
  • Constants:  Your org ID is a great example of a constant.  It's a value that will not change in your org.
  • Objects:  Okay, this is confusing.  When you start programming, you will see that Salesforce objects are now referred to as SObjects.  This is because object oriented programming languages use the term Objects to represent data collections.  Oh, hey, that's what objects are in Salesforce too, basically.  Only oop objects can also have actions related to them, things that you can do to them or things that they can do to other objects.  Oh, hey, sObjects are the same if you think about workflows as actions that are related to specific objects and think of triggers as actions that let one sObject act on another sObject.  So maybe this isn't confusing at all.
  • Array:  In the Salesforce database, you have a record ID associated with a bunch of fields -- record name, created date, etc.  This is essentially an array of data. Apex uses the term List rather than Array, but they are the same.  Lists can be multidimensional too.  For example, you can have a list of data from fields for a single contact record, or you can have multiple records in a list and each of those records will have its own list of field values.  List Views are two dimensional lists of data.
  • Cast:  In programming, you can force a variable of a particular data type to be treated like a different data type.  Similarly, in Salesforce, you can use Formulas like Text(PicklistSelection__c) to force a field, in this case a pick list, to be treated like a different type of data, in this case Text.
  • Model-View-Controller:  This is easy for you.  Model is the data model.  When you create custom objects and fields in Salesforce, you are changing the data model, native objects and fields are also part of the data model.  View is the user interface.  When you edit page layouts, you are changing the view.  Controller is any automation.  You might add workflow rules or formulas to affect data based on rules and reasons you define.
  • Boolean data: Think of a checkboxes.  They are true or false, checked or unchecked.
  • Boolean Operators: And, Or.   You may be using these in formulas or in list view filters already.  If you look for this value AND that value, both must be true.  If you look for this value OR that value, only one of them needs to be true, but both true will work as well.
  • SOQL: SObject Query Language lets you express in a few words the kinds of information you already use defining List Views.  For a List View, you sepcify filter criteria for selecting specified fields from the given object.  You might select First and Last Name from Contact with filters looking for records where the phone number is blank, for example.  SOQL lets you express the same sort of thing when programming in Apex, using a few key words.

If you want to write code for Salesforce, Visualforce will handle the View portion, Apex will handle the Controller portion, and Salesforce will continue to handle the Model portion of your program.  You will probably find yourself using data types you are very familiar with from Salesforce fields as you set up variables and constants.  And you will find SOQL easier to understand if you think of them in the context of list views, returning lists or arrays of data you request.

For a more complete introduction to programming for the administrator, please watch this Dreamforce session on coding for non-developers: http://dreamforce.vidyard.com/watch/haqgdyryAtDoQdMsOieTTA

Saturday, November 22, 2014

Learning Coding Skills May Be Easier Than You Think

Last week, I tried to convince you how easy the path can be from Salesforce Administrator to developer.  This week, I'd like to look at a couple of additional resources for the administrator who is beginning to dabble in code.

Don't be afraid to step out of your comfort zone and
try new skills.  You may be better than you think.
As I've mentioned before, Flow, or Visual Workflow, is a lot like a visual programming tool in the ways that it can be used to add complex functionality and alter the Salesforce user interface just by clicking on various programmatic elements.

But you can make Flows even more impactful by employing Visualforce as well.  With Visualforce, you can further customize the user interface and even incorporate HTML, CSS and JavaScript to provide more bells and whistles.

Visualforce also opens the door to more programmatic control over your Flow.  You can create more complex data interactions, such as referencing static resources, by adding an Apex controller to a Visualforce page that calls a Flow.  You can also use a custom Apex controller to specify a variable finish location for the Flow, for example finishing on a newly created record detail page.

I have written about this previously on my blog, here: http://www.snugsfbay.com/2014/04/salesforce-flow-using-record-ids-at.html

You might also be interested in watching a Dreamforce session I co-presented on this topic, which includes all the code you need to customize your Flow from start to finish, including the unit test: http://dreamforce.vidyard.com/watch/7mBX_EQGTTz8pmZeo0724A

Either way, I hope that you'll agree Flow is a great tool for administrators who are interested in expanding their skills and taking on more complex business problems.  And it provides a great stepping stone into learning to code in Visualforce and Apex as well.

Saturday, July 12, 2014

When Not To Use Triggers

For administrators who don't code, hiring a developer to create a trigger can be a frustrating proposition, but what else can you do when you need to automate a business process with Salesforce?

Movie props may need triggers,
but administrators can get by without them.
In my experience, many of the processes I need to automate are triggered by a user action on a single record, or are required in order to update a list of records because of a specific change to the database model.  I may change the data model from using a multiselect picklist to check boxes, for example, and need to update all existing records to set the new check box fields based on existing picklist selections for each record.

Salesforce offers Custom Buttons, Links and Actions for updating a single record from the record detail page.  Perhaps converting a Lead to a Contact, for example.  And Global Actions can act on lists of records, such as when I want to create a new field and populate it in all existing records based on existing data.

To define, within Salesforce, the process that needs to be automated, administrators can use Flow rather than Apex.  Flow lets you retrieve records and manipulate them before saving those records, or new records, to Salesforce.  By embedding a Flow on a Visualforce page, it can handle the automated processing and logic associated with the Action or button.  Here is an example of a Visualforce page to initiate a Flow, named "FlowName":
   <apex:page sidebar="false" showheader="false">
    <flow:interview name="FlowName"/>
   </apex:page>
While Flows are easy to use and don't require programming experience, administrators should still learn to think like developers when creating Flows. Beware of using Flows in your production org without thorough testing first!  You can't develop Apex in your production org, which keeps you from damaging your data while you are developing the logic to automate data manipulation.  You should test your Flows in a Sandbox first to protect your data as well.

In the future, Flows will also be able to work with Triggers, but for now, you can have much of the same functionality at the click of a button.

Monday, February 3, 2014

5 Ways To Get Help With Your Salesforce Problem

Q:  How many different ways can you find help with your Salesforce implementation, administration and development?  A:  Lots!

If something appears to be off, you can easily find help!
Salesforce is so chock-full of features and the thrice-yearly releases offer so many improvements, it can be challenging to keep up.  For administrators who support smaller implementations, they may be the only person trying to keep up with everything that Salesforce can do for your business.  Salesforce has found a way to help with both of these situations by offering multiple avenues for help and support, including making it easy for the community of Salesforce users and administrators to help one another.

When you find yourself in need of help, here are my top five recommendations for finding the answers you need:


1.  Help and Training -- Salesforce offers standard and Premier Support and training for most users.  Help, without training, is offered for users with developer accounts.  Salesforce Help and Training should be your front-line for finding out how to do things in Salesforce.  All of the product documentation is searchable here, including some Best Practice documents.

Premier Support is what you want your support to be like, really.  Open 24 hours a day, they will track down even the craziest problems and solve them for you.  In addition to fantastic support, the online training available with Premier Support includes several of the classes offered in-person by Salesforce University. If you are working on Salesforce certification, you should definitely take a look at these training options!  And developers should note that Premier Support even offers help with code.

2.  The Community -- Let your peers give you a hand.  Online communities, success.salesforce.com and, for nonprofits using the nonprofit starter pack or other nonprofit specific applications, the Power of Us Hub, offer multiple channels for helpful discussions.
  • Answers -- Search for questions that others may have posted on topics of interest to you or post your own questions.  Lots of folks are looking for a Salesforce challenge and would love to answer your questions.  Note that the questions are organized by categories listed on the left side of the page.  For nonprofit organizations, you have an additional avenue for answers through the Power of Us Hub Q&A, a resource for applications and concerns specific to nonprofits.
  • Chatter Groups -- Sometimes, what you really want is to be kept abreast of what's happening and hear ideas from other Salesforce users and administrators.  Chatter Groups provide just that sort of information.  With groups like the Success -- Getting Started and Success -- Release Readiness, among others, you can keep up with Salesforce features.
  • User Groups -- Among the most helpful Chatter Groups, you will find the Salesforce User Groups online as well.  If you find a group in your geographic area, consider signing up for your local group and trying to attend meetings in person to get to know your peers.  Meetings give you an opportunity to ask other administrators, users and developers how easy or difficult a task may be before you try to hire a consultant.  User Groups can also keep you informed about Salesforce features and best practices and third-party application availability as well.
  • Developer Groups -- Like User Groups for developers, these provide opportunities for discussing technical issues and topics.

3.  Developer Community -- the developer boards offer a great place for help with all your Apex and Visualforce needs.  If you are trying to go beyond formulas and workflow, you may have questions that have been previously discussed on the developer boards.  You can find code samples to get you started with your projects as well.

4.  Office Hours -- both the Salesforce MVP community and the Salesforce Foundation host office hours as a regular webinar that folks can join to ask questions and get answers. Both provide a forum for conversations about problems and challenges you may be encountering.  The MVPs offer general help with Salesforce and the foundation offers help with issues concerning the Nonprofit Starter Pack and any related topics.

5.  Out in the Wild -- The community is also active outside of the Salesforce environment in places like Twitter (try #askforce when you want to make sure your question gets seen) and StackExchange, which tends to focus on technical challenges and developer concerns.  FindSFinfo is another great resource when you are looking for information to solve your problems, it performs a search of official documentation, discussion boards, blogs, code repositories, AppExchange, and videos for any text you enter.

By cultivating a strong community, Salesforce ensures that you can always find the help you need!






Monday, December 16, 2013

Advanced Data Manipulation With Flows

Salesforce Visual Flow provides a relatively easy means to design task-specific user interfaces for end users to interact with data.  But it is important to note that Flow data is not permanent and exists only during one user's execution of the Flow.  You easily can connect Flow data to your Salesforce database, Visualforce pages and Apex code as well.

See my previous posts for more information about how Flows can simplify difficult processes for Salesforce users and tips for styling Flows. 

Record Lookup

Don't forget to save data if you need it!
If you intend for users to save the data, it can simply be written to Salesforce via the Flow data creation elements.  Similarly, there are elements for retrieving, updating, and deleting Salesforce
data. 

One of the important elements for connected Flow data to your Salesforce database is Lookup.  You can use the record lookup element to prevent duplicates when users enter data using Flow forms.  Note that the lookup will only return one record at a time.  If, for example, your form requests four fields for a Lead: first and last name as well as an email address and company, you can use all four to match the newly input data with existing data in Salesforce.  An exact match will be returned for Pat Smith with the same company name and email address.  It will not return matches with similar company names.

In addition, if there are already two Pat Smith leads with the same company and email address, currently only one of them will be returned.  At Dreamforce 2013, there was some talk about future releases returning a collection of records.

Once you have sorted out duplicates, you can determine whether the Flow data should be used with the Create element to create a new record in Salesforce or with the Update element to modify an existing record.  Make sure your Flow users have the appropriate object permissions to perform these tasks.

Error Messages

When you connect Flow data and Salesforce data, note that Salesforce might generate errors.  For example, because Flows respect user permissions and security settings as well as required fields, a user could try to save or retrieve data that is not appropriate for them.  In these cases, Salesforce will return an error.

Use a Decision Branch to process these "Fault" behaviors after linking to Salesforce.  For example, you can present error message Screens or send a user back to a previous Screen to start over.  

Accessing Flow Variables

If you need to use it in more complex processes, Visualforce and Apex can help.  As I mentioned, Flow data is not automatically retained and is unique to the specific user's current execution of the Flow.  Variables within the Flow can be made accessible to Apex and Visualforce by changing their settings from "Private", for use only in the specific Flow, to "Input", "Output" or "Input and Output".  These settings will also determine whether a Flow variable can be accessed by other Flows when one Flow contains another existing Flow as a subflow.

Note that the only way Visualforce by itself can access Flow variables is when it sends initial values to an Input variable.  For example, if your Visualforce page calls a Flow named JustSteps, it can pass a value to start at a specific step.  The code for passing a variable to specify step 3 might look like the following on the Visualforce page:

   <apex:page>
    <flow:interview name="JustSteps">
        <apex:param name="stepNumber" value="3"/>
    </flow:interview>
   </apex:page>

The Flow would then need to incorporate a Decision element at the start to check the stepNumber Input variable.

Note that Visualforce cannot change the value of a variable after the Flow has been initiated, nor can it retrieve values from Output variables without the use of an Apex controller as well.

Apex & the Flow

You can gain even more control over Flow behavior by using an Apex controller with your Flow.  The most basic controller provides your Visualforce pages access to output variables.  For example, a simple controller might look like the following:

   public class FlowClass {
    public Flow.Interview.JustSteps myflow { get; set; }
   }

Note that the  Flow name is the same in the class and in the Visualforce page that refers to the class. 
In this case the Visualforce page that uses the controller and retrieves values for a Flow Output variable called "stepsRemaining" might look something like this:

   <apex:page controller="FlowClass">

    <flow:interview name="JustSteps" interview="{!myflow}" />
   
    <apex:outputText value="Remaining steps: {!myflow.stepsRemaining}  "/> 

   </apex:page>

Another way to get more out of your Flow is through the use of an Apex plug-in.  Note that plug-in code needs to have a particular bit of code in use in order to implement the Apex Process.Plugin Interface.  An Apex plug-in can then be incorporated like any other element directly into your Flow and can assist with more complex data processing such as creating and saving attachments or converting Leads.

Once you start delving deeply into Apex and Visualforce for use with your Flow, you will probably want to reconsider managing the process.  If your process is very code intensive, you might then decide to bypass Flow and create what you need with just Visualforce and Apex.  For those who prefer not to code any more than they have to, Flow is a great alternative.