I am always unsure whether to use
without sharingin my classes or to just leave that out. The documentation is part of my confusion.
- Any practical hints?
- When do you use it and in which types of classes
(Domain, Service, Util)?
- When do you leave it out?
So the perfect answer would be “When I write the header of a new Apex class I put it in when ….”.
If not declared explicitly, classes are always
Apex without a sharing declaration is insecure by default. Ref
It is important to understand that in both cases (With or Without Sharing), Apex runs in System Mode, so it wouldn’t respect things like Field Level Security.
Use With Sharing when the User has access to the records being updated via Role, Sharing Rules, Sales Teams – any sort of sharing really.
Without Sharing is reserved for cases where the User does not have access to the records, but there is a need to update them based on user input.
Also the With / Without Sharing commutes and if a class doesn’t have an explicit declaration, the sharing context of the calling class is inherited.