function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pjaenick.ax736pjaenick.ax736 

Class with sharing / method

Is it possible to define one method within a "with sharing" class as "without sharing"?  If so, what's the correct syntax? 

 

"Error: Compile Error: Methods cannot be marked with(out) sharing"

 

I'd rather not turn off the "with sharing" clause for the entire class.

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You can create an inner class that holds the method, or use a separate class entirely. Your exact scenario will determine which syntax is correct.

 

public with sharing class outside {
    public without sharing class inside {
        public void dosomething() {
        
        }
    }
}

For example, "inside" could be a wrapper class, or a helper class instantiated when needed in a method from "outside." You can't have just a single method honor/ignore sharing explictly, as this property is defined at the class level.

All Answers

sfdcfoxsfdcfox

You can create an inner class that holds the method, or use a separate class entirely. Your exact scenario will determine which syntax is correct.

 

public with sharing class outside {
    public without sharing class inside {
        public void dosomething() {
        
        }
    }
}

For example, "inside" could be a wrapper class, or a helper class instantiated when needed in a method from "outside." You can't have just a single method honor/ignore sharing explictly, as this property is defined at the class level.

This was selected as the best answer
pjaenick.ax736pjaenick.ax736

Thanks sfdcfox!

 

A trigger that references the nested method would use "outside.inside.dosomething()" ?

 

(tried, this syntax didn't seem to work - rec'd "Method does not exist or incorrect signature" - though I was forced to remove the "static" from my inner class, in case that's the cause - "Only top-level class methods can be declared static").

sfdcfoxsfdcfox

Correct. It can't be static. This means that you'll have to take one of two approaches:

 

1. 

outside.inside helper = new outside.inside();
helper.doSomething();

2.

public with sharing class util {
    public static void doSomething() {
    }
}

// In trigger

util.doSomething();

 

pjaenick.ax736pjaenick.ax736

Thank you !  Moved the method to its own class - didn't make sense to turn it into an inside class, as (other than that they act upon the same object) there really wasn't any dependency / relationship.

 

Appreciate the assist - thanks again.  Marked your first response as the solution.