Salesforce Developer – Apex Sharing Questions
Apex sharing enables developers to programmatically control record access in Salesforce, providing granular control beyond declarative sharing mechanisms. These questions cover sharing fundamentals, with sharing vs without sharing keywords, user vs inherited sharing, sharing reasons, manual sharing implementation, sharing rule automation, CRUD/FLS enforcement, testing sharing scenarios, governor limit considerations, best practices, troubleshooting access issues, integration with custom objects, and security implications. Understanding Apex sharing is essential for building secure Salesforce applications.
Apex Sharing - Q&A
- Q1. What is Apex sharing and when would you use it?
Ans: Apex sharing allows programmatic control of record access: - Purpose: Grant or restrict access beyond OWD and role hierarchy - Use cases: * Dynamic sharing based on business rules * Sharing records with specific users or groups * Temporary access for special processes * Integration with external systems requiring access control * Custom sharing for complex business scenarios - Limitation: Only works with custom objects, not standard objects Example:public class AccountSharingHandler { public static void shareAccountWithUser(Id accountId, Id userId) { AccountShare accountShare = new AccountShare(); accountShare.AccountId = accountId; accountShare.UserOrGroupId = userId; accountShare.AccountAccessLevel = 'Read'; accountShare.ContactAccessLevel = 'Read'; accountShare.CaseAccessLevel = 'Read'; accountShare.OpportunityAccessLevel = 'Read'; accountShare.RowCause = 'Manual'; // Sharing Reason insert accountShare; } }
- Q2. Explain the difference between with sharing, without sharing, and inherited sharing.
Ans: Sharing keywords control data access in Apex: - with sharing: Respects user's sharing rules and OWD * Enforces record-level security * Respects role hierarchy, sharing rules, manual shares * Recommended for classes that query sensitive data - without sharing: Bypasses sharing rules * Runs in system context with full access * Should be used carefully and only when necessary * Common for system maintenance or batch processes - inherited sharing (API v44+): Inherits sharing from calling context * If called from with sharing context, enforces sharing * If called from without sharing context, bypasses sharing * Provides flexibility in sharing enforcement Example:public with sharing class SecureAccountService { public static List
getAccounts() { // Respects user's sharing rules return [SELECT Id, Name FROM Account]; } } public without sharing class SystemMaintenanceService { public static void cleanupOldRecords() { // Bypasses sharing - full access List oldAccounts = [SELECT Id FROM Account WHERE CreatedDate < LAST_YEAR]; delete oldAccounts; } } public inherited sharing class FlexibleService { public static List getAccounts() { // Inherits sharing from calling context return [SELECT Id, Name FROM Account]; } } - Q3. How do you implement manual sharing in Apex?
Ans: Manual sharing implementation: 1. Create Share Object: For each custom object (e.g., AccountShare) 2. Set Required Fields: Record ID, User/Group ID, Access Levels 3. Specify RowCause: Sharing reason (must be defined in object) 4. Insert Share Record: DML operation to create sharing Example:public class ManualSharingService { public static void shareCustomObject(Id recordId, Id userId, String accessLevel) { // For a custom object MyObject__c, the share object is MyObject__Share MyObject__Share myObjectShare = new MyObject__Share(); myObjectShare.ParentId = recordId; // Record being shared myObjectShare.UserOrGroupId = userId; // User or Group to share with myObjectShare.AccessLevel = accessLevel; // Read, Edit, etc. myObjectShare.RowCause = 'Manual'; // Must match defined sharing reasons Ans: Critical aspects: - Audit sharing changes - Validate recipient permissions - Prevent over-sharing - Consider field-level security - Monitor sharing table growth - Review sharing during ownership changes
- Q10. How do you handle sharing for custom objects?
Ans: Implementation steps: 1. Set OWD to Private 2. Create CustomObject__Share objects 3. Implement trigger/framework 4. Consider sharing reasons 5. Bulkify sharing operations Note: Custom objects require explicit sharing - Q11. What are sharing reasons and how are they used?
Ans: Sharing reasons: - Track why access was granted - Defined via picklist on share objects - Useful for: * Auditing * Cleanup operations * Temporary access tracking Example field: OpportunityShare.RowCause - Q12. How do you troubleshoot missing sharing records?
Ans: Diagnostic steps: 1. Check OWD settings 2. Verify role hierarchy 3. Review sharing rules 4. Query share tables 5. Test with System.runAs() 6. Check for recalculation needs - Q13. What are the performance implications of Apex Sharing?
Ans: Performance considerations: - Sharing tables affect query performance - Bulk operations recommended - Asynchronous processing for large volumes - Indexing considerations (UserOrGroupId) - Sharing recalculation impact - Q14. How do you implement territory-based sharing in Apex?
Ans: Territory pattern: 1. Create Territory__c custom object 2. Build junction object (UserTerritory__c) 3. Implement trigger to manage AccountShare 4. Schedule batch for initial load 5. Handle territory changes Alternative: Use native Territory Management - Q15. Explain real-world Apex Sharing scenarios.
Ans: Practical applications: - Partner portal access control - Dynamic project team visibility - Regional sales territory sharing - Temporary audit access grants - Hierarchical approval visibility - Multi-brand data segregation