What methods must be static in Apex? - methods

I’m going through preparation for a professional assessment and at the moment I have a question that I can’t give a complete answer to, as I am new to Apex.
Question: Describe the features of static methods. What methods(necessarily) must be static?
There are no problems with the first part, but I would like to find an exhaustive answer somewhere in the second part. Annotations # Future for example, etc.

static methods need to be used when you don't need an instance of a class or if the method needs to be exposed to other callers. Examples of this are lwc/aura/visualforce remoting methods.
See these links for examples of why static is necessary
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_apex.htm
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_RemoteAction.htm

Related

Is it possible to show comments retrieved from /// <inerithdoc cref=""/>

I like intellisense and I think everyone should always add structured comments on classes and methods, I say so because the concept of being "self commenting code" is per se a wrong practice.
How do you draw the line between something that for the creator is obvious but this isn't true for any other developer?
In my company we have a wide range of very useful shared NuGet packages, but most of them have no comments, or at least in the interfaces. This cause the consumer class, using IoC, to blindly use the interfaces loosing completely the comments and therefore the intellisense.
Maybe I don't create the NuGet packages in the right way, but so far the best practice I found, is to add comments in the interfaces and add in the implementing class, the comment: /// <inerithdoc cref=""/>.
This helps me share the documentation, parameters and return type descriptions and so on.
Now the inherithdoc, is mostly used for the XML documentation generation, but not really helpful when it comes to access the description from the implementation class.
An example, I have IMyClass with all the nice comments, if I open MyClass which implements IMyClass, I can read through the code but I don't have straight access to the comments and it is very annoying to be forced to jump back and forth to the Interface in order to read them.
So a possible solution would be to copy the comments across Interfaces and implementing Classes, but I hate duplication, and you can easily end up updating the descriptions here but not there.
So my question for the community is, how do you handle this? Is there Any extension that shows me the description maybe as part of the codelens?
Hovering the mouse on the cref attribute, allow me to get the description of the class/interface and methods, but not parameters.

Is there a common convension to put new methods(on top or on bottom)?

If we omit visibility modifiers(let's say all methods are public), is there any common convension to put new methods in class? I mean if I put them on bottom it's logically correct, because methods are sorted by date. If I put them on top, it's easy to see and compare what methods are added if the class is very long.
Just depends on what you and your team are comfortable with. I usually have method at the top of my class followed by fields. If there are many method that do different thing you are better off organizing them in a new class. Now without seeing any code I'm simply guessing.
No, I don't think there is.
As Kalagen said it's up to you and your team to decide it.
I would keep any methods that share similar functionality together and keep the class definition short.
The short answer in my opinion is no. Coding style might vary depending on the language you are using and the team you are working with. In addition you might have your own preference as well. I tend to add new methods close to methods that are related to it (e.g. if method1 calls method2 then method1 is above method2). Then it is relatively easy to find the method that's being called. On the other hand, most IDEs can find the method with a mouse click.
If you're using version control, you can easily see what methods were added and in which order, so sorting by date is not needed.
And as others have mentioned, keep the class small. Take a look at the Single responsibility principle. If the methods you are adding are not related to the responsibility of the class, extract them and create a new class.

Is it common practice to hold a repository globally? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In repository examples, I see the repository instantiated when the Session opens, which seems as if it is around for the entire Session. In controller actions, the data layer is then accessed through calls to the repository. Is this common practice? Wouldn't it make more sense to be instantiating the repository in an on need basis per action request?
Edit: A more exact scenario.
public class myController : Controller {
IMyRepository myRepository;
public myController(IMyRepository repositoryParam){
myRepository = repositoryParam;
}
public ActionResult someAction(){
MyClass myClass = myRepository.RepositoryAction();
}
}
In this scenario, myRepository is global to myController (note: this is based off an example from Steven Sanderson). I have seen it also defined for all controllers to access, but this is a simple, exact, example. In this example, why would the repository be used globally instead of on a per use basis?
To answer your question, Travis, you should read up a bit on the Repository Pattern. This pattern is used to provide a number of advantages, including:
It centralizes the data logic or Web service access logic.
It provides a substitution point for the unit tests.
It provides a flexible architecture that can be adapted as the overall design of the application evolves.
As to your question: "Is this a common practice?" the answer is, "It should be." but, unfortunately, I don't see it as much as I would prefer.
Now, in your example, you show the repository being created within the context of your controller class. (Please note that this is NOT the same thing as an object being made "global" as you put it. Global means that the object is accessible from any scope. Read more about it here at Wikipedia.)
In any case, one of the advantages is that the repository allows you to change between how you are accessing your data (or even where your data is being accessed) by using the correct, concrete version of the repository. So, you may have:
IRepository - Your interface which the concrete repositories implement.
DatabaseRepository - Accesses your data in a database.
FlatFileRepository - Access your data out of a flat file.
etc.
If you wish to switch to other data sources, it is a simple as swapping out the concrete implementation in your controller. (Please note, there are more advanced and flexible ways of doing this through dependency injection, but that is out of scope of this question, although it does/can play heavily in the repository pattern.)
In any case, say your project team decides "Hey, we're going to switch from storing all our data in flat files to using a database." Well, if you have scattered the instantiations of that specific repository throughout your code, you now have a lot of different areas to fix and update, somewhat negating the advantages of the repository pattern. However, by declaring a member repository of your controller, you just switch from a FlatFileRepository to a DatabaseRepository, implement the new repository, and you are finished! Everybody on the team is happy!
Update: "Why Instantiate a Class Variable?"
To answer that question, you have to think of your two options. The first option is that you could hold a relatively small object in memory. The other alternative is you could instantiate a new object in memory every time that a user needs to access one of your actions causing new memory to be allocated (and deallocated when you leave the scope that the object was in) and requiring more work by the server which is hosting your web app.
If you think about how a website is used, users are hitting those actions on a frequent basis. Every action signifies a portion of your website. If you instantiated every single time you needed the repository, you would quickly give the server a much bigger workload than it actually needs - particularly as your site grows in size. (I am sure other folks can think of other reasons why you would want to do it the way shown in the tutorial vs. instantiation in each individual action.)
And, then, of course, there is the refactoring issue as I mentioned above. That is about "efficiency of making changes" or improving the maintainability.
Hope that helps you a bit more and better answers your question!

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Too many public methods forced by test-driven development

A very specific question from a novice to TDD:
I separate my tests and my application into different packages. Thus, most of my application methods have to be public for tests to access them. As I progress, it becomes obvious that some methods could become private, but if I make that change, the tests that access them won't work. Am I missing a step, or doing something wrong, or is this just one downfall of TDD?
This is not a downfall of TDD, but rather an approach to testing that believes you need to test every property and every method. In fact you should not care about private methods when testing because they should only exist to facilitate some public portion of the API.
Never change something from private to public for testing purposes!
You should be trying to verify only publicly visible behavior. The rest are implementation details and you specifically want to avoid testing those. TDD is meant to give you a set of tests that will allow you to easily change the implementation details without breaking the tests (changing behavior).
Let’s say I have a type: MyClass and I want to test the DoStuff method. All I care about is that the DoStuff method does something meaningful and returns the expected results. It may call a hundred private methods to get to that point, but I don't care as the consumer of that method.
You don't specify what language you are using, but certainly in most of them you can put the tests in a way that have more privileged access to the class. In Java, for example, the test can be in the same package, with the actual class file being in a different directory so it is separate from production code.
However, when you are doing real TDD, the tests are driving the class design, so if you have a method that exists just to test some subset of functionality, you are probably (not always) doing something wrong, and you should look at techniques like dependency injection and mocking to better guide your design.
This is where the old saying, "TDD is about design," frequently comes up. A class with too many public methods probably has too many responsibilities - and the fact that you are test-driving it only exposes that; it doesn't cause the problem.
When you find yourself in this situation, the best solution is frequently to find some subset of the public methods that can be extracted into a new class ("sprout class"), then give your original class an instance variable of the sprouted class. The public methods deserve to be public in the new class, but they are now - with respect to the API of the original class - private. And you now have better adherence to SRP, looser coupling, and higher cohesion - better design.
All because TDD exposed features of your class that would otherwise have slid in under the radar. TDD is about design.
At least in Java, it's good practice to have two source trees, one for the code and one for the tests. So you can put your code and your tests in the same package, while they're still in different directories:
src/org/my/xy/X.java
test/org/my/xy/TestX.java
Then you can make your methods package private.

Resources