I am new to Salesforce apex coding. My first class that I am developing has 10 methods and is some 800 lines.
I haven’t added much of exception handling, so the size should swell further.
I am wondering, what the best practice for Apex code is... should I create 10 classes with 1 method instead of letting 1 class with 10 methods.
Any help on this would be greatly appreciated.
Thanks
Argee
What do you use for coding? Try to move away from Developer Console. VSCode has some decent plugins like Prettier or Apex PMD that should help you with formatting and making methods too complex. ~80 lines/method is so-so. I'd worry about passing long lists of parameters and having deeply nested code in functions rather than just their length.
There are general guidelines (from other languages, there's nothing special about Apex!) that ideally function should fit on 1 screen so programmer can see it whole without scrolling. Read this one, maybe it'll resonate with you: https://dzone.com/articles/rule-30-%E2%80%93-when-method-class-or
I wouldn't split it into separate files just for sake of it, unless you can clearly define some "separation of concerns". Say 1 trigger per object, 1 trigger handler class (ideally derived from base class). Chunkier bits not in the handler but maybe in some "service" style class that has public static methods and can operate whether called from trigger, visualforce, lightning web component, maybe some one-off data fix would need these, maybe in future you'd need to expose part of it as REST service. And separate file for unit tests (as blasphemous as it sounds - try to not write too many comments. As you're learning you'll need comments to remind yourself what built-in methods do but naming your functions right can help a lot. And a well-written unit test is better at demonstrating the idea behind the code, sample usage and expected errors than comments that can be often overlooked).
Exception handling is an art. Sometimes it's good to just let it throw an exception. If you have a method that creates Account, Contact and Opportunity and say Opportunity fails on validation rule - what should happen? Only you will know what's good. Exception will mean the whole thing gets rolled back (no "widow" Accounts) which sucks but it's probably "more stable" state for your application. If you naively try-catch it without Database.rollback() - how will you tell user to not create duplicates with 2nd click. So maybe you don't need too much error handling ;)
I wish to generate automated messages that are associated with a finite (>20, < 100) number of types:
class Message(models.Model):
MSG_CHOICES = (
('MEETING', 'Meeting Reminder'),
('STATUS', 'Status Change Reminder'),
...
)
message = models.CharField(max_length=100)
msg_type = models.CharField(max_length=10, choices=MSG_CHOICES)
The actual message of each will depend on the type and arguments I must feed it at some point. For example, a 'MEETING' message will basically be:
"Hi, you have a meeting at %s with %s." % (time, person_to_meet)
while a 'STATUS' message will be something like
"Hi, this is a reminder that you changed your %s status to %s." % (status_type, new_status)
Now, the complexity here is that we have to render the message differently for the different types. Here's my attempt at brainstorming some different approaches:
revamp the model to have a base message model and a derived one for each, with its own type of constructor, saving the "string templates" inside the constructors for each model. This fits the pattern of separating models with different logic (and I'd usually do this for a model of different "types"), but feels clunky because besides the logic of creating the messages, these guys are basically the same. The only difference in logic comes from creating the messages themselves, and it seems like a waste to split just because of it.
keep the model as is, create class methods in the code to make a factory for each type, saving the "string templates" inside the class (or even inside the database). This is the easiest, but it feels dirty.
this is the creative/crazy one (hence the title): keep the model as is, and save the string templates as actual template files. In the constructors, use the Django template library to render those files and return the strings. This seems good because it separates out hard-coded data from code-logic, but it feels wonky since I'm using templates at two different levels of the code (one for making models and one for the views). It "feels" wrong but I can't really pinpoint why.
So the main questions:
What is the best-practice for this situation? Is it one of these or is it some other approach?
is there a "model" example of this practice somewhere? I feel lots of systems generate automated alerts/messages, so if one has particularly good code I'd like to look at it.
Thanks!
-Yan
IMHO, you shouldn't be storing the message in the db at all. You are storing the msg_type. That should really be enough. Your logic to display the information to the user (via the template) should handle this. This would allow you to localize the message if you needed to at some point in the future based on the Accept-Language header. In my experience, it's a bad idea to store user messages in the db. And, at least to my way of thinking, it's not really true business logic. It seems to belong in the UI layer. Ok. Just my opinion on it. This question is pretty old. I would be curious to read what you ultimately ended up doing here.
This is in C Language
I want to know how i can write a program to lookup all the input fields of a website. Any website. and then can fill them in. I can write the simple webbrowser in vbs but how can i analyse the input fields. even better would be is i could click the lookup field and it puts the name of it in a box..... that would be ideal.
Anyone can help? thanks :)
Are you sure you want to do this in C?
I ask because it is not easy. First of all, you need to be able to run the HTTP GET request against the webpage you wish to view. For this, you probably need libcurl; you definitely don't want to be writing from scratch at any rate.
Next, you need to process the html you get, finding all input fields. You do NOT want to do this using regular expressions, if anything for the sake of bobince's blood pressure. HTML is not a regular language is the bit you need to take away - you need an xml parser. Enter libxml. I'm sure there are other xml libraries out there, and even libraries for parsing html.
Finally, having done that (got the fields etc) you need to be able to populate them and submit the correct request as per the ACTION and METHOD parameters of the FORM.
This is of course assuming you know what the fields should be formatted with. And it also assumes nothing else is going on. If you have a javascript validated web form (I sincerely hope they're validating on the request too, but they might provide feedback via JS) you won't benefit from that (unless you're going to integrate JS, in which case you might as well write a browser).
This is not a trivial task and it is the reason there are accessibility standards for HTML, because otherwise it becomes tricky to interpret the form without human interaction.
Of course, this all assumes said html is well formed, which isn't always the case...
I might suggest another approach. BeautifulSoup is a well known Python web scraping library that works very well. Python as a language allows easier string manipulation too, which will dramatically cut down your development time. I'd suggest giving the need to use C some serious thought given the size and complexity of the task you want to undertake vs your need to get a result quickly. If you have a lot of time, by all means go for C.
Weird question, but I'm not sure if it's anti-pattern or not.
Say I have a web app that will be rendering 1000 records to an html table.
The typical approach I've seen is to send a query down to the database, translate the records in some way to some abstract state (be it an array, or a object, etc) and place the translated records into a collection that is then iterated over in the view.
As the number of records grows, this approach uses up more and more memory.
Why not send along with the query a callback that performs an operation on each of the translated rows as they are read from the database? This would mean that you don't need to collect the data for further iteration in the view so the memory footprint shrinks, and you're not iterating over the data twice.
There must be something implicitly wrong with this approach, because I rarely see it used anywhere. What's wrong with this approach?
Thanks.
Actually, this is exactly how a well-developed application should behave.
There is nothing wrong with this approach, except that not all database interfaces allow you to do this easily.
If we talk about tabularizing 10 records for a yet another social network, there is no need to mess with callbacks if you can get an array of hashes or whatever with a single call that is already implemented for you.
There must be something implicitly wrong with this approach, because I rarely see it used anywhere.
I use it. Frequently. Even when i wouldn't use too much memory repeatedly copying the data, using a callback just seems cleaner. In languages with closures, it also lets you keep relevant code together while factoring out the messy DB stuff.
This is a "limited by your tools" class of problem: Most programming languages don't allow to say "Do something around this code". This was solved in recent years with the advent of closures. Think of a closure as a way to pass code into another method which is then executed in a context. For example, in GSQL, you can write:
def l = []
sql.execute ("select id from table where time > ?", time) { row ->
l << row[0]
}
This will open a connection to the database, create a statement and a result set and then run the l << it[0] for each row the DB returns. Note that the code runs inside of sql.execute() but it can access local variables (l) and variables defined in sql.execute() (row).
With this kind of code, you can even generate the result of a HTTP request on the fly without keeping much of the page in RAM at any time. In my case, I'd stream a 2MB document to the browser using only a few KB of RAM and the browser would then chew 83s to parse this.
This is roughly what the iterator pattern allows you to do. In many cases this breaks down on the interface between your application and the database. Technologies like LINQ even have solutions that can send back code to the database.
I've found it easier to use an interface resolver than deep callback where its hooked up through several classes. MS has a much fancier version than mine called Unity. This provides a much cleaner way of accessing classes that should not be tightly coupled
http://www.codeplex.com/unity
Which naming convention do you use and why?
I like to use employeeNameTextBox, because:
It seems more natural from an English language perspective.
I find it's easier to look up with Intellisense.
The convention is similar to the convention used for events (MouseClickEvent, MouseClickEventHandler) and dependency properties (VisiblityProperty).
Note: I am using the full name rather than an abbreviation (such as "tb"), because it is in line with MS's naming conventions that say to avoid using abbreviations.
http://msdn.microsoft.com/en-us/library/ms229045.aspx
The only reason to use the control type in the name first (textBoxEmployeeName) is for easier grouping with Intellisense (All textbox controls would then show up together). Beyond that, there really is no benefit to using that way. I find the second way (employeeNameTextBox) more readable and prefer that way personally, but a lot of people will still go with the control type first, since that is the way it was done for a long time.
Naming your variables is so important. Thick client view conventions seem to be given the short end of the stick. Here are my thoughts:
Never put getters and setters for actual business values on your view. Don't do this:
public Name EmployeeName { get; set; }
To get or set an EmployeeName, your stateful code should explicitly call a method. Do it this way because it projects that the state is not stored on the view, but can be derived from or transposed to the view:
public void SetEmployeeName(Name employeeName);
public Name GetEmployeeName();
Hungarian notation is stupid. It was useful in languages <= VB6 because they used late binding of variable types. You had to protect yourself because type mismatches were runtime errors, not compile time. Only use txtEmployeeName if you also would use strEmployeeName and intEmployeeNumber.
If prefixing the pattern name isn't consistent with your naming convention, don't do it for the control type (which represents a pattern). If you wouldn't create a commandNameFormatting (instead of nameFormattingComamnd), then don't create a textBoxEmployeeName.
You'll probably need a suffix of some sort, since EmployeeName doesn't sufficiently describe the variable's purpose. An EmployeeName text box's purpose is to receive input. You could call it EmployeeNameTextBox if that makes you comfortable, but it might be better to call it EmployeNameInput. This has the added bonus that if you have a label, it's clear that EmployeeNamePrompt (or EmployeeNameLabel) is not the same as the text box. Without some sort of descriptive suffix, you don't have a good way to differentiate.
I (almost) always use [controltype][descriptive name]. I want to know right away what type of control I'm dealing with when I look at code, and if I DON'T remember the name, intellisense can help me out.
Just using a descriptive name (EmplyeeName) doesn't work for me. What type of control? Is it a label, a text box, or a combo box? Or a string? Or a file? It's important enough that the type of control or variable is always a part of it.
I propose a third option: uiEmployeName. Reasons:
It's not Hungarian. Both of the notations you mention are just flavors of Hungarian.
If you change an employee name text box over to a listbox you don't need to rename your variables.
Everything is grouped nicely in the intellisense without involving the type of the object.
The name of the object closely follows its function. It is a user-facing object that gets the employee name.
I generally try to keep the element type short, followed by a distinguishing label. I find that it quickly communicates the type and purpose of the element:
txtEmployeeName;
lblEmployeeName;
Why not EmployeeName? Seriously how does the control type as part of the name when it is already provided by your IDE assist in delivering easy to maintain code? Consider Ottenger's Rules for Variable and class Naming
K
As I read it, an article linked to in the article mentioned in the question (namely, Names of Resources) does use the control type at the end, in FileMenu (and ArgumentException though it's not a control).
My personal opinion is that this is also more readable, as it's the employee name text box and hence should be named the employeeNameTextBox, just like the words "File menu" are read in that order. (Though I substitute "Edit" for "TextBox" for brevity — I should probably kick that habit to use control names consistently with the environment name for them.)
A MUST READ is the XAML Guidelines released by Jaime:
Also read more here
WPF-specific Answer: No name at all.
Why? Because if you're developing using WPF you should not be naming your controls. If you are, you are doing something wrong.
WinForms required controls to be named because its data binding was so weak. WPF solves all that: The control itself can specify its data and behavior, so there is no need to name it.
I guess it's better to follow Microsoft's Object Naming Convention for naming your controls both in C# as well as Visual Basic.
I don't recommend hungarian notation in any form. textBoxEmployeeName is a form of hungarian notation. So I support the use of employeeNameTextBox.
Personally I don't even bother using the word TextBox, because it is not what is important about the variable. What is important is "Employee" and "Name". Not only does adding the word TextBox lock you in to a certain type, it also make it much harder to change that type, because you need to change the name to normalize your code and make it correct. Say for some reason you started this as a TextBox, but you later received a requirement to change this to a DropDownList or some other type, now you have to update all of your code and JavaScript to make it say DropDownList instead of TextBox.
It is much easier to forget about trying to type your variable names, and just simply name them. You have intellisense and compile time error checking for a reason, why not use it.
I would go with [controlType][DomainTerm] which in this case is textBoxEmployeeName. The reason is that while coding for the C# code behind you are more care about the UI controls than the domain specific terms.UI(View) side coding we need to identify/recognize the control type faster, which is little more important than the domain specific name in the View side , and since we read from 'Left to right' this naming convention is relevant.
I generally use txtEmployeeName or cmpEmployeeType , but textBox instead of txt is preferred as per MS guidelines
I have used both txtEmployeeName and employeeNameTextbox. Like many of the posts indicated, this is helpful for grouping. One groups by control types (txtEmployeeName, txtManagerName) while the other can group different related controls together (employeeNameTextbox, employeePhoneTextbox, managerNameTextBox, managerPhoneTextbox). In many cases I find the later more useful while coding.
You should do whatever it is that makes your code readable and self-documenting. Following hard and fast rules is always a mistake because they almost never cover all aspects of what needs to be done. There is nothing wrong with having guidelines (such as not using Hungarian notation), but it is more important that you are consistent and clear with your naming convention, whatever it is, than you follow some rules found on the Internet.
Ideas:
Avoid encodings/abbreviations.
The name should stand out from
similar names in the same scope.
Make the unique-most part the
left-most part. I suspect you have
several text boxes, but only one is
the employee name.
Avoid needless context. Are all the
names on this page about employees?
Is it an "employee" page? Then
EmployeeName is redundant. NameBox
or NameControl should be plenty.
Avoid needless context: do you have
names that are not controls? If so,
"Box", or "Control" is useful,
otherwise not so much.
Disclosure: I am the "ottinger" from "ottingers naming rules", which also evolved to be chapter 2 of "Clean Code". See short form at http://agileinaflash.blogspot.com/2009/02/meaningful-names.html
In VB I actually like to go with [ControlName]_[ControlType]. I can't remember how I started doing that but I suppose it's because it feels like a logical order. It also simplifies coding a bit because the code suggestions are grouped by the control description rather than the control type.
I name controls the same way in C# except I follow C#'s preference for camelCase: [controlName]_[controlType].
I also tend to use my own abbreviations for control types, though they are not vague.
Examples:
VB: Save_Btn and NewFile_MItem (menu item)
C#: save_btn and newFile_mItem
It works for me, but of course every programmer has their style.