Is there any way to make an Apex method parameter lazy?Get Total Permutations of child objects in a list of...

Plausible reason for gold-digging ant

Caron Accent v{a} doesn't render without usepackage{xeCJK}

How vim overwrites readonly mode?

A question about partitioning positivie integers into finitely many arithmetic progresions

Illustrator to chemdraw

Is there a verb that means to inject with poison?

Taking headphones when quitting job

Book where a space ship journeys to the center of the galaxy to find all the stars had gone supernova

How IPsec tunnel mode work without GRE

How to completely remove a package in Ubuntu (like it never existed)

The No-Straight Maze

Is the fingering of thirds flexible or do I have to follow the rules?

Is it possible to rotate the Isolines on a Surface Using `MeshFunction`?

Does the US government have any planning in place to ensure there's no shortages of food, fuel, steel and other commodities?

Sitecore 9.1 Installation - Skip to particular step

Need help with a circuit diagram where the motor does not seem to have any connection to ground. Error with diagram? Or am i missing something?

What does an unprocessed RAW file look like?

Sharepoint metadata URL

Is there any danger of my neighbor having my wife's signature?

Is there any advantage in specifying './' in a for loop using a glob?

Should a cast be used to truncate a long variable?

Eww, those bytes are gross

Am I correct in stating that the study of topology is purely theoretical?

How is this property called for mod?



Is there any way to make an Apex method parameter lazy?


Get Total Permutations of child objects in a list of listsProcessInstanceWorkitems not created when running an Approval Process unit testWill SFDC manufacture batches from concurrent operations?Order of execution of controller method calls during rerenderCalling a method with List<string> Ids parameterIs there an easy way to sync the Default Account Team of an User to all accounts he owns by APEX?Is there any way to LIKE a chatter post in the context of another user?Need a Help to Convert Workflow Formula field into ApexIs there a Salesforce method to validate Remote Objects Query Criteria and turn it into dynamic SOQL?Is applying a LIMIT to a Count() query an optimization?













2















Let's say I want to call a method like:



doSomething(a.b.c.d.e.f());


I know that this might be an expensive operation and a, a.b, a.b.c, a.b.c.d, and a.b.c.d.e might all be null, however I would rather deal with all these possibilities within doSomething() is there any way I can defer that operation until I want/need it?



(I'm 99% certain the answer is 'no', but I hope to learn that I'm wrong.)










share|improve this question


















  • 1





    This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

    – sfdcfox
    5 hours ago


















2















Let's say I want to call a method like:



doSomething(a.b.c.d.e.f());


I know that this might be an expensive operation and a, a.b, a.b.c, a.b.c.d, and a.b.c.d.e might all be null, however I would rather deal with all these possibilities within doSomething() is there any way I can defer that operation until I want/need it?



(I'm 99% certain the answer is 'no', but I hope to learn that I'm wrong.)










share|improve this question


















  • 1





    This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

    – sfdcfox
    5 hours ago
















2












2








2








Let's say I want to call a method like:



doSomething(a.b.c.d.e.f());


I know that this might be an expensive operation and a, a.b, a.b.c, a.b.c.d, and a.b.c.d.e might all be null, however I would rather deal with all these possibilities within doSomething() is there any way I can defer that operation until I want/need it?



(I'm 99% certain the answer is 'no', but I hope to learn that I'm wrong.)










share|improve this question














Let's say I want to call a method like:



doSomething(a.b.c.d.e.f());


I know that this might be an expensive operation and a, a.b, a.b.c, a.b.c.d, and a.b.c.d.e might all be null, however I would rather deal with all these possibilities within doSomething() is there any way I can defer that operation until I want/need it?



(I'm 99% certain the answer is 'no', but I hope to learn that I'm wrong.)







apex null-pointer method lazy-loading






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 8 hours ago









Brian KesslerBrian Kessler

1,6411131




1,6411131








  • 1





    This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

    – sfdcfox
    5 hours ago
















  • 1





    This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

    – sfdcfox
    5 hours ago










1




1





This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

– sfdcfox
5 hours ago







This Idea would help, though not as nice as having a shortcut like ? null checks available in .Net.

– sfdcfox
5 hours ago












1 Answer
1






active

oldest

votes


















6














Not exactly, but you can do something like lazy evaluation by making use of the Callable interface (or rolling your own). Here's an example using Callable...



To start with, a test:



@IsTest private class LazyTest {

@TestSetup static void setup() {
List<Account> accounts = new List<Account> {
new Account(Name = 'A'),
new Account(Name = 'B')};

insert accounts;

List<Contact> contacts = new List<Contact> {
new Contact(LastName = '1', AccountId = accounts[0].Id),
new Contact(LastName = '2', AccountId = accounts[1].Id)};

insert contacts;
}

@IsTest static void testBehavior() {
Callable lazyContacts = new LazyContacts(new LazyAccounts('A'));
// No calls made yet, so I can pass this around at no great cost
System.assertEquals(0, Limits.getQueries());

// OK, I've decided I need those contacts now...
List<Contact> results = (List<Contact>)lazyContacts.call(null, null);
System.assertEquals(2, Limits.getQueries());
System.assertEquals(1, results.size());
System.assertEquals('1', results[0].LastName);
}
}


In the test, lazyContacts is not yet the Contacts I'm looking for. It's like a Callable that will provide the Contacts when I actually need them. It's parameterised by another Callable, so that inner one is also not invoked until you decide you actually need it.



The actual implementations:



public with sharing class LazyContacts implements Callable {

private Callable lazyAccounts;

public LazyContacts(Callable lazyAccounts) {
this.lazyAccounts = lazyAccounts;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT LastName
FROM Contact
WHERE AccountId IN :(List<SObject>)lazyAccounts.call(null, null)
];
}
}

public with sharing class LazyAccounts implements Callable {

private String accountName;

public LazyAccounts(String accountName) {
this.accountName = accountName;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT Id
FROM Account
WHERE Name = :accountName
];
}
}


You could certainly put together something like that in Apex. And you can do similar with iterators - only iterating when the data is actually requested.



The only downside is that Apex is missing a few language niceties that exist in Java and would make the code more succinct (and type-safe if we had templates).






share|improve this answer



















  • 1





    Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

    – Brian Kessler
    6 hours ago






  • 3





    The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

    – Aidan
    6 hours ago











Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "459"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f251558%2fis-there-any-way-to-make-an-apex-method-parameter-lazy%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














Not exactly, but you can do something like lazy evaluation by making use of the Callable interface (or rolling your own). Here's an example using Callable...



To start with, a test:



@IsTest private class LazyTest {

@TestSetup static void setup() {
List<Account> accounts = new List<Account> {
new Account(Name = 'A'),
new Account(Name = 'B')};

insert accounts;

List<Contact> contacts = new List<Contact> {
new Contact(LastName = '1', AccountId = accounts[0].Id),
new Contact(LastName = '2', AccountId = accounts[1].Id)};

insert contacts;
}

@IsTest static void testBehavior() {
Callable lazyContacts = new LazyContacts(new LazyAccounts('A'));
// No calls made yet, so I can pass this around at no great cost
System.assertEquals(0, Limits.getQueries());

// OK, I've decided I need those contacts now...
List<Contact> results = (List<Contact>)lazyContacts.call(null, null);
System.assertEquals(2, Limits.getQueries());
System.assertEquals(1, results.size());
System.assertEquals('1', results[0].LastName);
}
}


In the test, lazyContacts is not yet the Contacts I'm looking for. It's like a Callable that will provide the Contacts when I actually need them. It's parameterised by another Callable, so that inner one is also not invoked until you decide you actually need it.



The actual implementations:



public with sharing class LazyContacts implements Callable {

private Callable lazyAccounts;

public LazyContacts(Callable lazyAccounts) {
this.lazyAccounts = lazyAccounts;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT LastName
FROM Contact
WHERE AccountId IN :(List<SObject>)lazyAccounts.call(null, null)
];
}
}

public with sharing class LazyAccounts implements Callable {

private String accountName;

public LazyAccounts(String accountName) {
this.accountName = accountName;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT Id
FROM Account
WHERE Name = :accountName
];
}
}


You could certainly put together something like that in Apex. And you can do similar with iterators - only iterating when the data is actually requested.



The only downside is that Apex is missing a few language niceties that exist in Java and would make the code more succinct (and type-safe if we had templates).






share|improve this answer



















  • 1





    Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

    – Brian Kessler
    6 hours ago






  • 3





    The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

    – Aidan
    6 hours ago
















6














Not exactly, but you can do something like lazy evaluation by making use of the Callable interface (or rolling your own). Here's an example using Callable...



To start with, a test:



@IsTest private class LazyTest {

@TestSetup static void setup() {
List<Account> accounts = new List<Account> {
new Account(Name = 'A'),
new Account(Name = 'B')};

insert accounts;

List<Contact> contacts = new List<Contact> {
new Contact(LastName = '1', AccountId = accounts[0].Id),
new Contact(LastName = '2', AccountId = accounts[1].Id)};

insert contacts;
}

@IsTest static void testBehavior() {
Callable lazyContacts = new LazyContacts(new LazyAccounts('A'));
// No calls made yet, so I can pass this around at no great cost
System.assertEquals(0, Limits.getQueries());

// OK, I've decided I need those contacts now...
List<Contact> results = (List<Contact>)lazyContacts.call(null, null);
System.assertEquals(2, Limits.getQueries());
System.assertEquals(1, results.size());
System.assertEquals('1', results[0].LastName);
}
}


In the test, lazyContacts is not yet the Contacts I'm looking for. It's like a Callable that will provide the Contacts when I actually need them. It's parameterised by another Callable, so that inner one is also not invoked until you decide you actually need it.



The actual implementations:



public with sharing class LazyContacts implements Callable {

private Callable lazyAccounts;

public LazyContacts(Callable lazyAccounts) {
this.lazyAccounts = lazyAccounts;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT LastName
FROM Contact
WHERE AccountId IN :(List<SObject>)lazyAccounts.call(null, null)
];
}
}

public with sharing class LazyAccounts implements Callable {

private String accountName;

public LazyAccounts(String accountName) {
this.accountName = accountName;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT Id
FROM Account
WHERE Name = :accountName
];
}
}


You could certainly put together something like that in Apex. And you can do similar with iterators - only iterating when the data is actually requested.



The only downside is that Apex is missing a few language niceties that exist in Java and would make the code more succinct (and type-safe if we had templates).






share|improve this answer



















  • 1





    Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

    – Brian Kessler
    6 hours ago






  • 3





    The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

    – Aidan
    6 hours ago














6












6








6







Not exactly, but you can do something like lazy evaluation by making use of the Callable interface (or rolling your own). Here's an example using Callable...



To start with, a test:



@IsTest private class LazyTest {

@TestSetup static void setup() {
List<Account> accounts = new List<Account> {
new Account(Name = 'A'),
new Account(Name = 'B')};

insert accounts;

List<Contact> contacts = new List<Contact> {
new Contact(LastName = '1', AccountId = accounts[0].Id),
new Contact(LastName = '2', AccountId = accounts[1].Id)};

insert contacts;
}

@IsTest static void testBehavior() {
Callable lazyContacts = new LazyContacts(new LazyAccounts('A'));
// No calls made yet, so I can pass this around at no great cost
System.assertEquals(0, Limits.getQueries());

// OK, I've decided I need those contacts now...
List<Contact> results = (List<Contact>)lazyContacts.call(null, null);
System.assertEquals(2, Limits.getQueries());
System.assertEquals(1, results.size());
System.assertEquals('1', results[0].LastName);
}
}


In the test, lazyContacts is not yet the Contacts I'm looking for. It's like a Callable that will provide the Contacts when I actually need them. It's parameterised by another Callable, so that inner one is also not invoked until you decide you actually need it.



The actual implementations:



public with sharing class LazyContacts implements Callable {

private Callable lazyAccounts;

public LazyContacts(Callable lazyAccounts) {
this.lazyAccounts = lazyAccounts;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT LastName
FROM Contact
WHERE AccountId IN :(List<SObject>)lazyAccounts.call(null, null)
];
}
}

public with sharing class LazyAccounts implements Callable {

private String accountName;

public LazyAccounts(String accountName) {
this.accountName = accountName;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT Id
FROM Account
WHERE Name = :accountName
];
}
}


You could certainly put together something like that in Apex. And you can do similar with iterators - only iterating when the data is actually requested.



The only downside is that Apex is missing a few language niceties that exist in Java and would make the code more succinct (and type-safe if we had templates).






share|improve this answer













Not exactly, but you can do something like lazy evaluation by making use of the Callable interface (or rolling your own). Here's an example using Callable...



To start with, a test:



@IsTest private class LazyTest {

@TestSetup static void setup() {
List<Account> accounts = new List<Account> {
new Account(Name = 'A'),
new Account(Name = 'B')};

insert accounts;

List<Contact> contacts = new List<Contact> {
new Contact(LastName = '1', AccountId = accounts[0].Id),
new Contact(LastName = '2', AccountId = accounts[1].Id)};

insert contacts;
}

@IsTest static void testBehavior() {
Callable lazyContacts = new LazyContacts(new LazyAccounts('A'));
// No calls made yet, so I can pass this around at no great cost
System.assertEquals(0, Limits.getQueries());

// OK, I've decided I need those contacts now...
List<Contact> results = (List<Contact>)lazyContacts.call(null, null);
System.assertEquals(2, Limits.getQueries());
System.assertEquals(1, results.size());
System.assertEquals('1', results[0].LastName);
}
}


In the test, lazyContacts is not yet the Contacts I'm looking for. It's like a Callable that will provide the Contacts when I actually need them. It's parameterised by another Callable, so that inner one is also not invoked until you decide you actually need it.



The actual implementations:



public with sharing class LazyContacts implements Callable {

private Callable lazyAccounts;

public LazyContacts(Callable lazyAccounts) {
this.lazyAccounts = lazyAccounts;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT LastName
FROM Contact
WHERE AccountId IN :(List<SObject>)lazyAccounts.call(null, null)
];
}
}

public with sharing class LazyAccounts implements Callable {

private String accountName;

public LazyAccounts(String accountName) {
this.accountName = accountName;
}

public Object call(String param1, Map<String, Object> param2) {
return [
SELECT Id
FROM Account
WHERE Name = :accountName
];
}
}


You could certainly put together something like that in Apex. And you can do similar with iterators - only iterating when the data is actually requested.



The only downside is that Apex is missing a few language niceties that exist in Java and would make the code more succinct (and type-safe if we had templates).







share|improve this answer












share|improve this answer



share|improve this answer










answered 6 hours ago









AidanAidan

7,2101144




7,2101144








  • 1





    Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

    – Brian Kessler
    6 hours ago






  • 3





    The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

    – Aidan
    6 hours ago














  • 1





    Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

    – Brian Kessler
    6 hours ago






  • 3





    The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

    – Aidan
    6 hours ago








1




1





Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

– Brian Kessler
6 hours ago





Thanks for the response. Interesting approach. I'm not really sure what "Callable" brings to this conversation since, a you point out, we could roll our own interface and do so in a way that doesn't have unused parameters and could have greater type safety... Also doesn't solve the problem of a, a.b, etc possibly being null (but I guess that probably isn't solvable in Apex)

– Brian Kessler
6 hours ago




3




3





The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

– Aidan
6 hours ago





The advantage of callable is that it exists already, so no extra dependencies if you're using unlocked packaging. And it does keep everything very loosely coupled. It seems like you're asking two questions, really: 1. How can I defer evaluation? A: Use callable or something similar 2. How can I avoid lots of null-checks. 1 seems like the bigger problem to me, so that's what I answered. 2 can be done by replacing null with an appropriate actual object e.g. an empty list, or string, or a Null Object. Then make sure you don't do expensive things if the incoming data doesn't need them

– Aidan
6 hours ago


















draft saved

draft discarded




















































Thanks for contributing an answer to Salesforce Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f251558%2fis-there-any-way-to-make-an-apex-method-parameter-lazy%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Why not use the yoke to control yaw, as well as pitch and roll? Announcing the arrival of...

Couldn't open a raw socket. Error: Permission denied (13) (nmap)Is it possible to run networking commands...

VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...