Maintaining Maximum Line Length When Using Tabs Instead of Spaces? - coding-style

Style guides for various languages recommend a maximum line length range of 80–100 characters for readability and comprehension.
My question is, how do people using tabs for indentation comply with the line length limits? Because, if the length of a tab is set to 2 in your editor, the same code could be over 80 characters long in someone else's editor with tab length set to 3/4/6/8.
Some suggest that I mentally see my tab length at 8 characters. This isn't realistic and won't let me focus on programming as I'd have to check it for every other line.
So, how do you (if you use only tabs in your code) do it?

Almost all languages have a convention for tab size. Most projects have a convention for tabs size as well, which is usually (though not always) the same as the language's tab size.
For example, Ruby is 2, Python & PHP is 4, C is 8, etc.
Sticking with the project's tab length, or the language tab size if there is no obvious project tab size, is by far the most sane thing to do, since this what almost all people will use, except perhaps a few.
The ability to set a different tab size is probably the largest advantage of using tabs instead of spaces, and if a user wants to deviate from the standard, then that's fine, but there is no reasonable way to also comply with the maximum line length in every possible situation.
You can compare it to most web sites; they're designed for a 100% zoom level. Zooming in or changing the font size almost always works, but some minor things may break. It's practically impossible to design for every possible zoom level & font size, so artefacts are accepted.
If you want to make sure the code complies to both the line length and tab size, you should probably use spaces, and not "real" tabs. Personally, I feel these guidelines are exactly that: guidelines; and not strict rules, so I don't think it matters that much. Other people's opinion differs on this matter, though.
Personally, I like tabs, for a number of reasons which are not important now, but only deviate from the standard temporarily, usually when editing heavy-nested code where I would like some more clarity which block I'm editing.

You probably don't write very long lines often, so you probably won't have to reformat your code too often.
Therefore, you can use an approach where you periodically check your file for compliance, and fix anything that's out of whack (for example, you could do this before submitting the file to code-review).
Here's a trivially simple Python script that takes a file on stdin and tells you which lines exceed 80 chars:
TABSIZE = 8
MAXLENGTH = 80
for i, line in enumerate(sys.stdin):
if len(line.rstrip('\n').replace('\t', ' '*TABSIZE)) > MAXLENGTH:
print "%d: line exceeds %d characters" % (i+1, MAXLENGTH)
You can extend this in various ways: have it take a filename/directory and automatically scan everything in it, make the tab size or length configurable, etc.

Some editors can be set up to insert a number of spaces equal to your tab length instead of an actual tab (Visual Studio has this enabled by default). This allows you to use the tab key to indent while writing code, but also guarantees that the code will look the same when someone else reads it, regardless of what their tab length may be.
Things get a little trickier if the reader also needs to edit the code, as is the case in pretty much every development team. Teams will usually have tabs vs. spaces and tab length as part of their coding standard. Each developer is responsible for making their own commits align with the standard, generally by setting up their environment to do this automatically. Changes that don't meet the standard can be reverted, and the developer made to fix them before they get integrated.

If you are going to have style guidelines that everyone has to follow then one way to insure that all code conforms to a column width maximum of 100 is to use code formatter such as Clang Format on check-in for example they include a option to set the ColumnLimit:
The column limit.
A column limit of 0 means that there is no column limit. In this case, clang-format will respect the input’s line breaking decisions
within statements unless they contradict other rules.
Once your team agrees to the settings then no one has to think about these details on check-in code formatting will be automatically done. This requires a degree of compromise but once in place you stop thinking about pretty quickly and you just worry about your code rather then formatting.

If you want to ensure you don't go over the limit as prescribed in a team/project coding standard, then it would be irrational to not also have a teamp/project standard for tab width. Modern editors let you set the tab width, so if your team decides and everyone sets their editor to that tab width, everyone will be on the same page.
Think if a line is 100 characters long for you and someone comes by and says it's over because their editor is set to 8 while yours is 2. You could tell them they have the wrong tab width and be making just as valid a point as they could if they told you your tab width was wrong if there's no agreed upon standard. If there's not, the 8-width guy will be wrong when he writes a 100 character line and another developer who prefers 10-width tabs complains.
Where tabs don't inherently have a defined width, it's up to the team to either choose one or choose not to engage in irrational arguments about it.
That said, spaces are shown to be correlated with higher income, so, y'know... ;)

Related

What is a "safe terminal width" these days (2019)?

I'm planning on making a certain kind of plaintext-based manual/whatever, meaning it will be presented using a fixed-width font and a fixed number of characters per line. Now I'm wondering what a "safe" such "line width" (in number of characters) is these days.
My first thought is "80", but I have two concerns with that:
I vaguely remember that 80 isn't safe for e-mail, but has to be 78 for some reason.
80 seems very narrow when there are extremely high-res screens/desktops everywhere. On the other hand, there are also a lot of small "mobile devices", and a major reason I'm using this "primitive" method of presentation over rich HTML or something else is that it's supposed to be easy to read and concise.
120 is what Windows uses by default for cmd.exe, which seems slightly more sane than 80. However, I'm very torn about this.
I'm trying to maximize the compatibility and easiness of reading this content. I'm trying to avoid any kind of problems that might arise from choosing a too narrow or too wide value.
Also, yes, I know that HTML/CSS have all kinds of features for limiting the width and whatnot. However, even e-mail with HTML seems to be very problematic, and CSS appears to still not exactly be mature in terms of typography features.
To make it clear: I'm not asking specifically about e-mail, specifically about web pages, or specifically about any kind of existing medium. I'm trying to make this "universal" so that it can be applied to "any device/platform", excluding only extremely old/obscure/exotic ones which do something really crazy.
You might say that I should be storing it in a database (which I am) and then generate the appropriate format on an on-demand basis, which I might well do, but there's also the "beauty factor" of the presentation of the text. I wish to retain some kind of control at least for the "main" format (plaintext), where I can be sure that the readers are reading it as I intended it, meaning purposedly limited line widths for improved readability and also for the visual beauty of the text content.

What's the point of Incremental Find in Sublime Text?

At the end of this tutorial: https://www.youtube.com/watch?v=ICxMZGLKEbU the author makes it look like the Incremental Find (CTRL+I) is somehow a quicker way to get one's cursor from anywhere in the edited document to some specified place than when using the Regular Find (CTR+F), but I fail to see any difference in the number of steps required. You hit the keys, type a word to which you want to get to, and then either press ENTER (Incremental) or ESCAPE (Regular).
Also, I don't quite see why it's called incremental.
There is a slight difference in between the two functions. With Find (CtrlF), you type in what you're looking for, and each time you hit Enter the next occurrence of the pattern is shown, but it is not a selection in that you can begin typing right away - you need to hit Esc first, and the highlighting is changed to a selection.
With Incremental Find (CtrlI), on the other hand, you start typing in your pattern, and when you hit Enter, the Find highlighting is turned into a selection, the dialog box disappears, and you are immediately able to begin editing the selection. This saves a grand total of one keystroke over the Find method, but has the disadvantage that, unless you hit F3 (Find Next), you are only editing the first instance of the pattern found.
It's kind of a subtle difference, and each one can be used in different situations. Play around with them both and see how each fits into your workflow.
The only functional difference (other than using different keys) is that with incremental search you have the option of either going back to the original (pre-search) cursor position by hitting ESC or staying on the found result by hitting RETURN... whereas the full Find function does not give you the ability to go back to the original position (although you can easily do so with the Goto > Jump Back command after exiting your search).
So in the one very limited use-case of "I want to save 1 keystroke in the event that I want to go back to my original cursor position after searching and seeing what I found but not changing it at all", incremental search has the normal find functionality beat. However, to me this is a detriment because whenever I try incremental search, I wind up hitting that ESCAPE key by accident (because my muscle memory is so used to it from the normal Find functionality) and having to do the search over again.
Hence, practically speaking I think it's best to ignore the existence of Incremental Search. Why bother trying to teach your fingers a separate sequence of keyboard commands and an ever-so-slightly different mental model of how it works (but with no practical difference other than saving 1 keystroke in an edge-case at the expense of triggering it accidentally more often than you want it to actually happen on purpose)?
Historically speaking, I think incremental search is a holdover from older text editors that didn't have search functionality as well-done (IMO) as Sublime. (Actually I think Sublime v2's search interface didn't work as smoothly as v3 does, so maybe it was more helpful back in the old days of Sublime as well?)
The behavior of Ctrl+F copies the behavior of the Find dialog as implemented in the majority of mainstream software. The Incremental search copies Emacs' Incremental search functionality.
The biggest advantage of incremental search is, it shortens the search operation in most cases. Say you want to find "shakespeare". With regular search you must type the whole 11 letters, while with incremental you will most possibly get to the word after typing the first few letters.

Password Mask Character

We have an old 32bit PowerBuilder application (3rd party) that was written for Windows XP and, although it runs under Windows 8, we have noticed that the password masking character is a different sized character (XP is a small black circle and Windows 8 is a larger black circle). This is a problem because the application was written to limit the space available in the password field (22 characters in XP but only 13 in Windows_8). Our password policies require 15-character minimum passwords, and obviously these wont fit when we run the application in Windows 8.
Because the character sizes change with the operating system (not application side), we suspect the problem is with a .dll file or a font that is being referenced by the PowerBuilder application. Are there any ideas where the password mask is being called?
As a workaround, maybe you could be able to type more characters if you increase the edit width?
You could give a try with either uuspy or WinCheat.
If it helps, you could then find a mean to script the send of a WM_SIZE to the control or inject a dll to do so...
I'm afraid you're looking for a complicated solution to a simple problem.
I'm guessing this is a DataWindow-independent (i.e. not inside a DataWindow object) SingleLineEdit. There are generally two reasons you can't type all the characters you want (regardless of the Password attribute) into one of these fields:
You have a non-zero value set in the Limit attribute. However, since your limitation is varying, this likely isn't your culprit.
You have the attribute AutoHScroll (automatic horizontal scroll) set to FALSE (or unchecked in the IDE painters). This means when the field fills up graphically, you can't enter more characters. (This also means, with a variable width font, which most are, you fit more i's into the field than W's; this isn't a good way to go when data length is important. In fact, it's seldom a good way to go at all.)
Your symptom sounds like AutoHScroll is turned off (the default is on when you drop and SLE on the window). Check that back to on, optionally set the Limit attribute to something that makes sense (if the original intention was to constrain the number of characters entered, and it was just implemented poorly), and my guess is that you'll be good to go.
Good luck,
Terry

Performance Issue - How to display very large text file in j2me

I want to display a very large text file but want to break it so that after every 1024 characters shown (page), the user will have to press next to read the next set of characters while back will take them to the exact same previous characters (if any).
Performance wise, am I to create an array of forms and store each 'page' or should the creation of the form be at the point the user presses next or previous?
Performance wise, none of approaches you consider is guaranteed to be problem-free. MIDP 2 specification (JSR-118) does not enforce any specific performance requirements for cases like that. As a result, different devices may behave differently.
To stay on a safe side, you may implement both approaches and let users choose which one works better on their device.
Another option worth considering is to use uneditable TextBox instead of Form. TextBox primary purpose is to display large chunks of text - because of that one may expect that sensible device manufacturers will provide an implementation optimized for that. TextBox even has a method getMaxSize which will let you know if device "thinks" that 1024 characters are too much for it.
Performance wise ?? That would depend on the size no short cut with j2me .... another option is to split the files to smaller chunks.
Reading InputStream ... Use read with offset and length is more efficient
InputStream is = getClass().getResourceAsStream(file);
is.read(b, 0, 1024);
You can add a comment of you need anything else
Thanks
:)

RPG dialogue engine / structure [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 6 years ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I've always been interested in the data structures involved in an RPG (Role-Playing Game). In particular, I'm curious about dialogue and events based actions.
For example: If I approach an NPC at point x in the game, with items y and quests z, how would I work out what the NPC needs to say? Branching dialogue and responding to player input seems as trivial as having a defined script, and user input causes the script reader to jump to a particular line in the script, which has a corresponding set of response lines (much like a choose your own adventure)
However, tying in logic to work out if the player has certain items, and completed certain quests seems to really ruin this script based model.
I'm looking for ideas (not necessarily programming language examples) of how to approach all of this dialogue and logic, and separate it out so that it's very easy to add new branching content, without delving into too much code.
This is really an open question. I don't believe there's a single solution, but it'd be good to get the ball rolling with some ideas. As more of a designer than a programmer, I'm always interested in ways to separate content and code.
For example: If I approach an NPC at
point x in the game, with items y and
quests z, how would I work out what
the NPC needs to say? Branching
dialogue and responding to player
input seems as trivial as having a
defined script, and user input causes
the script reader to jump to a
particular line in the script, which
has a corresponding set of response
lines (much like a choose your own
adventure)
However, tying in logic to work out if
the player has certain items, and
completed certain quests seems to
really ruin this script based model.
Not at all. You simply factor the conditionals into the data.
Let's say you have your list of dialogues, numbered 1 to 400 or whatever like the Choose Your Own Adventure book examples. I assume each dialogue may consist of the text spoken by the NPC, followed by a list of responses available to the player.
So the next step is to add the conditionals in there, by simply attaching conditions to each response. The easiest way is to do this with a scripting language, so you have a short and simple piece of code that returns True if this response is available to the player and False if it is not.
eg. (XML format, but could be anything)
<dialogue id='1'>
<text>
Couldst thou venture forth and kill me 10 rats, perchance?
</text>
<response condition="True" nextDialogue='2'>
Verily! Naught could be better than slaying thy verminous foes. Ten ratty
carcasses shall I bring unto thee.
</text>
<response condition="rats_left_in_world() < 10" nextDialogue='3'>
Nay, brother! Had thou but ten rats remaining, my sword would be thine,
but tis not to be.
</response>
</dialogue>
In your scripting language, you'd need a 'rats_left_in_world' function that you can call to retrieve the value in question.
What if you have no scripting language? Well, you could have the programmer code an individual condition for each situation in your dialogue - a bit tedious, not all that difficult if your dialogue is written up-front. Then just refer to a condition by name in the conversation script.
A more advanced scheme, still not requiring a scripting language, might use a tag for each condition, like so:
<response>
<condition type='min_level' value='50'/>
Sadly squire, my time is too valuable for the likes of thee. Get thyself a
farm hand or stable boy to do thy bidding!
</response>
You can add as many conditions in there as you need, as long as they can be easily specified with one or two values. If all conditions are met, the response is available.
It's interesting, there's seems to be a core idea being missed here. We're having a discussion that relates to a programmer performing the task. Indeed, the code examples above are coupled to code, not content.
In game development, it's the content developers that we programmers want to empower. They will not (this is very important) look at code. Period. Now and again you get a technical artist or technical designer, and they're wonderful and don't mind it; but, the majority of content authors are not technically inclined.
I understand the question is for your own edification; but, it should be pointed out that, in industry, when we solve these types of problems our end users (the people utilizing the technology we're developing) are not engineers.
A system like this (branching dialogue) requires a representation in a tool that is relatively intuitive to use. For example, Unreal's Kismet visual scripting system could be utilized.
Essentially, the data structures (more than likely a branching tree as it's easy to represent/debug/etc.) would be crafted by a programmer, as would the nodes that represent the object in script. The system with its ability to link to world objects (more than likely also represented by nodes in visual scripting), etc. would then be crafted and the whole kitten caboodle linked together in some glorious bit of elegant code.
After all of that, a designer would actually be able to build a visual representation of the dialogue branching in the visual scripting language. This would be map-encounter specific, more than likely. Of course, you could procedurally generate these; but, that's more of a programmer desire than a designer's.
Just thought I'd add that bit of knowledge and insight.
EDIT: Noticed there's an XML example. I'm not sure what other designers/artists/etc. feel about it; but, the ones I've worked with cringe at the idea of touching a text file.
I'd venture to say that most modern games (be they RPGs, action games, anything above basic card/board games) generally consist of several components: The display engine, the core data structures, and typically a secondary scripting engine. One example which was popular for a time (and may still be; I haven't even spoken to a game developer in years) was Lua.
The decision-making you're talking about (events, conversation branches, etc) is typically handled by the secondary scripting engine, as the scripting languages are more flexible and typically easier to use for the game's designers. Again, most of the real story-driven or game-driving logic will actually happen here, where it can be swapped out and changed relatively easily. (At least, compared to running a full build of all the code!)
The primary game engine combines the data structures related to the world (geometry, etc), the data structures related to the player(s) and other actor(s) needed, and the scripts to drive the encounters, and uses all of that to display the final, integrated environment.
You can certainly use a scripting language to handle dialogue. Basically a script might look like this:
ShowMessage("Hello " + hero.name + ", how can I help you?")
choices = { "Open the door for me", "Tell me about yourself", "Nevermind" }
chosen = ShowChoices(choices)
if chosen == 0
if hero.inventory["gold key"] > 0
ShowMessage("You have the key! I'll open the door for you!")
isGateOpen = true
else
ShowMessage("I'm sorry, but you need the gold key")
end if
else if chosen == 1
if isGateOpen
ShowMessage("I'm the gate keeper, and the gate is open")
else
ShowMessage("I'm the gate keeper and you need gold key to pass")
end if
else
ShowMessage("Okay, tell me if you need anything")
end if
This is fine for most games. The scripting language can be simple and you can write more complicated logical branches. Your engine will have some representation of the world that is exposed to the scripting language. In this example, this means the name of the hero and the items in the inventory, but you could expose anything you like. You also define functions that could be called by scripts to do things like show a message or play some sound effect. You need to keep track of some global data that is shared between scripts, such as whether a door is open or a quest is done (perhaps as part of the map and quest classes).
In some games however, scripting could get tedious, especially if the dialogue is more dynamic and depends on many conditions (say, character mood and stats, npc knowledge, weather, items, etc.) Here it is possible to store your dialogue tree in some format that allows easily specifying preconditions and outcomes. I don't know if this is the way to do it, but I've once asked a question about storing game logic in XML files. I've found this approach to be effective for my game (in which dialogue is heavily dependent on many factors). In particular, in the future I could easily make a simple dialogue editor that doesn't require much scripting and allow you to simply define dialogue and branches with a graphical user interface.
I recently had to develop something for this, and opted for a very basic text file structure. You can see the resulting code and text format at:
https://github.com/scottbw/dialoguejs
There is a tradeoff between sophistication of scripting and ease of editing for non-programmers.
I've opted for a very simple solution for the dialogue, and handle triggering of related game events separately in a secondary scripting language.
Eventually I might add some way of adding "stage directions" to the text dialogue format that are used to trigger events in the secondary scripting engine, but again without needing to put anything that looks like code in the dialogue file itself.
That's an excellent questions. I had to solve that a few times for clients. We started with an XML structure quite similar to yours, and now we use JSON. You can see an example here: http://www.branchtrack.com/projects/on029pq6.json or https://dl.dropboxusercontent.com/u/11433463/branchtrack/on029pq6.json (prettify it for readability).
Full disclosure: the link above is generated in BranchTrack, an online editor for branching dialogues, and I am the CEO. Feel free to ask anything.
I recently tackled a problem like this while making Chat Mapper. What I do is graphically plot out the dialogues as nodes in a tree and then each node has a condition and a script associated with them. As you traverse through the tree and hit a node, you check the condition to see whether or not that node is valid, and if it is, you execute the script associated with that node. It's a fairly simple idea but seems to work well from our testing. We are using a .NET Lua interpreter for the scripts.
For my solution I developed a custom text file format consisting of seven lines of text per node. Each line can be a strided list or just a text line. Each node has a position number. The last digit of the number is a type, so there are 10 different types of nodes, such as fresh questions, confirmations, repeating actions based on prior results, etc.
Each dialog activation begins with a select query to the data store whose results can be compared against members of a strided list, to match up with the appropriate node. This is more brutal than an if/then but it makes the text config file smaller since you don't need any syntax besides the stride separator. I use a system of wildcards to allow for select query results to be able to be inserted into the speech of the NPC.
Lastly there are API hooks to allow custom scripts to interface in, in case the easy config file is not enough. I plan to make a web app gui in nodejs to allow people to visually script the config files :D

Resources