Trapdoor In The Sun

Alan Shanahan, Technician & Consultant


Leave a comment

The Transition To Force.com Developer

This is aimed at Java and C# developers who want to move into cloud computing and create demand for their skills.

One thing I regard as vital is to constantly keep an eye on your career progression. My aim is to make myself just that little bit more employable every year. It’s tough to combine this with a busy work schedule, but just because it’s tough doesn’t mean it’s not worthwhile.

The last year has seen huge growth and even bigger projections for the future of Cloud Computing. The trends are all upward, there’s no doubt. Gartner’s recent report states that the areas of “social, mobile, big data and cloud” will experience growth as they are championed by new IT leaders. Forrester predicts patterns of growth that are also encouraging. Most pundits and industry commentators agree and many of the big players are positioning themselves along these lines.

Along with explosive sales in mobile and tablet devices, it’s clear that mobile applications (particularly those that are cloud-based) will feature strongly in a global IT context for some time to come.

Add social media to the mix and it’s clear that Salesforce.com (with its Force.com platform) has its bases well and truly covered. They’ve got Chatter; Facebook and Twitter integration is covered; Touch is their technology stack for mobile; mobile apps proliferate.

And at their heart SFDC are “Cloud”. They are pioneers in the arena, that’s an undisputed fact.

Getting down to nuts and bolts, if you’re a developer with Java or C# skills, there’s a definite path you can take to sharpen your skills to become a certified Force.com developer. If you have designs on such a career path, my advice would be to follow these lists:

Application & Configuration Skills:

  • Get yourself trained up on the (Sales Force Automation) SFA application and, optionally, get yourself a certification
  • Understand what Account, Contact, Opportunity, Pricebook, Product, Case, Lead are, and what they do
  • Understand how to use Reports & Dashboards
  • Preferably, attend at least one of the Salesforce Administrator courses
  • Learn how to configure custom objects, custom fields, page layouts, field sets, formula fields, validation rules, custom buttons & links
  • Learn about Security, Roles & Profiles, field-level security
  • Get acquainted with Workflow and Approvals, what they are, what they can do
  • Learn how to import data with the Data Import Wizard

Technical & Coding Skills:

  • Sign up for a free SFDC Developer org
  • Learn about coding on the Force.com platform: Apex Triggers & Classes, VisualForce, Components, Custom Settings, Custom Labels, Resources
  • Understand what Force.com Governor Limits are, how to apply them
  • Learn what SFDC API usage limits are and understand how they may affect any application you design
  • Learn the new coding paradigms for bulk processing (a large topic but here’s a useful starter blog post)
  • Understand Lists, Maps, Sets and when to use them to handle batches of data
  • Understand Test Classes & methods
  • Learn about Apex Batch and Scheduled jobs
  • Learn how to use the SFDC SOAP and REST APIs and Workflow Outbound Messaging options
  • Learn how to extend the API with your own custom web services
  • Understand how to process inbound emails in Apex
  • Use Eclipse and the Force.com plugin to maintain Apex & Visualforce code and to examine the database schema
  • Learn how to debug code and troubleshoot using the various tools on the Force.com platform
  • Understand all the places (or “hooks”) where you can plug into the SFDC application to customise it
  • Gain at least a cursory understanding of SControls (deprecated functionality) in case you need to modernise or maintain old applications
  • Understand how to use the Apex Data Loader
  • To help you on your way with the above, here is a link to all SFDC documentation (pay special attention to the Apex and Visualforce reference docs)

You can also take your existing skills with you, and these will be invaluable:

  • Database and application design skills
  • Data Migration skills
  • Data Integration knowledge
  • Service-Oriented Architecture (SOA) and web service knowledge
  • Industry vertical expertise
  • Test-Driven Development (TDD) strategies
  • Source code version control tools and techniques
  • Multi-developer, multi work-stream development
  • Application testing strategies & methods

You can acquire all the training resources you need with little or no cost, but you can also accelerate your ramp-up time by attending SFDC formal training courses.

Anecdotal evidence would suggest that there are at least some Java developers out there who have a reluctance to extend their knowledge into the Force.com arena, primarily because of the more restricted nature of the environment. However, if you take the plunge, the rewards are there for the taking and you’ll join a growing army of technicians with niche skills.

Don’t be too quick to assume, however, that because you can instantly read Apex code (which a Java or C/Whatever coder can), your transition will be instant – there’s a little more to it than that. Most who took that path with that outlook fell foul of platform differences, a.k.a. the famed Governor Limits. But, learning the How, When and Why of these limits will help get you to the next stage in the transition process.

Acronyms used above:

  • SFDC = SalesForceDotCom
  • API = Application Programming Interface
  • SOA = Service-Oriented Architecture
  • SOAP = Simple Object Access Protocol
  • REST = Representational State Transfer
  • TDD = Test-Driven Development
Advertisement


Leave a comment

Force.com: Build Your Own Test Data Creation Suite

Every coded Force.com project needs its unit test suite. The platform has recently adapted its default practice to make it impossible for your test code to see any data in the database, BUT this is a good thing: it forces us to create unit tests that are truly data-independent. This makes them more portable, and safer.

Another practice that is highly recommended and advantageous to adopt is that of “writing once, reusing many times”; as is true for all code. What I’ve done here is to create a generic template that will help you create test data as you need it, from a common library of methods that are adaptable and can be reused. And the paradigm stretches to include bulk creation of data, which is necessary in the constrained world of Apex programming.

This post gives you the ability to add code to your project that will allow you to create, with very little additional effort, a full set of test data for your own methods and classes to play with. And I won’t be holding back; in fact, by the end of this post you will have a fully-described body of code that you can use as the starting point for your own project.

To demonstrate the concept, I’ve created a set of data-creation methods that will generate data for 4 standard Force.com objects: Account, Contact, Opportunity and OpportunityContactRole. Anyone familiar with the SFA application will understand what these objects are and how they are related. It’s important to understand the links between these tables, however:

  • Account is a top-level or parent table.
  • Contact is a child object of Account. There can be zero or more Contact records related to an Account.
  • Opportunity is a child object of Account. There can be zero or more Opportunity records related to an Account.
  • The OpportunityContactRole object is a “junction object”; it links two tables, in this case Contact and Opportunity. It can also store an optional Role for each record.

This link will show you an entity relationship diagram (ERD) that may help to clarify. Note, also, that I use the terms “object” and “table” interchangeably. For the purposes of this blog post, it will not be necessary to make any distinction and you can think of them as the same thing.

I’ll walk you through the code now. There will be links to the full class and its own test class at the end of the post.

First, we define the class and provide some high-level comments.

public class MyTestDataSuite {
	//================================================================================
	// This class contains a basic blueprint for a generic test data creation suite.
	// Clone and adapt the samples for your own custom objects and fields.
	// Ensure you complement the suite with comprehensive unit tests.
	//================================================================================

Below, I’ve defined some text constants used for the creation of test data. I’ve tried to use some data that is not likely to exist in the database, but as long as you’re not using the IsTest(SeeAllData=true) annotation and are using version 24 of the API or higher, there will be no conflict with existing data. Click here for more information.

	//--------------------------------------------------------------------------------
	// Definition of constants
	//--------------------------------------------------------------------------------
	public static final String ACCOUNT_NAME_PREFIX     = 'TEST ACCOUNT XXXX';
	public static final String CONTACT_NAME_PREFIX1    = 'FIRSTZZZZ';
	public static final String CONTACT_NAME_PREFIX2    = 'LASTZZZZ';
	public static final String OPPORTUNITY_NAME_PREFIX = 'OPPTYZZZZ';

	public static final String CONTACT_SIZE_MISMATCH =
		'Class/Method MyTestDataSuite/createTestContactData:' +
		' Number of Contact records requested does not match related Account map size.';
	public static final String OPPORTUNITY_SIZE_MISMATCH =
		'Class/Method MyTestDataSuite/createTestOpportunityData:' +
		' Number of Opportunity records requested does not match related Account map size.';
	public static final String OCR_SIZE_MISMATCH1 =
		'Class/Method MyTestDataSuite/createTestOCRData:' +
		' Number of OpportunityContactRole records requested does not match related Opportunity map size.';
	public static final String OCR_SIZE_MISMATCH2 =
		'Class/Method MyTestDataSuite/createTestOCRData:' +
		' Number of OpportunityContactRole records requested does not match related Contact map size.';

In the next short section, I’ve simply defined an Exception class to be used by the data creation methods, primarily where unrecoverable errors occur.

	//--------------------------------------------------------------------------------
	// Internal Exception class
	//--------------------------------------------------------------------------------
	public class DataSuiteException extends Exception {}

Just below, we’re finally getting into the real meat of the post. After the initial bounds checking, this code iterates through an integer loop, creating an Account record with incrementing names; they are then added to the return map, using the integer as a map key.

	//--------------------------------------------------------------------------------
	// This is where the batch of Account records are created.
	//--------------------------------------------------------------------------------
	public static Map<Integer,Account> createTestAccountData(Integer numAccs) {

		// Carry out some batch size bounds checking
		if (numAccs > 200) numAccs = 200;
		if (numAccs < 0)   numAccs = 0;

		// Initialise any initial, incrementing or unique values here
		String  wrkAccNamePrefix = ACCOUNT_NAME_PREFIX;
		Integer wrkAccountNumber = 200001;

		// Create the requested number of Account records
        Map<Integer,Account> wrkMapAccs = new Map<Integer,Account>();
        for (Integer iX = 1; iX<=numAccs; iX++) {
			Account wrkAcc = createTestAccountRecord(
				 wrkAccountNumber
				,wrkAccNamePrefix
			);
			wrkMapAccs.put(iX,wrkAcc);
			wrkAccountNumber++;
        }
		return wrkMapAccs;
    }

It’s important to note that I’ve broken out the creation of each individual record into a method in its own right. This makes it easier to read, and easier to maintain. If you wish to populate the values of any other object fields, this is the place to do it.

	//--------------------------------------------------------------------------------
	// Creation of each Account record takes place here
	//--------------------------------------------------------------------------------
	static Account createTestAccountRecord(Integer accNum, String accPfx) {

		Account wrkAccount = new Account(
			 Name                     = accPfx + ' ' + String.valueOf(accNum)
			,Custom_Account_Number__c = accNum
		);
		return wrkAccount;

	}

Below, I’ve created a similar data creation method for Contact, but note the addition of the mapInt2Account map structure; this allows the Contact to be linked to its parent Account record (on a 1:1 basis), by populating the AccountId lookup field with the parent Id value. The bounds checking is a little more involved here; I’m checking that the request to create N Contact records is accompanied by N Account (parent) records to “attach” them to.

 	//--------------------------------------------------------------------------------
	// This is where the batch of Contact records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,Contact> createTestContactData(Integer numCons, Map<Integer,Account> mapInt2Account) {

		// Carry out some batch size bounds checking
		if (numCons > 200) numCons = 200;
		if (numCons < 0)   numCons = 0;
		if (numCons != mapInt2Account.size()) {
			throw new MyTestDataSuite.DataSuiteException(CONTACT_SIZE_MISMATCH);
		}

		// Initialise any initial, incrementing or unique values here
		String  wrkConNamePrefix1 = CONTACT_NAME_PREFIX1;
		String  wrkConNamePrefix2 = CONTACT_NAME_PREFIX2;
		Integer wrkContactNumber  = 200001;

		// Create the requested number of Contact records
        Map<Integer,Contact> wrkMapCons = new Map<Integer,Contact>();
        for (Integer iX = 1; iX<=numCons; iX++) {
			Contact wrkCon = createTestContactRecord(
				 wrkContactNumber
				,mapInt2Account.get(iX).Id
				,wrkConNamePrefix1
				,wrkConNamePrefix2
			);
			wrkMapCons.put(iX,wrkCon);
			wrkContactNumber++;
        }
		return wrkMapCons;
    }

	//--------------------------------------------------------------------------------
	// Creation of each Contact record takes place here
	//--------------------------------------------------------------------------------
	static Contact createTestContactRecord(Integer conNum, Id accId, String conPfx1, String conPfx2) {

		Contact wrkContact = new Contact(
			 AccountId     = accId
			,FirstName     = conPfx1 + ' ' + String.valueOf(conNum)
			,LastName      = conPfx2 + ' ' + String.valueOf(conNum)
		);
		return wrkContact;

	}

The creation of Opportunity records is similar to that of Contacts, with it being related to the Account object by way of a lookup field.

 	//--------------------------------------------------------------------------------
	// This is where the batch of Opportunity records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,Opportunity> createTestOpportunityData(
	 	 Integer numOpps
	 	,Map<Integer,Account> mapInt2Account
	 	,String strStageName
	 	,Date datCloseDate
	 ) {

		// Carry out some batch size bounds checking
		if (numOpps > 200) numOpps = 200;
		if (numOpps < 0)   numOpps = 0;
		if (numOpps != mapInt2Account.size()) {
			throw new MyTestDataSuite.DataSuiteException(OPPORTUNITY_SIZE_MISMATCH);
		}

		// Initialise any initial, incrementing or unique values here
		String  wrkOppNamePrefix     = OPPORTUNITY_NAME_PREFIX;
		Integer wrkOpportunityNumber = 200001;

		// Create the requested number of Opportunity records
        Map<Integer,Opportunity> wrkMapOpps = new Map<Integer,Opportunity>();
        for (Integer iX = 1; iX<=numOpps; iX++) {
			Opportunity wrkOpp = createTestOpportunityRecord(
				 wrkOpportunityNumber
				,mapInt2Account.get(iX).Id
				,wrkOppNamePrefix
				,strStageName
				,datCloseDate
			);
			wrkMapOpps.put(iX,wrkOpp);
			wrkOpportunityNumber++;
        }
		return wrkMapOpps;
    }

	//--------------------------------------------------------------------------------
	// Creation of each Opportunity record takes place here
	//--------------------------------------------------------------------------------
	static Opportunity createTestOpportunityRecord(Integer oppNum, Id accId, String oppPfx, String stageName, Date closeDate) {

		Opportunity wrkOpportunity = new Opportunity(
			 AccountId     = accId
			,Name          = oppPfx + ' ' + String.valueOf(oppNum)
			,StageName     = stageName
			,CloseDate     = closeDate
		);
		return wrkOpportunity;

	}

The creation of OpportunityContactRole records, below, is simple, in that there are only a small number of fields to be populated for this to make any sense. But it’s slight more tricky because it needs to be aware of both the Contact and Opportunity maps created earlier. It’s all about dependencies and ensuring they are maintained correctly.

 	//--------------------------------------------------------------------------------
	// This is where the batch of Opportunity Contact Role records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,OpportunityContactRole> createTestOCRData(
	 	 Integer numOCRs
	 	,Map<Integer,Opportunity> mapInt2Opportunity
	 	,Map<Integer,Contact> mapInt2Contact
	 	,String strRole
	 ) {

		// Carry out some batch size bounds checking
		if (numOCRs > 200) numOCRs = 200;
		if (numOCRs < 0)   numOCRs = 0;
		if (numOCRs != mapInt2Opportunity.size()) {
			throw new MyTestDataSuite.DataSuiteException(OCR_SIZE_MISMATCH1);
		}
		if (numOCRs != mapInt2Contact.size()) {
			throw new MyTestDataSuite.DataSuiteException(OCR_SIZE_MISMATCH2);
		}

		// Initialise any initial, incrementing or unique values here (commented lines, below, left in for clarity)
		//String  wrkOCRNamePrefix     = 'OPPTYZZZZ';
		//Integer wrkOCRNumber         = 200001;

		// Create the requested number of OpportunityContactRole records
        Map<Integer,OpportunityContactRole> wrkMapOCRs = new Map<Integer,OpportunityContactRole>();
        for (Integer iX = 1; iX<=numOCRs; iX++) {
			OpportunityContactRole wrkOCR = createTestOCRRecord(
				 mapInt2Contact.get(iX).Id
				,mapInt2Opportunity.get(iX).Id
				,strRole
			);
			wrkMapOCRs.put(iX,wrkOCR);
			//wrkOCRNumber++;
        }
		return wrkMapOCRs;
    }

Here, you can see that there are two ID fields to be populated. The Role and IsPrimary fields are optional, so make whatever changes are appropriate to your needs here.

	//--------------------------------------------------------------------------------
	// Creation of each OpportunityContactRole record takes place here
	//--------------------------------------------------------------------------------
	static OpportunityContactRole createTestOCRRecord(Id conId, Id oppId, String ocrRole) {

		OpportunityContactRole wrkOCR = new OpportunityContactRole(
			 ContactId     = conId
			,OpportunityId = oppId
			,Role          = ocrRole
			,IsPrimary     = TRUE
		);
		return wrkOCR;

	}

The class wouldn’t be complete without a closing backet.

}

I’ve included the full source code for the above class here, along with its test class. I don’t claim the test class is complete; you may wish to consider adding some more unit tests to make it complete, especially around edge test cases.

The full MyTestDataSuite class:

public class MyTestDataSuite {
	//================================================================================
	// This class contains a basic blueprint for a generic test data creation suite.
	// Clone and adapt the samples for your own custom objects and fields.
	// Ensure you complement the suite with comprehensive unit tests.
	//================================================================================

	//--------------------------------------------------------------------------------
	// Definition of constants
	//--------------------------------------------------------------------------------
	public static final String ACCOUNT_NAME_PREFIX     = 'TEST ACCOUNT XXXX';
	public static final String CONTACT_NAME_PREFIX1    = 'FIRSTZZZZ';
	public static final String CONTACT_NAME_PREFIX2    = 'LASTZZZZ';
	public static final String OPPORTUNITY_NAME_PREFIX = 'OPPTYZZZZ';

	public static final String CONTACT_SIZE_MISMATCH =
		'Class/Method MyTestDataSuite/createTestContactData:' +
		' Number of Contact records requested does not match related Account map size.';
	public static final String OPPORTUNITY_SIZE_MISMATCH =
		'Class/Method MyTestDataSuite/createTestOpportunityData:' +
		' Number of Opportunity records requested does not match related Account map size.';
	public static final String OCR_SIZE_MISMATCH1 =
		'Class/Method MyTestDataSuite/createTestOCRData:' +
		' Number of OpportunityContactRole records requested does not match related Opportunity map size.';
	public static final String OCR_SIZE_MISMATCH2 =
		'Class/Method MyTestDataSuite/createTestOCRData:' +
		' Number of OpportunityContactRole records requested does not match related Contact map size.';
	
	//--------------------------------------------------------------------------------
	// Internal Exception class
	//--------------------------------------------------------------------------------
	public class DataSuiteException extends Exception {}


	//--------------------------------------------------------------------------------
	// This is where the batch of Account records are created.
	//--------------------------------------------------------------------------------
	public static Map<Integer,Account> createTestAccountData(Integer numAccs) {

		// Carry out some batch size bounds checking
		if (numAccs > 200) numAccs = 200;
		if (numAccs < 0)   numAccs = 0;

		// Initialise any initial, incrementing or unique values here
		String  wrkAccNamePrefix = ACCOUNT_NAME_PREFIX;
		Integer wrkAccountNumber = 200001;

		// Create the requested number of Account records
        Map<Integer,Account> wrkMapAccs = new Map<Integer,Account>();
        for (Integer iX = 1; iX<=numAccs; iX++) {
			Account wrkAcc = createTestAccountRecord(
				 wrkAccountNumber
				,wrkAccNamePrefix
			);
			wrkMapAccs.put(iX,wrkAcc);
			wrkAccountNumber++;
        }
		return wrkMapAccs;
    }
                                                         

	//--------------------------------------------------------------------------------
	// Creation of each Account record takes place here
	//--------------------------------------------------------------------------------
	static Account createTestAccountRecord(Integer accNum, String accPfx) {

		Account wrkAccount = new Account(
			 Name                     = accPfx + ' ' + String.valueOf(accNum)
			,Custom_Account_Number__c = accNum
		);
		return wrkAccount;

	}

    
 	//--------------------------------------------------------------------------------
	// This is where the batch of Contact records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,Contact> createTestContactData(Integer numCons, Map<Integer,Account> mapInt2Account) {

		// Carry out some batch size bounds checking
		if (numCons > 200) numCons = 200;
		if (numCons < 0)   numCons = 0;
		if (numCons != mapInt2Account.size()) {
			throw new MyTestDataSuite.DataSuiteException(CONTACT_SIZE_MISMATCH);
		}

		// Initialise any initial, incrementing or unique values here
		String  wrkConNamePrefix1 = CONTACT_NAME_PREFIX1;
		String  wrkConNamePrefix2 = CONTACT_NAME_PREFIX2;
		Integer wrkContactNumber  = 200001;

		// Create the requested number of Contact records
        Map<Integer,Contact> wrkMapCons = new Map<Integer,Contact>();
        for (Integer iX = 1; iX<=numCons; iX++) {
			Contact wrkCon = createTestContactRecord(
				 wrkContactNumber
				,mapInt2Account.get(iX).Id
				,wrkConNamePrefix1
				,wrkConNamePrefix2
			);
			wrkMapCons.put(iX,wrkCon);
			wrkContactNumber++;
        }
		return wrkMapCons;
    }
                                                         

	//--------------------------------------------------------------------------------
	// Creation of each Contact record takes place here
	//--------------------------------------------------------------------------------
	static Contact createTestContactRecord(Integer conNum, Id accId, String conPfx1, String conPfx2) {

		Contact wrkContact = new Contact(
			 AccountId     = accId
			,FirstName     = conPfx1 + ' ' + String.valueOf(conNum)
			,LastName      = conPfx2 + ' ' + String.valueOf(conNum)
		);
		return wrkContact;

	}
    
    
 	//--------------------------------------------------------------------------------
	// This is where the batch of Opportunity records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,Opportunity> createTestOpportunityData(
	 	 Integer numOpps
	 	,Map<Integer,Account> mapInt2Account
	 	,String strStageName
	 	,Date datCloseDate
	 ) {

		// Carry out some batch size bounds checking
		if (numOpps > 200) numOpps = 200;
		if (numOpps < 0)   numOpps = 0;
		if (numOpps != mapInt2Account.size()) {
			throw new MyTestDataSuite.DataSuiteException(OPPORTUNITY_SIZE_MISMATCH);
		}

		// Initialise any initial, incrementing or unique values here
		String  wrkOppNamePrefix     = OPPORTUNITY_NAME_PREFIX;
		Integer wrkOpportunityNumber = 200001;

		// Create the requested number of Opportunity records
        Map<Integer,Opportunity> wrkMapOpps = new Map<Integer,Opportunity>();
        for (Integer iX = 1; iX<=numOpps; iX++) {
			Opportunity wrkOpp = createTestOpportunityRecord(
				 wrkOpportunityNumber
				,mapInt2Account.get(iX).Id
				,wrkOppNamePrefix
				,strStageName
				,datCloseDate
			);
			wrkMapOpps.put(iX,wrkOpp);
			wrkOpportunityNumber++;
        }
		return wrkMapOpps;
    }
                                                         

	//--------------------------------------------------------------------------------
	// Creation of each Opportunity record takes place here
	//--------------------------------------------------------------------------------
	static Opportunity createTestOpportunityRecord(Integer oppNum, Id accId, String oppPfx, String stageName, Date closeDate) {

		Opportunity wrkOpportunity = new Opportunity(
			 AccountId     = accId
			,Name          = oppPfx + ' ' + String.valueOf(oppNum)
			,StageName     = stageName
			,CloseDate     = closeDate
		);
		return wrkOpportunity;

	}
    
    
 	//--------------------------------------------------------------------------------
	// This is where the batch of Opportunity Contact Role records are created.
	//--------------------------------------------------------------------------------
	 public static Map<Integer,OpportunityContactRole> createTestOCRData(
	 	 Integer numOCRs
	 	,Map<Integer,Opportunity> mapInt2Opportunity
	 	,Map<Integer,Contact> mapInt2Contact
	 	,String strRole
	 ) {

		// Carry out some batch size bounds checking
		if (numOCRs > 200) numOCRs = 200;
		if (numOCRs < 0)   numOCRs = 0;
		if (numOCRs != mapInt2Opportunity.size()) {
			throw new MyTestDataSuite.DataSuiteException(OCR_SIZE_MISMATCH1);
		}
		if (numOCRs != mapInt2Contact.size()) {
			throw new MyTestDataSuite.DataSuiteException(OCR_SIZE_MISMATCH2);
		}

		// Initialise any initial, incrementing or unique values here (commented lines, below, left in for clarity)
		//String  wrkOCRNamePrefix     = 'OPPTYZZZZ';
		//Integer wrkOCRNumber         = 200001;

		// Create the requested number of OpportunityContactRole records
        Map<Integer,OpportunityContactRole> wrkMapOCRs = new Map<Integer,OpportunityContactRole>();
        for (Integer iX = 1; iX<=numOCRs; iX++) {
			OpportunityContactRole wrkOCR = createTestOCRRecord(
				 mapInt2Contact.get(iX).Id
				,mapInt2Opportunity.get(iX).Id
				,strRole
			);
			wrkMapOCRs.put(iX,wrkOCR);
			//wrkOCRNumber++;
        }
		return wrkMapOCRs;
    }
                                                         

	//--------------------------------------------------------------------------------
	// Creation of each OpportunityContactRole record takes place here
	//--------------------------------------------------------------------------------
	static OpportunityContactRole createTestOCRRecord(Id conId, Id oppId, String ocrRole) {

		OpportunityContactRole wrkOCR = new OpportunityContactRole(
			 ContactId     = conId
			,OpportunityId = oppId
			,Role          = ocrRole
			,IsPrimary     = TRUE
		);
		return wrkOCR;

	}
    
    
     
}

The full MyTestDataSuiteTEST class:

@isTest
private class MyTestDataSuiteTEST {

	//--------------------------------------------------------------------------------
	// Test method for Account batch creation
	//                 Contact batch creation
	//                 Opportunity batch creation
	//                 OpportunityContactRole batch creation
	//--------------------------------------------------------------------------------
    static testMethod void createAccConOppOCR() {

		// Specify the start of a test data creation session
		Test.startTest();

		// Create map of Account records
		Map<Integer,Account> mapInt2Account =
			MyTestDataSuite.createTestAccountData(200);
		insert mapInt2Account.values();

		// Create map of Contact records
		Map<Integer,Contact> mapInt2Contact =
			MyTestDataSuite.createTestContactData(200, mapInt2Account);
		insert mapInt2Contact.values();

		// Create map of Opportunity records
		Map<Integer,Opportunity> mapInt2Opportunity =
			MyTestDataSuite.createTestOpportunityData(200, mapInt2Account, 'Closed Won', System.Today());
		insert mapInt2Opportunity.values();

		// Create map of OpportunityContactRole records
		Map<Integer,OpportunityContactRole> mapInt2OCR =
			MyTestDataSuite.createTestOCRData(200, mapInt2Opportunity, mapInt2Contact, 'Business User');
		insert mapInt2OCR.values();

		// Verify that the right number of map elements have been created
		System.AssertEquals(200,mapInt2Account.size());
		System.AssertEquals(200,mapInt2Contact.size());
		System.AssertEquals(200,mapInt2Opportunity.size());
		System.AssertEquals(200,mapInt2OCR.size());

		// Randomly check that the variable elements of the Account map were created as expected
		System.AssertEquals(MyTestDataSuite.ACCOUNT_NAME_PREFIX + ' ' + '200001', mapInt2Account.get(  1).Name);
		System.AssertEquals(MyTestDataSuite.ACCOUNT_NAME_PREFIX + ' ' + '200033', mapInt2Account.get( 33).Name);
		System.AssertEquals(MyTestDataSuite.ACCOUNT_NAME_PREFIX + ' ' + '200107', mapInt2Account.get(107).Name);
		System.AssertEquals(MyTestDataSuite.ACCOUNT_NAME_PREFIX + ' ' + '200200', mapInt2Account.get(200).Name);

		// Retrieve random set of Contact records from database and check Name concatenation
		List<String> lstFirstNames = new List<String>();
		lstFirstNames.add(MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200001');
		lstFirstNames.add(MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200015');
		lstFirstNames.add(MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200131');
		lstFirstNames.add(MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200200');
		List<Contact> lstContact1 = [
			SELECT Id, Name, FirstName, LastName
			FROM Contact
			WHERE FirstName IN :lstFirstNames
		];
		System.AssertEquals(4, lstContact1.size());  // Ensure we have retrieved 4 records from database

		Integer conCount1 = 0;  // Counter for verified Contact records
		for (Contact iCon : lstContact1) {
			if (iCon.FirstName == MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200001') {  // Check Contact record 1
				conCount1++;
				System.AssertEquals(iCon.Name,MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200001' + ' ' +
				                              MyTestDataSuite.CONTACT_NAME_PREFIX2 + ' ' + '200001');
			}
			if (iCon.FirstName == MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200015') {  // Check Contact record 2
				conCount1++;
				System.AssertEquals(iCon.Name,MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200015' + ' ' +
				                              MyTestDataSuite.CONTACT_NAME_PREFIX2 + ' ' + '200015');
			}
			if (iCon.FirstName == MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200131') {  // Check Contact record 3
				conCount1++;
				System.AssertEquals(iCon.Name,MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200131' + ' ' +
				                              MyTestDataSuite.CONTACT_NAME_PREFIX2 + ' ' + '200131');
			}
			if (iCon.FirstName == MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200200') {  // Check Contact record 4
				conCount1++;
				System.AssertEquals(iCon.Name,MyTestDataSuite.CONTACT_NAME_PREFIX1 + ' ' + '200200' + ' ' +
				                              MyTestDataSuite.CONTACT_NAME_PREFIX2 + ' ' + '200200');
			}
		}
		System.AssertEquals(4,conCount1);  // There should be 4 verified Contact records




		// Specify the end of a test data creation session
		Test.stopTest();

    }


	//--------------------------------------------------------------------------------
	// Test method for Account & Contact batch creation bounds checking
	//--------------------------------------------------------------------------------
    static testMethod void createAccountBoundsCheck() {

		// Specify the start of a test data creation session
		Test.startTest();

		// ACCOUNT

		// Create map of Account records with -3 elements (0 will be created)
		Map<Integer,Account> mapInt2AccountA =
			MyTestDataSuite.createTestAccountData(-3);
		System.AssertEquals(0, mapInt2AccountA.size());

		// Create map of Account records with 5000 elements (200 will be created)
		Map<Integer,Account> mapInt2AccountB =
			MyTestDataSuite.createTestAccountData(5000);
		System.AssertEquals(200, mapInt2AccountB.size());

		// Specify the end of a test data creation session
		Test.stopTest();

    }

    static testMethod void createContactBoundsCheck() {

		// Specify the start of a test data creation session
		Test.startTest();

		// CONTACT

		// Create map of Account records with 200 elements
		Map<Integer,Account> mapInt2AccountA =
			MyTestDataSuite.createTestAccountData(200);
		System.AssertEquals(200, mapInt2AccountA.size());

		// Create map of Contact records with 1234 elements (200 will be created)
		Map<Integer,Contact> mapInt2ContactA =
			MyTestDataSuite.createTestContactData(1234, mapInt2AccountA);
		System.AssertEquals(200, mapInt2ContactA.size());

		// Create map of Contact records with 10 elements (from 200 Account, exception will be thrown)
		try {
			Map<Integer,Contact> mapInt2ContactB =
				MyTestDataSuite.createTestContactData(10, mapInt2AccountA);
			System.Assert(false);  // This line should not be reached.
		}
		catch (Exception ex1) {
			System.Assert(ex1 instanceOf MyTestDataSuite.DataSuiteException);
			System.AssertEquals(ex1.getMessage(),MyTestDataSuite.CONTACT_SIZE_MISMATCH);
		}

		// Specify the end of a test data creation session
		Test.stopTest();

    }

    static testMethod void createOpportunityBoundsCheck() {

		// Specify the start of a test data creation session
		Test.startTest();

		// OPPORTUNITY

		// Create map of Account records with 200 elements
		Map<Integer,Account> mapInt2AccountA =
			MyTestDataSuite.createTestAccountData(200);
		System.AssertEquals(200, mapInt2AccountA.size());

		// Create map of Opportunity records with 201 elements (200 will be created)
		Map<Integer,Opportunity> mapInt2OpportunityA =
			MyTestDataSuite.createTestOpportunityData(201, mapInt2AccountA, 'Closed Won', System.Today());
		System.AssertEquals(200, mapInt2OpportunityA.size());

		// Create map of Opportunity records with 199 elements (from 200 Accounts, exception will be thrown)
		try {
			Map<Integer,Opportunity> mapInt2OpportunityB =
				MyTestDataSuite.createTestOpportunityData(199, mapInt2AccountA, 'Closed Won', System.Today());
			System.Assert(false);  // This line should not be reached.
		}
		catch (Exception ex1) {
			System.Assert(ex1 instanceOf MyTestDataSuite.DataSuiteException);
			System.AssertEquals(ex1.getMessage(),MyTestDataSuite.OPPORTUNITY_SIZE_MISMATCH);
		}

		// Specify the end of a test data creation session
		Test.stopTest();

    }

    static testMethod void createOCRBoundsCheck() {

		// Specify the start of a test data creation session
		Test.startTest();

		// OPPORTUNITYCONTACTROLE

		// Create map of Account records with 200 elements
		Map<Integer,Account> mapInt2AccountA =
			MyTestDataSuite.createTestAccountData(200);
		System.AssertEquals(200, mapInt2AccountA.size());

		// Create map of Account records with 100 elements
		Map<Integer,Account> mapInt2AccountB =
			MyTestDataSuite.createTestAccountData(100);
		System.AssertEquals(100, mapInt2AccountB.size());

		// Create map of Contact records with 200 elements
		Map<Integer,Contact> mapInt2ContactA =
			MyTestDataSuite.createTestContactData(200, mapInt2AccountA);
		System.AssertEquals(200, mapInt2ContactA.size());

		// Create map of Contact records with 100 elements
		Map<Integer,Contact> mapInt2ContactB =
			MyTestDataSuite.createTestContactData(100, mapInt2AccountB);
		System.AssertEquals(100, mapInt2ContactB.size());

		// Create map of Opportunity records with 200 elements
		Map<Integer,Opportunity> mapInt2OpportunityA =
			MyTestDataSuite.createTestOpportunityData(200, mapInt2AccountA, 'Closed Won', System.Today());
		System.AssertEquals(200, mapInt2OpportunityA.size());

		// Create map of Opportunity records with 100 elements
		Map<Integer,Opportunity> mapInt2OpportunityB =
			MyTestDataSuite.createTestOpportunityData(100, mapInt2AccountB, 'Closed Won', System.Today());
		System.AssertEquals(100, mapInt2OpportunityB.size());

		// Create map of OpportunityContactRole records with 200 elements
		Map<Integer,OpportunityContactRole> mapInt2OCRA =
			MyTestDataSuite.createTestOCRData(200, mapInt2OpportunityA, mapInt2ContactA, 'Business User');
		System.AssertEquals(200, mapInt2OCRA.size());

		// Create map of OpportunityContactRole records with 123 elements (from 100 Opportunity records, exception will be thrown)
		try {
			Map<Integer,OpportunityContactRole> mapInt2OCRB =
				MyTestDataSuite.createTestOCRData(123, mapInt2OpportunityB, mapInt2ContactA, 'Business User');
			System.Assert(false);  // This line should not be reached.
		}
		catch (Exception ex1) {
			System.Assert(ex1 instanceOf MyTestDataSuite.DataSuiteException);
			System.AssertEquals(ex1.getMessage(),MyTestDataSuite.OCR_SIZE_MISMATCH1);
		}

		// Create map of OpportunityContactRole records with 100 elements (from 200 Contact records, exception will be thrown)
		try {
			Map<Integer,OpportunityContactRole> mapInt2OCRC =
				MyTestDataSuite.createTestOCRData(100, mapInt2OpportunityB, mapInt2ContactA, 'Business User');
			System.Assert(false);  // This line should not be reached.
		}
		catch (Exception ex1) {
			System.Assert(ex1 instanceOf MyTestDataSuite.DataSuiteException);
			System.AssertEquals(ex1.getMessage(),MyTestDataSuite.OCR_SIZE_MISMATCH2);
		}

		// Specify the end of a test data creation session
		Test.stopTest();

    }


}

I will leave it to you to attempt to decipher the code in the test class. If there is sufficient demand, I’ll add a post with a descriptive walkthrough. All comments are welcome and encouraged.


1 Comment

Auditable Programming

Developers use debugging tools to look at the internal workings of their creations every day. One of the most useful debugging function is the ability to peer inside the contents of variables at strategic points in a program’s execution to see whether it’s behaving as expected. This is the use of a technical tool for a technical purpose. But why couldn’t we use that same concept to build better software; to give end users a peek inside the internals of the programs we write?

In the case of a complex set of calculations or decisions, this can really reap benefits. Let’s take the example of a custom discount calculation, and assume the following:

  • There are 5 different discounts that can apply to a customer order
  • Some discounts are mutually-exclusive
  • All discounts have limits that will be applied if appropriate
  • All conditions have a specific set of conditions that determine whether they are applicable
  • Some discounts require approval from a senior manager
  • Discounts above predefined threshold amounts and order percentages require approval
  • Some products do not qualify for discounts
  • Discounts can arise from a customer account, at order level or at product level

Looking at this list of preconditions, or business rules, it’s not hard to see that the internal workings of a discount calculation program can be quite complex. Consider also that you, as a developer, will need to write the code to implement these rules. You will have to debug the code and test it thoroughly. You will also have to gain customer acceptance that he is satisfied that everything works.

How can you make that last thing easier to achieve? By letting the end user peer inside the process through all stages. Let’s break this down further.

All programmed components have three simple components: input, process and output. The input to a process might be the customer record, with its associated 12.5% discount field. Another input would be a product line on an order, and its associated total amount field. The processing would be a multiplication of the line total by the discount percentage, but there might also be a decision point whereby the program checks that the product allows discount; the “Allow Discount” flag on the product would, therefore, be another input. And the output would simply be the amount of discount.

Now, let’s say we created a large text field on the order that we would use to accumulate text output to give the end user the visibility I mentioned earlier, for example:


Customer Information:
---------------------
Account "Smith And Sons" qualifies for a 12.5% on all applicable products.
Sales Discount of EUR 100.00 has been applied to this order by User: John Smith

------------
Order Lines:
------------
Processing line 1 of the order:
Product Code "ABC123", Description "Widget 123", discount IS applicable.
Order Line Total is EUR 2,500.00, Discount is EUR 312.50, Discounted Line Total is EUR 2,187.50

Processing line 2 of the order:
Product Code "XYZ001", Description "Widget 001", discount IS NOT applicable.
Order Line Total is EUR 5,000.00

--------------
Order Summary:
--------------
Order List Price Total is EUR 7,500.00
Total Order Discount Amount is EUR 412.50

----------
Approvals:
----------
Sales Discount is below the threshold level of 10% of the Order List Price Total. No approval is required.
Total Order Discount is 18.18% of Order List Price Total. Approval required because this exceeds the threshold value of 16%.

The key point to take from this is the enormous value that this text brings to the application, especially to the end user. It is valuable to anyone testing the application too, because it really is a debugging log; but it is presented in a plain-English manner.

This strategy will not hurt you when it comes to quality. Bottom line, it’s about programming for the user, not for the programmer.


Leave a comment

Techie Poll: Code Comments Misspellings & Bad Grammar

As a picky, petty pedant, this is a topic near and dear to me. The question also applies to field names, method and class names and any other symbolic placeholder names in program code.

Question: “What do you think of misspellings and bad grammar in code comments, field names, method and class names?

Your comments are welcome, as always. It doesn’t have to stop at a poll, it’s worthy of discussion.


Leave a comment

Wild Goose Chase

This is an argument in favour of refactoring code to prevent duplication. It’s a real example that happened in the last couple of years and demonstrates an important point.

In our example, one code function existed in four separate places in the same code suite.

At some point later, a business functional change meant that a code change was required. The change was made, but only in one of those four places. The testing that followed was significant because the change was made to code that formed part of some core business functions. Errors were found in testing, it’s fairly obvious why. [For those not paying attention, the change needed to be made in three other places.]

Now, because we didn’t know the code too well, it was a reasonable assumption that one possible cause for the errors was code version regression. Something was askew in the version control department, or so we assumed. Much time was spent investigating this as the root cause. It was a wild goose chase.

It’s a classic example of why quality belongs to developers. Amongst others.


Leave a comment

Update: New Salesforce.com function to provide 18-char IDs

I blogged in the past on the subject of Salesforce.com IDs: click here to see it.

The wonderful thing is that SFDC were listening! Not just to me, but I was a voice in the crowd. They responded in the Spring ’12 release with a new function to be used in formula fields:

Syntax example: CASESAFEID(Id)

Official documentation link: http://login.salesforce.com/help/doc/en/customize_functions_a_h.htm#CASESAFEID

It’s that simple. Just set up a new custom field with this as the formula and use it in your reports.

 

[Note: SFDC = SalesForceDotCom]


Leave a comment

Developer Maturity

Thirty-odd years ago, I wrote my first lines of BASIC code on an Apple II computer donated to my secondary school by some local businesses. We were the first of our school and, to some degree, our generation to have access to such a device. I was hooked from the word go. All these years and a few dozen jobs later, I can tell you I’ve seen the full spectrum of good and bad in the world of programming; I may even have contributed to the bad side, but I live in hope that most of what I produced was leaning towards the better side of things.

But I can see definite steps in my progression in those intervening years; let me focus on programming itself, or “development” as the industry likes to call it. Today, I have a very different mindset to that of my teen years. My young naive self revelled in the idea that you could type an arbitrary set of instructions into a machine and it could do the most marvellous things. Coding was an end in itself! It existed just so that beautiful programs could be written and run. I had a lot to learn.

Then I started working in the real world. My programs were now being used by real people, in a real business, every day. There was a huge amount of job satisfaction in that idea. Everything changed. My “hobby” was now something to take seriously and it had to perform to a new standard. But I didn’t fully realise that and I still saw programming as an isolated pursuit with its own intrinsic value; in my mind it was a primary activity with its own purpose rather than an enabler. This illustrated an immaturity in terms of my business viewpoint.

Many years later, I’ve managed programmers and development teams. Still doing that. I’ve designing solutions for customers that are implemented by these teams. I’ve seen and reviewed a lot of code. In that sea of code, the full spectrum of quality exists. Some bad practices can have a subjective slant to them, but other bad practices are just plain bad. I’ll tackle the subject of quality later, it’s just too big to even contemplate here. But one point on quality is worth reiterating here and now: quality is everyone’s responsibility. I won’t explain that further, I believe the words do that for themselves. You own quality. You own problems created by your programs, no matter how trivial. At least to some extent. You owe it to your team to properly ring fence and test scenarios your programs are supposed to handle. You owe it to the customers who are paying for your development efforts.

And what I have seen is a set of behaviour patterns that seem to be repeating.

Firstly, there is an obvious disconnect between some programmers and the end user they are programming for. Think about users. Someone will sit in front of a screen and use your programs. They are real people, no matter how distant they are, or how imaginary they seem.

Another misalignment I’ve seen is that some programmers don’t conceive that data represents real world things. Financial data represents money, real money, not imaginary money. This is important to customers. It’s their money, the life blood of their business, which would simply curl up and die without it.

Polish! Polish your code. Polish the user interface. Try to break your programs. Keep trying until they no longer break.

Open your mind. Let go. Don’t be afraid to rework what you’ve written. The best writers and authors do this regularly; that’s why they’re the best. Coding is not an end in itself, it’s a means to an end: the business aim is the end. Code is just an enabler.

Do these things…

…and you’ll be all grown up.

[Note: I’ve emphasised “some programmers” in this piece. I’ve worked and continue to work with many superb developers. It’s worth mentioning.]